Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (C) 2018 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_network_vpc
15 description:
16 - Represents an vpc resource.
17 short_description: Creates a Huawei Cloud VPC
18 author: Huawei Inc. (@huaweicloud)
19 requirements:
20 - requests >= 2.18.4
21 - keystoneauth1 >= 3.6.0
22 attributes:
23 check_mode:
24 support: full
25 diff_mode:
26 support: none
27 options:
28 state:
29 description:
30 - Whether the given object should exist in VPC.
31 type: str
32 choices: ['present', 'absent']
33 default: 'present'
34 timeouts:
35 description:
36 - The timeouts for each operations.
37 type: dict
38 default: {}
39 suboptions:
40 create:
41 description:
42 - The timeout for create operation.
43 type: str
44 default: '15m'
45 update:
46 description:
47 - The timeout for update operation.
48 type: str
49 default: '15m'
50 delete:
51 description:
52 - The timeout for delete operation.
53 type: str
54 default: '15m'
55 name:
56 description:
57 - The name of vpc.
58 type: str
59 required: true
60 cidr:
61 description:
62 - The range of available subnets in the VPC.
63 type: str
64 required: true
65 extends_documentation_fragment:
66 - community.general._hwc
67 - community.general._attributes
68 """
69
70 EXAMPLES = r"""
71 - name: Create a vpc
72 community.general.hwc_network_vpc:
73 identity_endpoint: "{{ identity_endpoint }}"
74 user: "{{ user }}"
75 password: "{{ password }}"
76 domain: "{{ domain }}"
77 project: "{{ project }}"
78 region: "{{ region }}"
79 name: "vpc_1"
80 cidr: "192.168.100.0/24"
81 state: present
82 """
83
84 RETURN = r"""
85 id:
86 description:
87 - The ID of VPC.
88 type: str
89 returned: success
90 name:
91 description:
92 - The name of VPC.
93 type: str
94 returned: success
95 cidr:
96 description:
97 - The range of available subnets in the VPC.
98 type: str
99 returned: success
100 status:
101 description:
102 - The status of VPC.
103 type: str
104 returned: success
105 routes:
106 description:
107 - The route information.
108 type: complex
109 returned: success
110 contains:
111 destination:
112 description:
113 - The destination network segment of a route.
114 type: str
115 returned: success
116 next_hop:
117 description:
118 - The next hop of a route. If the route type is peering, it provides VPC peering connection ID.
119 type: str
120 returned: success
121 enable_shared_snat:
122 description:
123 - Show whether the shared SNAT is enabled.
124 type: bool
125 returned: success
126 """
127
128 ###############################################################################
129 # Imports
130 ###############################################################################
131
132 import re
133
134 from ansible_collections.community.general.plugins.module_utils._hwc_utils import (
135 Config,
136 HwcClientException,
137 HwcClientException404,
138 HwcModule,
139 are_different_dicts,
140 build_path,
141 get_region,
142 is_empty_value,
143 navigate_value,
144 wait_to_finish,
145 )
146
147 ###############################################################################
148 # Main
149 ###############################################################################
150
151
152 def main():
153 """Main function"""
154
155 module = HwcModule(
156 argument_spec=dict(
157 state=dict(default="present", choices=["present", "absent"], type="str"),
158 timeouts=dict(
159 type="dict",
160 options=dict(
161 create=dict(default="15m", type="str"),
162 update=dict(default="15m", type="str"),
163 delete=dict(default="15m", type="str"),
164 ),
165 default=dict(),
166 ),
167 name=dict(required=True, type="str"),
168 cidr=dict(required=True, type="str"),
169 ),
170 supports_check_mode=True,
171 )
172 config = Config(module, "vpc")
173
174 state = module.params["state"]
175
176 if (not module.params.get("id")) and module.params.get("name"):
177 module.params["id"] = get_id_by_name(config)
178
179 fetch = None
180 link = self_link(module)
181 # the link will include Nones if required format parameters are missed
182 if not re.search("/None/|/None$", link):
183 client = config.client(get_region(module), "vpc", "project")
184 fetch = fetch_resource(module, client, link)
185 if fetch:
186 fetch = fetch.get("vpc")
187 changed = False
188
189 if fetch:
190 if state == "present":
191 expect = _get_editable_properties(module)
192 current_state = response_to_hash(module, fetch)
193 current = {"cidr": current_state["cidr"]}
194 if are_different_dicts(expect, current):
195 if not module.check_mode:
196 fetch = update(config, self_link(module))
197 fetch = response_to_hash(module, fetch.get("vpc"))
198 changed = True
199 else:
200 fetch = current_state
201 else:
202 if not module.check_mode:
203 delete(config, self_link(module))
204 fetch = {}
205 changed = True
206 else:
207 if state == "present":
208 if not module.check_mode:
209 fetch = create(config, "vpcs")
210 fetch = response_to_hash(module, fetch.get("vpc"))
211 changed = True
212 else:
213 fetch = {}
214
215 fetch.update({"changed": changed})
216
217 module.exit_json(**fetch)
218
219
220 def create(config, link):
221 module = config.module
222 client = config.client(get_region(module), "vpc", "project")
223
224 r = None
225 try:
226 r = client.post(link, resource_to_create(module))
227 except HwcClientException as ex:
228 msg = f"module(hwc_network_vpc): error creating resource, error: {ex}"
229 module.fail_json(msg=msg)
230
231 wait_done = wait_for_operation(config, "create", r)
232 v = ""
233 try:
234 v = navigate_value(wait_done, ["vpc", "id"])
235 except Exception as ex:
236 module.fail_json(msg=str(ex))
237
238 url = build_path(module, "vpcs/{op_id}", {"op_id": v})
239 return fetch_resource(module, client, url)
240
241
242 def update(config, link):
243 module = config.module
244 client = config.client(get_region(module), "vpc", "project")
245
246 r = None
247 try:
248 r = client.put(link, resource_to_update(module))
249 except HwcClientException as ex:
250 msg = f"module(hwc_network_vpc): error updating resource, error: {ex}"
251 module.fail_json(msg=msg)
252
253 wait_for_operation(config, "update", r)
254
255 return fetch_resource(module, client, link)
256
257
258 def delete(config, link):
259 module = config.module
260 client = config.client(get_region(module), "vpc", "project")
261
262 try:
263 client.delete(link)
264 except HwcClientException as ex:
265 msg = f"module(hwc_network_vpc): error deleting resource, error: {ex}"
266 module.fail_json(msg=msg)
267
268 wait_for_delete(module, client, link)
269
270
271 def fetch_resource(module, client, link):
272 try:
273 return client.get(link)
274 except HwcClientException as ex:
275 msg = f"module(hwc_network_vpc): error fetching resource, error: {ex}"
276 module.fail_json(msg=msg)
277
278
279 def get_id_by_name(config):
280 module = config.module
281 client = config.client(get_region(module), "vpc", "project")
282 name = module.params.get("name")
283 link = "vpcs"
284 query_link = "?marker={marker}&limit=10"
285 link += query_link
286 not_format_keys = re.findall("={marker}", link)
287 none_values = re.findall("=None", link)
288
289 if not (not_format_keys or none_values):
290 r = None
291 try:
292 r = client.get(link)
293 except Exception:
294 pass
295 if r is None:
296 return None
297 r = r.get("vpcs", [])
298 ids = [i.get("id") for i in r if i.get("name", "") == name]
299 if not ids:
300 return None
301 elif len(ids) == 1:
302 return ids[0]
303 else:
304 module.fail_json(msg="Multiple resources with same name are found.")
305 elif none_values:
306 module.fail_json(msg="Can not find id by name because url includes None.")
307 else:
308 p = {"marker": ""}
309 ids = set()
310 while True:
311 r = None
312 try:
313 r = client.get(link.format(**p))
314 except Exception:
315 pass
316 if r is None:
317 break
318 r = r.get("vpcs", [])
319 if r == []:
320 break
321 for i in r:
322 if i.get("name") == name:
323 ids.add(i.get("id"))
324 if len(ids) >= 2:
325 module.fail_json(msg="Multiple resources with same name are found.")
326
327 p["marker"] = r[-1].get("id")
328
329 return ids.pop() if ids else None
330
331
332 def self_link(module):
333 return build_path(module, "vpcs/{id}")
334
335
336 def resource_to_create(module):
337 params = dict()
338
339 v = module.params.get("cidr")
340 if not is_empty_value(v):
341 params["cidr"] = v
342
343 v = module.params.get("name")
344 if not is_empty_value(v):
345 params["name"] = v
346
347 if not params:
348 return params
349
350 params = {"vpc": params}
351
352 return params
353
354
355 def resource_to_update(module):
356 params = dict()
357
358 v = module.params.get("cidr")
359 if not is_empty_value(v):
360 params["cidr"] = v
361
362 if not params:
363 return params
364
365 params = {"vpc": params}
366
367 return params
368
369
370 def _get_editable_properties(module):
371 return {
372 "cidr": module.params.get("cidr"),
373 }
374
375
376 def response_to_hash(module, response):
377 """Remove unnecessary properties from the response.
378 This is for doing comparisons with Ansible's current parameters.
379 """
380 return {
381 "id": response.get("id"),
382 "name": response.get("name"),
383 "cidr": response.get("cidr"),
384 "status": response.get("status"),
385 "routes": VpcRoutesArray(response.get("routes", []), module).from_response(),
386 "enable_shared_snat": response.get("enable_shared_snat"),
387 }
388
389
390 def wait_for_operation(config, op_type, op_result):
391 module = config.module
392 op_id = ""
393 try:
394 op_id = navigate_value(op_result, ["vpc", "id"])
395 except Exception as ex:
396 module.fail_json(msg=str(ex))
397
398 url = build_path(module, "vpcs/{op_id}", {"op_id": op_id})
399 timeout = 60 * int(module.params["timeouts"][op_type].rstrip("m"))
400 states = {
401 "create": {
402 "allowed": ["CREATING", "DONW", "OK"],
403 "complete": ["OK"],
404 },
405 "update": {
406 "allowed": ["PENDING_UPDATE", "DONW", "OK"],
407 "complete": ["OK"],
408 },
409 }
410
411 return wait_for_completion(url, timeout, states[op_type]["allowed"], states[op_type]["complete"], config)
412
413
414 def wait_for_completion(op_uri, timeout, allowed_states, complete_states, config):
415 module = config.module
416 client = config.client(get_region(module), "vpc", "project")
417
418 def _refresh_status():
419 r = None
420 try:
421 r = fetch_resource(module, client, op_uri)
422 except Exception:
423 return None, ""
424
425 status = ""
426 try:
427 status = navigate_value(r, ["vpc", "status"])
428 except Exception:
429 return None, ""
430
431 return r, status
432
433 try:
434 return wait_to_finish(complete_states, allowed_states, _refresh_status, timeout)
435 except Exception as ex:
436 module.fail_json(msg=str(ex))
437
438
439 def wait_for_delete(module, client, link):
440 def _refresh_status():
441 try:
442 client.get(link)
443 except HwcClientException404:
444 return True, "Done"
445
446 except Exception:
447 return None, ""
448
449 return True, "Pending"
450
451 timeout = 60 * int(module.params["timeouts"]["delete"].rstrip("m"))
452 try:
453 return wait_to_finish(["Done"], ["Pending"], _refresh_status, timeout)
454 except Exception as ex:
455 module.fail_json(msg=str(ex))
456
457
458 class VpcRoutesArray:
459 def __init__(self, request, module):
460 self.module = module
461 if request:
462 self.request = request
463 else:
464 self.request = []
465
466 def to_request(self):
467 items = []
468 for item in self.request:
469 items.append(self._request_for_item(item))
470 return items
471
472 def from_response(self):
473 items = []
474 for item in self.request:
475 items.append(self._response_from_item(item))
476 return items
477
478 def _request_for_item(self, item):
479 return {"destination": item.get("destination"), "nexthop": item.get("next_hop")}
480
481 def _response_from_item(self, item):
482 return {"destination": item.get("destination"), "next_hop": item.get("nexthop")}
483
484
485 if __name__ == "__main__":
486 main()