Debian Codegraph @

ansible_collections/community/general/plugins/modules/hwc_vpc_subnet.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_subnet
15 description:
16 - Subnet management.
17 short_description: Creates a resource of VPC/Subnet in Huawei Cloud
18 version_added: '0.2.0'
19 author: Huawei Inc. (@huaweicloud)
20 requirements:
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 Huawei Cloud.
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 timeouts for create operation.
43 type: str
44 default: '15m'
45 update:
46 description:
47 - The timeouts for update operation.
48 type: str
49 default: '15m'
50 cidr:
51 description:
52 - Specifies the subnet CIDR block. The value must be within the VPC CIDR block and be in CIDR format. The subnet mask
53 cannot be greater than 28. Cannot be changed after creating the subnet.
54 type: str
55 required: true
56 gateway_ip:
57 description:
58 - Specifies the gateway of the subnet. The value must be an IP address in the subnet. Cannot be changed after creating
59 the subnet.
60 type: str
61 required: true
62 name:
63 description:
64 - Specifies the subnet name. The value is a string of 1 to 64 characters that can contain letters, digits, underscores
65 (V(_)), hyphens (V(-)), and periods (V(.)).
66 type: str
67 required: true
68 vpc_id:
69 description:
70 - Specifies the ID of the VPC to which the subnet belongs. Cannot be changed after creating the subnet.
71 type: str
72 required: true
73 availability_zone:
74 description:
75 - Specifies the AZ to which the subnet belongs. Cannot be changed after creating the subnet.
76 type: str
77 dhcp_enable:
78 description:
79 - Specifies whether DHCP is enabled for the subnet. The value can be true (enabled) or false(disabled), and default
80 value is true. If this parameter is set to false, newly created ECSs cannot obtain IP addresses, and usernames and
81 passwords cannot be injected using Cloud-init.
82 type: bool
83 dns_address:
84 description:
85 - Specifies the DNS server addresses for subnet. The address in the head is used first.
86 type: list
87 elements: str
88 extends_documentation_fragment:
89 - community.general._hwc
90 - community.general._attributes
91 """
92
93 EXAMPLES = r"""
94 # create subnet
95 - name: Create vpc
96 hwc_network_vpc:
97 cidr: "192.168.100.0/24"
98 name: "ansible_network_vpc_test"
99 register: vpc
100 - name: Create subnet
101 community.general.hwc_vpc_subnet:
102 vpc_id: "{{ vpc.id }}"
103 cidr: "192.168.100.0/26"
104 gateway_ip: "192.168.100.32"
105 name: "ansible_network_subnet_test"
106 dhcp_enable: true
107 """
108
109 RETURN = r"""
110 cidr:
111 description:
112 - Specifies the subnet CIDR block. The value must be within the VPC CIDR block and be in CIDR format. The subnet mask
113 cannot be greater than 28.
114 type: str
115 returned: success
116 gateway_ip:
117 description:
118 - Specifies the gateway of the subnet. The value must be an IP address in the subnet.
119 type: str
120 returned: success
121 name:
122 description:
123 - Specifies the subnet name. The value is a string of 1 to 64 characters that can contain letters, digits, underscores
124 (V(_)), hyphens (V(-)), and periods (V(.)).
125 type: str
126 returned: success
127 vpc_id:
128 description:
129 - Specifies the ID of the VPC to which the subnet belongs.
130 type: str
131 returned: success
132 availability_zone:
133 description:
134 - Specifies the AZ to which the subnet belongs.
135 type: str
136 returned: success
137 dhcp_enable:
138 description:
139 - Specifies whether DHCP is enabled for the subnet. The value can be true (enabled) or false(disabled), and default value
140 is true. If this parameter is set to false, newly created ECSs cannot obtain IP addresses, and usernames and passwords
141 cannot be injected using Cloud-init.
142 type: bool
143 returned: success
144 dns_address:
145 description:
146 - Specifies the DNS server addresses for subnet. The address in the head is used first.
147 type: list
148 returned: success
149 """
150
151 from ansible_collections.community.general.plugins.module_utils._hwc_utils import (
152 Config,
153 HwcClientException,
154 HwcClientException404,
155 HwcModule,
156 are_different_dicts,
157 build_path,
158 get_region,
159 is_empty_value,
160 navigate_value,
161 wait_to_finish,
162 )
163
164
165 def build_module():
166 return HwcModule(
167 argument_spec=dict(
168 state=dict(default="present", choices=["present", "absent"], type="str"),
169 timeouts=dict(
170 type="dict",
171 options=dict(
172 create=dict(default="15m", type="str"),
173 update=dict(default="15m", type="str"),
174 ),
175 default=dict(),
176 ),
177 cidr=dict(type="str", required=True),
178 gateway_ip=dict(type="str", required=True),
179 name=dict(type="str", required=True),
180 vpc_id=dict(type="str", required=True),
181 availability_zone=dict(type="str"),
182 dhcp_enable=dict(type="bool"),
183 dns_address=dict(type="list", elements="str"),
184 ),
185 supports_check_mode=True,
186 )
187
188
189 def main():
190 """Main function"""
191
192 module = build_module()
193 config = Config(module, "vpc")
194
195 try:
196 resource = None
197 if module.params.get("id"):
198 resource = True
199 else:
200 v = search_resource(config)
201 if len(v) > 1:
202 raise Exception(f"Found more than one resource({', '.join([navigate_value(i, ['id']) for i in v])})")
203
204 if len(v) == 1:
205 resource = v[0]
206 module.params["id"] = navigate_value(resource, ["id"])
207
208 result = {}
209 changed = False
210 if module.params["state"] == "present":
211 if resource is None:
212 if not module.check_mode:
213 create(config)
214 changed = True
215
216 current = read_resource(config, exclude_output=True)
217 expect = user_input_parameters(module)
218 if are_different_dicts(expect, current):
219 if not module.check_mode:
220 update(config)
221 changed = True
222
223 result = read_resource(config)
224 result["id"] = module.params.get("id")
225 else:
226 if resource:
227 if not module.check_mode:
228 delete(config)
229 changed = True
230
231 except Exception as ex:
232 module.fail_json(msg=str(ex))
233
234 else:
235 result["changed"] = changed
236 module.exit_json(**result)
237
238
239 def user_input_parameters(module):
240 return {
241 "availability_zone": module.params.get("availability_zone"),
242 "cidr": module.params.get("cidr"),
243 "dhcp_enable": module.params.get("dhcp_enable"),
244 "dns_address": module.params.get("dns_address"),
245 "gateway_ip": module.params.get("gateway_ip"),
246 "name": module.params.get("name"),
247 "vpc_id": module.params.get("vpc_id"),
248 }
249
250
251 def create(config):
252 module = config.module
253 client = config.client(get_region(module), "vpc", "project")
254 timeout = 60 * int(module.params["timeouts"]["create"].rstrip("m"))
255 opts = user_input_parameters(module)
256
257 params = build_create_parameters(opts)
258 r = send_create_request(module, params, client)
259 obj = async_wait_create(config, r, client, timeout)
260 module.params["id"] = navigate_value(obj, ["subnet", "id"])
261
262
263 def update(config):
264 module = config.module
265 client = config.client(get_region(module), "vpc", "project")
266 timeout = 60 * int(module.params["timeouts"]["update"].rstrip("m"))
267 opts = user_input_parameters(module)
268
269 params = build_update_parameters(opts)
270 if params:
271 r = send_update_request(module, params, client)
272 async_wait_update(config, r, client, timeout)
273
274
275 def delete(config):
276 module = config.module
277 client = config.client(get_region(module), "vpc", "project")
278
279 send_delete_request(module, None, client)
280
281 url = build_path(module, "subnets/{id}")
282
283 def _refresh_status():
284 try:
285 client.get(url)
286 except HwcClientException404:
287 return True, "Done"
288
289 except Exception:
290 return None, ""
291
292 return True, "Pending"
293
294 timeout = 60 * int(module.params["timeouts"]["create"].rstrip("m"))
295 try:
296 wait_to_finish(["Done"], ["Pending"], _refresh_status, timeout)
297 except Exception as ex:
298 module.fail_json(msg=f"module(hwc_vpc_subnet): error waiting for api(delete) to be done, error= {ex}")
299
300
301 def read_resource(config, exclude_output=False):
302 module = config.module
303 client = config.client(get_region(module), "vpc", "project")
304
305 res = {}
306
307 r = send_read_request(module, client)
308 res["read"] = fill_read_resp_body(r)
309
310 return update_properties(module, res, None, exclude_output)
311
312
313 def _build_query_link(opts):
314 query_link = "?marker={marker}&limit=10"
315 v = navigate_value(opts, ["vpc_id"])
316 if v:
317 query_link += f"&vpc_id={v}"
318
319 return query_link
320
321
322 def search_resource(config):
323 module = config.module
324 client = config.client(get_region(module), "vpc", "project")
325 opts = user_input_parameters(module)
326 identity_obj = _build_identity_object(opts)
327 query_link = _build_query_link(opts)
328 link = f"subnets{query_link}"
329
330 result = []
331 p = {"marker": ""}
332 while True:
333 url = link.format(**p)
334 r = send_list_request(module, client, url)
335 if not r:
336 break
337
338 for item in r:
339 item = fill_list_resp_body(item)
340 if not are_different_dicts(identity_obj, item):
341 result.append(item)
342
343 if len(result) > 1:
344 break
345
346 p["marker"] = r[-1].get("id")
347
348 return result
349
350
351 def build_create_parameters(opts):
352 params = dict()
353
354 v = navigate_value(opts, ["availability_zone"], None)
355 if not is_empty_value(v):
356 params["availability_zone"] = v
357
358 v = navigate_value(opts, ["cidr"], None)
359 if not is_empty_value(v):
360 params["cidr"] = v
361
362 v = navigate_value(opts, ["dhcp_enable"], None)
363 if v is not None:
364 params["dhcp_enable"] = v
365
366 v = expand_create_dns_list(opts, None)
367 if not is_empty_value(v):
368 params["dnsList"] = v
369
370 v = navigate_value(opts, ["gateway_ip"], None)
371 if not is_empty_value(v):
372 params["gateway_ip"] = v
373
374 v = navigate_value(opts, ["name"], None)
375 if not is_empty_value(v):
376 params["name"] = v
377
378 v = expand_create_primary_dns(opts, None)
379 if not is_empty_value(v):
380 params["primary_dns"] = v
381
382 v = expand_create_secondary_dns(opts, None)
383 if not is_empty_value(v):
384 params["secondary_dns"] = v
385
386 v = navigate_value(opts, ["vpc_id"], None)
387 if not is_empty_value(v):
388 params["vpc_id"] = v
389
390 if not params:
391 return params
392
393 params = {"subnet": params}
394
395 return params
396
397
398 def expand_create_dns_list(d, array_index):
399 v = navigate_value(d, ["dns_address"], array_index)
400 return v if (v and len(v) > 2) else []
401
402
403 def expand_create_primary_dns(d, array_index):
404 v = navigate_value(d, ["dns_address"], array_index)
405 return v[0] if v else ""
406
407
408 def expand_create_secondary_dns(d, array_index):
409 v = navigate_value(d, ["dns_address"], array_index)
410 return v[1] if (v and len(v) > 1) else ""
411
412
413 def send_create_request(module, params, client):
414 url = "subnets"
415 try:
416 r = client.post(url, params)
417 except HwcClientException as ex:
418 msg = f"module(hwc_vpc_subnet): error running api(create), error: {ex}"
419 module.fail_json(msg=msg)
420
421 return r
422
423
424 def async_wait_create(config, result, client, timeout):
425 module = config.module
426
427 path_parameters = {
428 "subnet_id": ["subnet", "id"],
429 }
430 data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
431
432 url = build_path(module, "subnets/{subnet_id}", data)
433
434 def _query_status():
435 r = None
436 try:
437 r = client.get(url, timeout=timeout)
438 except HwcClientException:
439 return None, ""
440
441 try:
442 s = navigate_value(r, ["subnet", "status"])
443 return r, s
444 except Exception:
445 return None, ""
446
447 try:
448 return wait_to_finish(["ACTIVE"], ["UNKNOWN"], _query_status, timeout)
449 except Exception as ex:
450 module.fail_json(msg=f"module(hwc_vpc_subnet): error waiting for api(create) to be done, error= {ex}")
451
452
453 def build_update_parameters(opts):
454 params = dict()
455
456 v = navigate_value(opts, ["dhcp_enable"], None)
457 if v is not None:
458 params["dhcp_enable"] = v
459
460 v = expand_update_dns_list(opts, None)
461 if v is not None:
462 params["dnsList"] = v
463
464 v = navigate_value(opts, ["name"], None)
465 if not is_empty_value(v):
466 params["name"] = v
467
468 v = expand_update_primary_dns(opts, None)
469 if v is not None:
470 params["primary_dns"] = v
471
472 v = expand_update_secondary_dns(opts, None)
473 if v is not None:
474 params["secondary_dns"] = v
475
476 if not params:
477 return params
478
479 params = {"subnet": params}
480
481 return params
482
483
484 def expand_update_dns_list(d, array_index):
485 v = navigate_value(d, ["dns_address"], array_index)
486 if v:
487 if len(v) > 2:
488 return v
489 return None
490 return []
491
492
493 def expand_update_primary_dns(d, array_index):
494 v = navigate_value(d, ["dns_address"], array_index)
495 return v[0] if v else ""
496
497
498 def expand_update_secondary_dns(d, array_index):
499 v = navigate_value(d, ["dns_address"], array_index)
500 return v[1] if (v and len(v) > 1) else ""
501
502
503 def send_update_request(module, params, client):
504 url = build_path(module, "vpcs/{vpc_id}/subnets/{id}")
505
506 try:
507 r = client.put(url, params)
508 except HwcClientException as ex:
509 msg = f"module(hwc_vpc_subnet): error running api(update), error: {ex}"
510 module.fail_json(msg=msg)
511
512 return r
513
514
515 def async_wait_update(config, result, client, timeout):
516 module = config.module
517
518 path_parameters = {
519 "subnet_id": ["subnet", "id"],
520 }
521 data = {key: navigate_value(result, path) for key, path in path_parameters.items()}
522
523 url = build_path(module, "subnets/{subnet_id}", data)
524
525 def _query_status():
526 r = None
527 try:
528 r = client.get(url, timeout=timeout)
529 except HwcClientException:
530 return None, ""
531
532 try:
533 s = navigate_value(r, ["subnet", "status"])
534 return r, s
535 except Exception:
536 return None, ""
537
538 try:
539 return wait_to_finish(["ACTIVE"], ["UNKNOWN"], _query_status, timeout)
540 except Exception as ex:
541 module.fail_json(msg=f"module(hwc_vpc_subnet): error waiting for api(update) to be done, error= {ex}")
542
543
544 def send_delete_request(module, params, client):
545 url = build_path(module, "vpcs/{vpc_id}/subnets/{id}")
546
547 try:
548 r = client.delete(url, params)
549 except HwcClientException as ex:
550 msg = f"module(hwc_vpc_subnet): error running api(delete), error: {ex}"
551 module.fail_json(msg=msg)
552
553 return r
554
555
556 def send_read_request(module, client):
557 url = build_path(module, "subnets/{id}")
558
559 r = None
560 try:
561 r = client.get(url)
562 except HwcClientException as ex:
563 msg = f"module(hwc_vpc_subnet): error running api(read), error: {ex}"
564 module.fail_json(msg=msg)
565
566 return navigate_value(r, ["subnet"], None)
567
568
569 def fill_read_resp_body(body):
570 result = dict()
571
572 result["availability_zone"] = body.get("availability_zone")
573
574 result["cidr"] = body.get("cidr")
575
576 result["dhcp_enable"] = body.get("dhcp_enable")
577
578 result["dnsList"] = body.get("dnsList")
579
580 result["gateway_ip"] = body.get("gateway_ip")
581
582 result["id"] = body.get("id")
583
584 result["name"] = body.get("name")
585
586 result["neutron_network_id"] = body.get("neutron_network_id")
587
588 result["neutron_subnet_id"] = body.get("neutron_subnet_id")
589
590 result["primary_dns"] = body.get("primary_dns")
591
592 result["secondary_dns"] = body.get("secondary_dns")
593
594 result["status"] = body.get("status")
595
596 result["vpc_id"] = body.get("vpc_id")
597
598 return result
599
600
601 def update_properties(module, response, array_index, exclude_output=False):
602 r = user_input_parameters(module)
603
604 v = navigate_value(response, ["read", "availability_zone"], array_index)
605 r["availability_zone"] = v
606
607 v = navigate_value(response, ["read", "cidr"], array_index)
608 r["cidr"] = v
609
610 v = navigate_value(response, ["read", "dhcp_enable"], array_index)
611 r["dhcp_enable"] = v
612
613 v = navigate_value(response, ["read", "dnsList"], array_index)
614 r["dns_address"] = v
615
616 v = navigate_value(response, ["read", "gateway_ip"], array_index)
617 r["gateway_ip"] = v
618
619 v = navigate_value(response, ["read", "name"], array_index)
620 r["name"] = v
621
622 v = navigate_value(response, ["read", "vpc_id"], array_index)
623 r["vpc_id"] = v
624
625 return r
626
627
628 def send_list_request(module, client, url):
629 r = None
630 try:
631 r = client.get(url)
632 except HwcClientException as ex:
633 msg = f"module(hwc_vpc_subnet): error running api(list), error: {ex}"
634 module.fail_json(msg=msg)
635
636 return navigate_value(r, ["subnets"], None)
637
638
639 def _build_identity_object(all_opts):
640 result = dict()
641
642 v = navigate_value(all_opts, ["availability_zone"], None)
643 result["availability_zone"] = v
644
645 v = navigate_value(all_opts, ["cidr"], None)
646 result["cidr"] = v
647
648 v = navigate_value(all_opts, ["dhcp_enable"], None)
649 result["dhcp_enable"] = v
650
651 v = navigate_value(all_opts, ["dns_address"], None)
652 result["dnsList"] = v
653
654 v = navigate_value(all_opts, ["gateway_ip"], None)
655 result["gateway_ip"] = v
656
657 result["id"] = None
658
659 v = navigate_value(all_opts, ["name"], None)
660 result["name"] = v
661
662 result["neutron_network_id"] = None
663
664 result["neutron_subnet_id"] = None
665
666 result["primary_dns"] = None
667
668 result["secondary_dns"] = None
669
670 result["status"] = None
671
672 v = navigate_value(all_opts, ["vpc_id"], None)
673 result["vpc_id"] = v
674
675 return result
676
677
678 def fill_list_resp_body(body):
679 result = dict()
680
681 result["availability_zone"] = body.get("availability_zone")
682
683 result["cidr"] = body.get("cidr")
684
685 result["dhcp_enable"] = body.get("dhcp_enable")
686
687 result["dnsList"] = body.get("dnsList")
688
689 result["gateway_ip"] = body.get("gateway_ip")
690
691 result["id"] = body.get("id")
692
693 result["name"] = body.get("name")
694
695 result["neutron_network_id"] = body.get("neutron_network_id")
696
697 result["neutron_subnet_id"] = body.get("neutron_subnet_id")
698
699 result["primary_dns"] = body.get("primary_dns")
700
701 result["secondary_dns"] = body.get("secondary_dns")
702
703 result["status"] = body.get("status")
704
705 result["vpc_id"] = body.get("vpc_id")
706
707 return result
708
709
710 if __name__ == "__main__":
711 main()