Debian Codegraph @

ansible_collections/community/general/plugins/modules/hwc_vpc_peering_connect.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 SPDX-License-Identifier: GPL-3.0-or-later
5 # https://www.gnu.org/licenses/gpl-3.0.txt)
6
7
8 from __future__ import annotations
9
10 ###############################################################################
11 # Documentation
12 ###############################################################################
13
14 DOCUMENTATION = r"""
15 module: hwc_vpc_peering_connect
16 description:
17 - VPC peering management.
18 short_description: Creates a resource of VPC/PeeringConnect in Huawei Cloud
19 version_added: '0.2.0'
20 author: Huawei Inc. (@huaweicloud)
21 requirements:
22 - keystoneauth1 >= 3.6.0
23 attributes:
24 check_mode:
25 support: full
26 diff_mode:
27 support: none
28 options:
29 state:
30 description:
31 - Whether the given object should exist in Huawei Cloud.
32 type: str
33 choices: ['present', 'absent']
34 default: 'present'
35 timeouts:
36 description:
37 - The timeouts for each operations.
38 type: dict
39 default: {}
40 suboptions:
41 create:
42 description:
43 - The timeouts for create operation.
44 type: str
45 default: '15m'
46 local_vpc_id:
47 description:
48 - Specifies the ID of local VPC.
49 type: str
50 required: true
51 name:
52 description:
53 - Specifies the name of the VPC peering connection. The value can contain 1 to 64 characters.
54 type: str
55 required: true
56 peering_vpc:
57 description:
58 - Specifies information about the peering VPC.
59 type: dict
60 required: true
61 suboptions:
62 vpc_id:
63 description:
64 - Specifies the ID of peering VPC.
65 type: str
66 required: true
67 project_id:
68 description:
69 - Specifies the ID of the project which the peering vpc belongs to.
70 type: str
71 description:
72 description:
73 - The description of vpc peering connection.
74 type: str
75 extends_documentation_fragment:
76 - community.general._hwc
77 - community.general._attributes
78 """
79
80 EXAMPLES = r"""
81 # create a peering connect
82 - name: Create a local vpc
83 hwc_network_vpc:
84 cidr: "192.168.0.0/16"
85 name: "ansible_network_vpc_test_local"
86 register: vpc1
87 - name: Create a peering vpc
88 hwc_network_vpc:
89 cidr: "192.168.0.0/16"
90 name: "ansible_network_vpc_test_peering"
91 register: vpc2
92 - name: Create a peering connect
93 community.general.hwc_vpc_peering_connect:
94 local_vpc_id: "{{ vpc1.id }}"
95 name: "ansible_network_peering_test"
96 peering_vpc:
97 vpc_id: "{{ vpc2.id }}"
98 """
99
100 RETURN = r"""
101 local_vpc_id:
102 description:
103 - Specifies the ID of local VPC.
104 type: str
105 returned: success
106 name:
107 description:
108 - Specifies the name of the VPC peering connection. The value can contain 1 to 64 characters.
109 type: str
110 returned: success
111 peering_vpc:
112 description:
113 - Specifies information about the peering VPC.
114 type: dict
115 returned: success
116 contains:
117 vpc_id:
118 description:
119 - Specifies the ID of peering VPC.
120 type: str
121 returned: success
122 project_id:
123 description:
124 - Specifies the ID of the project which the peering vpc belongs to.
125 type: str
126 returned: success
127 description:
128 description:
129 - The description of vpc peering connection.
130 type: str
131 returned: success
132 """
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 def build_module():
149 return HwcModule(
150 argument_spec=dict(
151 state=dict(default="present", choices=["present", "absent"], type="str"),
152 timeouts=dict(
153 type="dict",
154 options=dict(
155 create=dict(default="15m", type="str"),
156 ),
157 default=dict(),
158 ),
159 local_vpc_id=dict(type="str", required=True),
160 name=dict(type="str", required=True),
161 peering_vpc=dict(
162 type="dict",
163 required=True,
164 options=dict(vpc_id=dict(type="str", required=True), project_id=dict(type="str")),
165 ),
166 description=dict(type="str"),
167 ),
168 supports_check_mode=True,
169 )
170
171
172 def main():
173 """Main function"""
174
175 module = build_module()
176 config = Config(module, "vpc")
177
178 try:
179 resource = None
180 if module.params["id"]:
181 resource = True
182 else:
183 v = search_resource(config)
184 if len(v) > 1:
185 raise Exception(f"Found more than one resource({', '.join([navigate_value(i, ['id']) for i in v])})")
186
187 if len(v) == 1:
188 resource = v[0]
189 module.params["id"] = navigate_value(resource, ["id"])
190
191 result = {}
192 changed = False
193 if module.params["state"] == "present":
194 if resource is None:
195 if not module.check_mode:
196 create(config)
197 changed = True
198
199 current = read_resource(config, exclude_output=True)
200 expect = user_input_parameters(module)
201 if are_different_dicts(expect, current):
202 if not module.check_mode:
203 update(config)
204 changed = True
205
206 result = read_resource(config)
207 result["id"] = module.params.get("id")
208 else:
209 if resource:
210 if not module.check_mode:
211 delete(config)
212 changed = True
213
214 except Exception as ex:
215 module.fail_json(msg=str(ex))
216
217 else:
218 result["changed"] = changed
219 module.exit_json(**result)
220
221
222 def user_input_parameters(module):
223 return {
224 "description": module.params.get("description"),
225 "local_vpc_id": module.params.get("local_vpc_id"),
226 "name": module.params.get("name"),
227 "peering_vpc": module.params.get("peering_vpc"),
228 }
229
230
231 def create(config):
232 module = config.module
233 client = config.client(get_region(module), "network", "project")
234 timeout = 60 * int(module.params["timeouts"]["create"].rstrip("m"))
235 opts = user_input_parameters(module)
236
237 params = build_create_parameters(opts)
238 r = send_create_request(module, params, client)
239 obj = async_wait_create(config, r, client, timeout)
240 module.params["id"] = navigate_value(obj, ["peering", "id"])
241
242
243 def update(config):
244 module = config.module
245 client = config.client(get_region(module), "network", "project")
246 opts = user_input_parameters(module)
247
248 params = build_update_parameters(opts)
249 if params:
250 send_update_request(module, params, client)
251
252
253 def delete(config):
254 module = config.module
255 client = config.client(get_region(module), "network", "project")
256
257 send_delete_request(module, None, client)
258
259 url = build_path(module, "v2.0/vpc/peerings/{id}")
260
261 def _refresh_status():
262 try:
263 client.get(url)
264 except HwcClientException404:
265 return True, "Done"
266
267 except Exception:
268 return None, ""
269
270 return True, "Pending"
271
272 timeout = 60 * int(module.params["timeouts"]["create"].rstrip("m"))
273 try:
274 wait_to_finish(["Done"], ["Pending"], _refresh_status, timeout)
275 except Exception as ex:
276 module.fail_json(msg=f"module(hwc_vpc_peering_connect): error waiting for api(delete) to be done, error= {ex}")
277
278
279 def read_resource(config, exclude_output=False):
280 module = config.module
281 client = config.client(get_region(module), "network", "project")
282
283 res = {}
284
285 r = send_read_request(module, client)
286 res["read"] = fill_read_resp_body(r)
287
288 return update_properties(module, res, None, exclude_output)
289
290
291 def _build_query_link(opts):
292 query_params = []
293
294 v = navigate_value(opts, ["local_vpc_id"])
295 if v:
296 query_params.append(f"vpc_id={v}")
297
298 v = navigate_value(opts, ["name"])
299 if v:
300 query_params.append(f"name={v}")
301
302 query_link = "?marker={marker}&limit=10"
303 if query_params:
304 query_link += f"&{'&'.join(query_params)}"
305
306 return query_link
307
308
309 def search_resource(config):
310 module = config.module
311 client = config.client(get_region(module), "network", "project")
312 opts = user_input_parameters(module)
313 identity_obj = _build_identity_object(opts)
314 query_link = _build_query_link(opts)
315 link = f"v2.0/vpc/peerings{query_link}"
316
317 result = []
318 p = {"marker": ""}
319 while True:
320 url = link.format(**p)
321 r = send_list_request(module, client, url)
322 if not r:
323 break
324
325 for item in r:
326 item = fill_list_resp_body(item)
327 if not are_different_dicts(identity_obj, item):
328 result.append(item)
329
330 if len(result) > 1:
331 break
332
333 p["marker"] = r[-1].get("id")
334
335 return result
336
337
338 def build_create_parameters(opts):
339 params = dict()
340
341 v = expand_create_accept_vpc_info(opts, None)
342 if not is_empty_value(v):
343 params["accept_vpc_info"] = v
344
345 v = navigate_value(opts, ["description"], None)
346 if not is_empty_value(v):
347 params["description"] = v
348
349 v = navigate_value(opts, ["name"], None)
350 if not is_empty_value(v):
351 params["name"] = v
352
353 v = expand_create_request_vpc_info(opts, None)
354 if not is_empty_value(v):
355 params["request_vpc_info"] = v
356
357 if not params:
358 return params
359
360 params = {"peering": params}
361
362 return params
363
364
365 def expand_create_accept_vpc_info(d, array_index):
366 r = dict()
367
368 v = navigate_value(d, ["peering_vpc", "project_id"], array_index)
369 if not is_empty_value(v):
370 r["tenant_id"] = v
371
372 v = navigate_value(d, ["peering_vpc", "vpc_id"], array_index)
373 if not is_empty_value(v):
374 r["vpc_id"] = v
375
376 return r
377
378
379 def expand_create_request_vpc_info(d, array_index):
380 r = dict()
381
382 r["tenant_id"] = ""
383
384 v = navigate_value(d, ["local_vpc_id"], array_index)
385 if not is_empty_value(v):
386 r["vpc_id"] = v
387
388 return r
389
390
391 def send_create_request(module, params, client):
392 url = "v2.0/vpc/peerings"
393 try:
394 r = client.post(url, params)
395 except HwcClientException as ex:
396 msg = f"module(hwc_vpc_peering_connect): error running api(create), error: {ex}"
397 module.fail_json(msg=msg)
398
399 return r
400
401
402 def async_wait_create(config, result, client, timeout):
403 module = config.module
404
405 path_parameters = {
406 "peering_id": ["peering", "id"],
407 }
408 data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
409
410 url = build_path(module, "v2.0/vpc/peerings/{peering_id}", data)
411
412 def _query_status():
413 r = None
414 try:
415 r = client.get(url, timeout=timeout)
416 except HwcClientException:
417 return None, ""
418
419 try:
420 s = navigate_value(r, ["peering", "status"])
421 return r, s
422 except Exception:
423 return None, ""
424
425 try:
426 return wait_to_finish(["ACTIVE"], ["PENDING_ACCEPTANCE"], _query_status, timeout)
427 except Exception as ex:
428 module.fail_json(msg=f"module(hwc_vpc_peering_connect): error waiting for api(create) to be done, error= {ex}")
429
430
431 def build_update_parameters(opts):
432 params = dict()
433
434 v = navigate_value(opts, ["description"], None)
435 if not is_empty_value(v):
436 params["description"] = v
437
438 v = navigate_value(opts, ["name"], None)
439 if not is_empty_value(v):
440 params["name"] = v
441
442 if not params:
443 return params
444
445 params = {"peering": params}
446
447 return params
448
449
450 def send_update_request(module, params, client):
451 url = build_path(module, "v2.0/vpc/peerings/{id}")
452
453 try:
454 r = client.put(url, params)
455 except HwcClientException as ex:
456 msg = f"module(hwc_vpc_peering_connect): error running api(update), error: {ex}"
457 module.fail_json(msg=msg)
458
459 return r
460
461
462 def send_delete_request(module, params, client):
463 url = build_path(module, "v2.0/vpc/peerings/{id}")
464
465 try:
466 r = client.delete(url, params)
467 except HwcClientException as ex:
468 msg = f"module(hwc_vpc_peering_connect): error running api(delete), error: {ex}"
469 module.fail_json(msg=msg)
470
471 return r
472
473
474 def send_read_request(module, client):
475 url = build_path(module, "v2.0/vpc/peerings/{id}")
476
477 r = None
478 try:
479 r = client.get(url)
480 except HwcClientException as ex:
481 msg = f"module(hwc_vpc_peering_connect): error running api(read), error: {ex}"
482 module.fail_json(msg=msg)
483
484 return navigate_value(r, ["peering"], None)
485
486
487 def fill_read_resp_body(body):
488 result = dict()
489
490 v = fill_read_resp_accept_vpc_info(body.get("accept_vpc_info"))
491 result["accept_vpc_info"] = v
492
493 result["description"] = body.get("description")
494
495 result["id"] = body.get("id")
496
497 result["name"] = body.get("name")
498
499 v = fill_read_resp_request_vpc_info(body.get("request_vpc_info"))
500 result["request_vpc_info"] = v
501
502 result["status"] = body.get("status")
503
504 return result
505
506
507 def fill_read_resp_accept_vpc_info(value):
508 if not value:
509 return None
510
511 result = dict()
512
513 result["tenant_id"] = value.get("tenant_id")
514
515 result["vpc_id"] = value.get("vpc_id")
516
517 return result
518
519
520 def fill_read_resp_request_vpc_info(value):
521 if not value:
522 return None
523
524 result = dict()
525
526 result["tenant_id"] = value.get("tenant_id")
527
528 result["vpc_id"] = value.get("vpc_id")
529
530 return result
531
532
533 def update_properties(module, response, array_index, exclude_output=False):
534 r = user_input_parameters(module)
535
536 v = navigate_value(response, ["read", "description"], array_index)
537 r["description"] = v
538
539 v = navigate_value(response, ["read", "request_vpc_info", "vpc_id"], array_index)
540 r["local_vpc_id"] = v
541
542 v = navigate_value(response, ["read", "name"], array_index)
543 r["name"] = v
544
545 v = r.get("peering_vpc")
546 v = flatten_peering_vpc(response, array_index, v, exclude_output)
547 r["peering_vpc"] = v
548
549 return r
550
551
552 def flatten_peering_vpc(d, array_index, current_value, exclude_output):
553 result = current_value
554 has_init_value = True
555 if not result:
556 result = dict()
557 has_init_value = False
558
559 v = navigate_value(d, ["read", "accept_vpc_info", "tenant_id"], array_index)
560 result["project_id"] = v
561
562 v = navigate_value(d, ["read", "accept_vpc_info", "vpc_id"], array_index)
563 result["vpc_id"] = v
564
565 if has_init_value:
566 return result
567
568 for v in result.values():
569 if v is not None:
570 return result
571 return current_value
572
573
574 def send_list_request(module, client, url):
575 r = None
576 try:
577 r = client.get(url)
578 except HwcClientException as ex:
579 msg = f"module(hwc_vpc_peering_connect): error running api(list), error: {ex}"
580 module.fail_json(msg=msg)
581
582 return navigate_value(r, ["peerings"], None)
583
584
585 def _build_identity_object(all_opts):
586 result = dict()
587
588 v = expand_list_accept_vpc_info(all_opts, None)
589 result["accept_vpc_info"] = v
590
591 v = navigate_value(all_opts, ["description"], None)
592 result["description"] = v
593
594 result["id"] = None
595
596 v = navigate_value(all_opts, ["name"], None)
597 result["name"] = v
598
599 v = expand_list_request_vpc_info(all_opts, None)
600 result["request_vpc_info"] = v
601
602 result["status"] = None
603
604 return result
605
606
607 def expand_list_accept_vpc_info(d, array_index):
608 r = dict()
609
610 v = navigate_value(d, ["peering_vpc", "project_id"], array_index)
611 r["tenant_id"] = v
612
613 v = navigate_value(d, ["peering_vpc", "vpc_id"], array_index)
614 r["vpc_id"] = v
615
616 for v in r.values():
617 if v is not None:
618 return r
619 return None
620
621
622 def expand_list_request_vpc_info(d, array_index):
623 r = dict()
624
625 r["tenant_id"] = None
626
627 v = navigate_value(d, ["local_vpc_id"], array_index)
628 r["vpc_id"] = v
629
630 for v in r.values():
631 if v is not None:
632 return r
633 return None
634
635
636 def fill_list_resp_body(body):
637 result = dict()
638
639 v = fill_list_resp_accept_vpc_info(body.get("accept_vpc_info"))
640 result["accept_vpc_info"] = v
641
642 result["description"] = body.get("description")
643
644 result["id"] = body.get("id")
645
646 result["name"] = body.get("name")
647
648 v = fill_list_resp_request_vpc_info(body.get("request_vpc_info"))
649 result["request_vpc_info"] = v
650
651 result["status"] = body.get("status")
652
653 return result
654
655
656 def fill_list_resp_accept_vpc_info(value):
657 if not value:
658 return None
659
660 result = dict()
661
662 result["tenant_id"] = value.get("tenant_id")
663
664 result["vpc_id"] = value.get("vpc_id")
665
666 return result
667
668
669 def fill_list_resp_request_vpc_info(value):
670 if not value:
671 return None
672
673 result = dict()
674
675 result["tenant_id"] = value.get("tenant_id")
676
677 result["vpc_id"] = value.get("vpc_id")
678
679 return result
680
681
682 if __name__ == "__main__":
683 main()