Debian Codegraph @

ansible_collections/community/general/plugins/modules/hwc_vpc_private_ip.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2019 Huawei
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 ###############################################################################
10 # Documentation
11 ###############################################################################
12
13 DOCUMENTATION = r"""
14 module: hwc_vpc_private_ip
15 description:
16 - VPC private IP management.
17 short_description: Creates a resource of VPC/PrivateIP in Huawei Cloud
18 notes:
19 - If O(id) option is provided, it takes precedence over O(subnet_id), O(ip_address) for private IP selection.
20 - O(subnet_id), O(ip_address) are used for private IP selection. If more than one private IP with this options exists, execution
21 is aborted.
22 - No parameter support updating. If one of option is changed, the module creates a new resource.
23 version_added: '0.2.0'
24 author: Huawei Inc. (@huaweicloud)
25 requirements:
26 - keystoneauth1 >= 3.6.0
27 attributes:
28 check_mode:
29 support: full
30 diff_mode:
31 support: none
32 options:
33 state:
34 description:
35 - Whether the given object should exist in Huawei Cloud.
36 type: str
37 choices: ['present', 'absent']
38 default: 'present'
39 subnet_id:
40 description:
41 - Specifies the ID of the subnet from which IP addresses are assigned. Cannot be changed after creating the private
42 IP.
43 type: str
44 required: true
45 ip_address:
46 description:
47 - Specifies the target IP address. The value can be an available IP address in the subnet. If it is not specified, the
48 system automatically assigns an IP address. Cannot be changed after creating the private IP.
49 type: str
50 extends_documentation_fragment:
51 - community.general._hwc
52 - community.general._attributes
53 """
54
55 EXAMPLES = r"""
56 # create a private IP
57 - name: Create vpc
58 hwc_network_vpc:
59 cidr: "192.168.100.0/24"
60 name: "ansible_network_vpc_test"
61 register: vpc
62 - name: Create subnet
63 hwc_vpc_subnet:
64 gateway_ip: "192.168.100.32"
65 name: "ansible_network_subnet_test"
66 dhcp_enable: true
67 vpc_id: "{{ vpc.id }}"
68 cidr: "192.168.100.0/26"
69 register: subnet
70 - name: Create a private IP
71 community.general.hwc_vpc_private_ip:
72 subnet_id: "{{ subnet.id }}"
73 ip_address: "192.168.100.33"
74 """
75
76 RETURN = r"""
77 subnet_id:
78 description:
79 - Specifies the ID of the subnet from which IP addresses are assigned.
80 type: str
81 returned: success
82 ip_address:
83 description:
84 - Specifies the target IP address. The value can be an available IP address in the subnet. If it is not specified, the
85 system automatically assigns an IP address.
86 type: str
87 returned: success
88 """
89
90 from ansible_collections.community.general.plugins.module_utils._hwc_utils import (
91 Config,
92 HwcClientException,
93 HwcModule,
94 are_different_dicts,
95 build_path,
96 get_region,
97 is_empty_value,
98 navigate_value,
99 )
100
101
102 def build_module():
103 return HwcModule(
104 argument_spec=dict(
105 state=dict(default="present", choices=["present", "absent"], type="str"),
106 subnet_id=dict(type="str", required=True),
107 ip_address=dict(type="str"),
108 ),
109 supports_check_mode=True,
110 )
111
112
113 def main():
114 """Main function"""
115
116 module = build_module()
117 config = Config(module, "vpc")
118
119 try:
120 resource = None
121 if module.params["id"]:
122 resource = True
123 else:
124 v = search_resource(config)
125 if len(v) > 1:
126 raise Exception(f"Found more than one resource({', '.join([navigate_value(i, ['id']) for i in v])})")
127
128 if len(v) == 1:
129 resource = v[0]
130 module.params["id"] = navigate_value(resource, ["id"])
131
132 result = {}
133 changed = False
134 if module.params["state"] == "present":
135 if resource is None:
136 if not module.check_mode:
137 create(config)
138 changed = True
139
140 current = read_resource(config, exclude_output=True)
141 expect = user_input_parameters(module)
142 if are_different_dicts(expect, current):
143 raise Exception(
144 f"Cannot change option from ({current}) to ({expect})of an existing resource.({module.params.get('id')})"
145 )
146
147 result = read_resource(config)
148 result["id"] = module.params.get("id")
149 else:
150 if resource:
151 if not module.check_mode:
152 delete(config)
153 changed = True
154
155 except Exception as ex:
156 module.fail_json(msg=str(ex))
157
158 else:
159 result["changed"] = changed
160 module.exit_json(**result)
161
162
163 def user_input_parameters(module):
164 return {
165 "ip_address": module.params.get("ip_address"),
166 "subnet_id": module.params.get("subnet_id"),
167 }
168
169
170 def create(config):
171 module = config.module
172 client = config.client(get_region(module), "vpc", "project")
173 opts = user_input_parameters(module)
174
175 params = build_create_parameters(opts)
176 r = send_create_request(module, params, client)
177 module.params["id"] = navigate_value(r, ["privateips", "id"], {"privateips": 0})
178
179
180 def delete(config):
181 module = config.module
182 client = config.client(get_region(module), "vpc", "project")
183
184 send_delete_request(module, None, client)
185
186
187 def read_resource(config, exclude_output=False):
188 module = config.module
189 client = config.client(get_region(module), "vpc", "project")
190
191 res = {}
192
193 r = send_read_request(module, client)
194 res["read"] = fill_read_resp_body(r)
195
196 return update_properties(module, res, None, exclude_output)
197
198
199 def _build_query_link(opts):
200 query_link = "?marker={marker}&limit=10"
201
202 return query_link
203
204
205 def search_resource(config):
206 module = config.module
207 client = config.client(get_region(module), "vpc", "project")
208 opts = user_input_parameters(module)
209 identity_obj = _build_identity_object(opts)
210 query_link = _build_query_link(opts)
211 link = build_path(module, "subnets/{subnet_id}/privateips") + query_link
212
213 result = []
214 p = {"marker": ""}
215 while True:
216 url = link.format(**p)
217 r = send_list_request(module, client, url)
218 if not r:
219 break
220
221 for item in r:
222 item = fill_list_resp_body(item)
223 if not are_different_dicts(identity_obj, item):
224 result.append(item)
225
226 if len(result) > 1:
227 break
228
229 p["marker"] = r[-1].get("id")
230
231 return result
232
233
234 def build_create_parameters(opts):
235 params = dict()
236
237 v = navigate_value(opts, ["ip_address"], None)
238 if not is_empty_value(v):
239 params["ip_address"] = v
240
241 v = navigate_value(opts, ["subnet_id"], None)
242 if not is_empty_value(v):
243 params["subnet_id"] = v
244
245 if not params:
246 return params
247
248 params = {"privateips": [params]}
249
250 return params
251
252
253 def send_create_request(module, params, client):
254 url = "privateips"
255 try:
256 r = client.post(url, params)
257 except HwcClientException as ex:
258 msg = f"module(hwc_vpc_private_ip): error running api(create), error: {ex}"
259 module.fail_json(msg=msg)
260
261 return r
262
263
264 def send_delete_request(module, params, client):
265 url = build_path(module, "privateips/{id}")
266
267 try:
268 r = client.delete(url, params)
269 except HwcClientException as ex:
270 msg = f"module(hwc_vpc_private_ip): error running api(delete), error: {ex}"
271 module.fail_json(msg=msg)
272
273 return r
274
275
276 def send_read_request(module, client):
277 url = build_path(module, "privateips/{id}")
278
279 r = None
280 try:
281 r = client.get(url)
282 except HwcClientException as ex:
283 msg = f"module(hwc_vpc_private_ip): error running api(read), error: {ex}"
284 module.fail_json(msg=msg)
285
286 return navigate_value(r, ["privateip"], None)
287
288
289 def fill_read_resp_body(body):
290 result = dict()
291
292 result["id"] = body.get("id")
293
294 result["ip_address"] = body.get("ip_address")
295
296 result["subnet_id"] = body.get("subnet_id")
297
298 return result
299
300
301 def update_properties(module, response, array_index, exclude_output=False):
302 r = user_input_parameters(module)
303
304 v = navigate_value(response, ["read", "ip_address"], array_index)
305 r["ip_address"] = v
306
307 v = navigate_value(response, ["read", "subnet_id"], array_index)
308 r["subnet_id"] = v
309
310 return r
311
312
313 def send_list_request(module, client, url):
314 r = None
315 try:
316 r = client.get(url)
317 except HwcClientException as ex:
318 msg = f"module(hwc_vpc_private_ip): error running api(list), error: {ex}"
319 module.fail_json(msg=msg)
320
321 return navigate_value(r, ["privateips"], None)
322
323
324 def _build_identity_object(all_opts):
325 result = dict()
326
327 result["id"] = None
328
329 v = navigate_value(all_opts, ["ip_address"], None)
330 result["ip_address"] = v
331
332 v = navigate_value(all_opts, ["subnet_id"], None)
333 result["subnet_id"] = v
334
335 return result
336
337
338 def fill_list_resp_body(body):
339 result = dict()
340
341 result["id"] = body.get("id")
342
343 result["ip_address"] = body.get("ip_address")
344
345 result["subnet_id"] = body.get("subnet_id")
346
347 return result
348
349
350 if __name__ == "__main__":
351 main()