Debian Codegraph @

ansible_collections/community/general/plugins/modules/hwc_ecs_instance.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_ecs_instance
15 description:
16 - Instance management.
17 short_description: Creates a resource of Ecs/Instance 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: '30m'
45 update:
46 description:
47 - The timeouts for update operation.
48 type: str
49 default: '30m'
50 delete:
51 description:
52 - The timeouts for delete operation.
53 type: str
54 default: '30m'
55 availability_zone:
56 description:
57 - Specifies the name of the AZ where the ECS is located.
58 type: str
59 required: true
60 flavor_name:
61 description:
62 - Specifies the name of the system flavor.
63 type: str
64 required: true
65 image_id:
66 description:
67 - Specifies the ID of the system image.
68 type: str
69 required: true
70 name:
71 description:
72 - Specifies the ECS name. Value requirements consists of 1 to 64 characters, including letters, digits, underscores
73 (V(_)), hyphens (V(-)), periods (V(.)).
74 type: str
75 required: true
76 nics:
77 description:
78 - Specifies the NIC information of the ECS. Constraints the network of the NIC must belong to the VPC specified by vpc_id.
79 A maximum of 12 NICs can be attached to an ECS.
80 type: list
81 elements: dict
82 required: true
83 suboptions:
84 ip_address:
85 description:
86 - Specifies the IP address of the NIC. The value is an IPv4 address. Its value must be an unused IP address in the
87 network segment of the subnet.
88 type: str
89 required: true
90 subnet_id:
91 description:
92 - Specifies the ID of subnet.
93 type: str
94 required: true
95 root_volume:
96 description:
97 - Specifies the configuration of the ECS's system disks.
98 type: dict
99 required: true
100 suboptions:
101 volume_type:
102 description:
103 - Specifies the ECS system disk type.
104 - SATA is common I/O disk type.
105 - SAS is high I/O disk type.
106 - SSD is ultra-high I/O disk type.
107 - Co-p1 is high I/O (performance-optimized I) disk type.
108 - Uh-l1 is ultra-high I/O (latency-optimized) disk type.
109 - NOTE is For HANA, HL1, and HL2 ECSs, use co-p1 and uh-l1 disks. For other ECSs, do not use co-p1 or uh-l1 disks.
110 type: str
111 required: true
112 size:
113 description:
114 - Specifies the system disk size, in GB. The value range is 1 to 1024. The system disk size must be greater than
115 or equal to the minimum system disk size supported by the image (min_disk attribute of the image). If this parameter
116 is not specified or is set to 0, the default system disk size is the minimum value of the system disk in the image
117 (min_disk attribute of the image).
118 type: int
119 snapshot_id:
120 description:
121 - Specifies the snapshot ID or ID of the original data disk contained in the full-ECS image.
122 type: str
123 vpc_id:
124 description:
125 - Specifies the ID of the VPC to which the ECS belongs.
126 type: str
127 required: true
128 admin_pass:
129 description:
130 - Specifies the initial login password of the administrator account for logging in to an ECS using password authentication.
131 The Linux administrator is root, and the Windows administrator is Administrator. Password complexity requirements,
132 consists of 8 to 26 characters. The password must contain at least three of the following character types 'uppercase
133 letters, lowercase letters, digits, and special characters (V(!@$%^-_=+[{}]:,./?))'. The password cannot contain the
134 username or the username in reverse. The Windows ECS password cannot contain the username, the username in reverse,
135 or more than two consecutive characters in the username.
136 type: str
137 data_volumes:
138 description:
139 - Specifies the data disks of ECS instance.
140 type: list
141 elements: dict
142 suboptions:
143 volume_id:
144 description:
145 - Specifies the disk ID.
146 type: str
147 required: true
148 device:
149 description:
150 - Specifies the disk device name.
151 type: str
152 description:
153 description:
154 - Specifies the description of an ECS, which is a null string by default. Can contain a maximum of 85 characters. Cannot
155 contain special characters, such as V(<) and V(>).
156 type: str
157 eip_id:
158 description:
159 - Specifies the ID of the elastic IP address assigned to the ECS. Only elastic IP addresses in the DOWN state can be
160 assigned.
161 type: str
162 enable_auto_recovery:
163 description:
164 - Specifies whether automatic recovery is enabled on the ECS.
165 type: bool
166 enterprise_project_id:
167 description:
168 - Specifies the ID of the enterprise project to which the ECS belongs.
169 type: str
170 security_groups:
171 description:
172 - Specifies the security groups of the ECS. If this parameter is left blank, the default security group is bound to
173 the ECS by default.
174 type: list
175 elements: str
176 server_metadata:
177 description:
178 - Specifies the metadata of ECS to be created.
179 type: dict
180 server_tags:
181 description:
182 - Specifies the tags of an ECS. When you create ECSs, one ECS supports up to 10 tags.
183 type: dict
184 ssh_key_name:
185 description:
186 - Specifies the name of the SSH key used for logging in to the ECS.
187 type: str
188 user_data:
189 description:
190 - Specifies the user data to be injected during the ECS creation process. Text, text files, and gzip files can be injected.
191 The content to be injected must be encoded with base64. The maximum size of the content to be injected (before encoding)
192 is 32 KB. For Linux ECSs, this parameter does not take effect when adminPass is used.
193 type: str
194 extends_documentation_fragment:
195 - community.general._hwc
196 - community.general._attributes
197 """
198
199 EXAMPLES = r"""
200 # create an ecs instance
201 - name: Create a vpc
202 hwc_network_vpc:
203 cidr: "192.168.100.0/24"
204 name: "ansible_network_vpc_test"
205 register: vpc
206 - name: Create a subnet
207 hwc_vpc_subnet:
208 gateway_ip: "192.168.100.32"
209 name: "ansible_network_subnet_test"
210 dhcp_enable: true
211 vpc_id: "{{ vpc.id }}"
212 cidr: "192.168.100.0/26"
213 register: subnet
214 - name: Create a eip
215 hwc_vpc_eip:
216 dedicated_bandwidth:
217 charge_mode: "traffic"
218 name: "ansible_test_dedicated_bandwidth"
219 size: 1
220 type: "5_bgp"
221 register: eip
222 - name: Create a disk
223 hwc_evs_disk:
224 availability_zone: "cn-north-1a"
225 name: "ansible_evs_disk_test"
226 volume_type: "SATA"
227 size: 10
228 register: disk
229 - name: Create an instance
230 community.general.hwc_ecs_instance:
231 data_volumes:
232 - volume_id: "{{ disk.id }}"
233 enable_auto_recovery: false
234 eip_id: "{{ eip.id }}"
235 name: "ansible_ecs_instance_test"
236 availability_zone: "cn-north-1a"
237 nics:
238 - subnet_id: "{{ subnet.id }}"
239 ip_address: "192.168.100.33"
240 - subnet_id: "{{ subnet.id }}"
241 ip_address: "192.168.100.34"
242 server_tags:
243 my_server: "my_server"
244 image_id: "8da46d6d-6079-4e31-ad6d-a7167efff892"
245 flavor_name: "s3.small.1"
246 vpc_id: "{{ vpc.id }}"
247 root_volume:
248 volume_type: "SAS"
249 """
250
251 RETURN = r"""
252 availability_zone:
253 description:
254 - Specifies the name of the AZ where the ECS is located.
255 type: str
256 returned: success
257 flavor_name:
258 description:
259 - Specifies the name of the system flavor.
260 type: str
261 returned: success
262 image_id:
263 description:
264 - Specifies the ID of the system image.
265 type: str
266 returned: success
267 name:
268 description:
269 - Specifies the ECS name. Value requirements "Consists of 1 to 64 characters, including letters, digits, underscores (V(_)),
270 hyphens (V(-)), periods (V(.)).".
271 type: str
272 returned: success
273 nics:
274 description:
275 - Specifies the NIC information of the ECS. The network of the NIC must belong to the VPC specified by vpc_id. A maximum
276 of 12 NICs can be attached to an ECS.
277 type: list
278 returned: success
279 contains:
280 ip_address:
281 description:
282 - Specifies the IP address of the NIC. The value is an IPv4 address. Its value must be an unused IP address in the
283 network segment of the subnet.
284 type: str
285 returned: success
286 subnet_id:
287 description:
288 - Specifies the ID of subnet.
289 type: str
290 returned: success
291 port_id:
292 description:
293 - Specifies the port ID corresponding to the IP address.
294 type: str
295 returned: success
296 root_volume:
297 description:
298 - Specifies the configuration of the ECS's system disks.
299 type: dict
300 returned: success
301 contains:
302 volume_type:
303 description:
304 - Specifies the ECS system disk type.
305 - SATA is common I/O disk type.
306 - SAS is high I/O disk type.
307 - SSD is ultra-high I/O disk type.
308 - Co-p1 is high I/O (performance-optimized I) disk type.
309 - Uh-l1 is ultra-high I/O (latency-optimized) disk type.
310 - NOTE is For HANA, HL1, and HL2 ECSs, use co-p1 and uh-l1 disks. For other ECSs, do not use co-p1 or uh-l1 disks.
311 type: str
312 returned: success
313 size:
314 description:
315 - Specifies the system disk size, in GB. The value range is 1 to 1024. The system disk size must be greater than or
316 equal to the minimum system disk size supported by the image (min_disk attribute of the image). If this parameter
317 is not specified or is set to 0, the default system disk size is the minimum value of the system disk in the image
318 (min_disk attribute of the image).
319 type: int
320 returned: success
321 snapshot_id:
322 description:
323 - Specifies the snapshot ID or ID of the original data disk contained in the full-ECS image.
324 type: str
325 returned: success
326 device:
327 description:
328 - Specifies the disk device name.
329 type: str
330 returned: success
331 volume_id:
332 description:
333 - Specifies the disk ID.
334 type: str
335 returned: success
336 vpc_id:
337 description:
338 - Specifies the ID of the VPC to which the ECS belongs.
339 type: str
340 returned: success
341 admin_pass:
342 description:
343 - Specifies the initial login password of the administrator account for logging in to an ECS using password authentication.
344 The Linux administrator is root, and the Windows administrator is Administrator. Password complexity requirements consists
345 of 8 to 26 characters. The password must contain at least three of the following character types "uppercase letters,
346 lowercase letters, digits, and special characters (!@$%^-_=+[{}]:,./?)". The password cannot contain the username or
347 the username in reverse. The Windows ECS password cannot contain the username, the username in reverse, or more than
348 two consecutive characters in the username.
349 type: str
350 returned: success
351 data_volumes:
352 description:
353 - Specifies the data disks of ECS instance.
354 type: list
355 returned: success
356 contains:
357 volume_id:
358 description:
359 - Specifies the disk ID.
360 type: str
361 returned: success
362 device:
363 description:
364 - Specifies the disk device name.
365 type: str
366 returned: success
367 description:
368 description:
369 - Specifies the description of an ECS, which is a null string by default. Can contain a maximum of 85 characters. Cannot
370 contain special characters, such as < and >.
371 type: str
372 returned: success
373 eip_id:
374 description:
375 - Specifies the ID of the elastic IP address assigned to the ECS. Only elastic IP addresses in the DOWN state can be assigned.
376 type: str
377 returned: success
378 enable_auto_recovery:
379 description:
380 - Specifies whether automatic recovery is enabled on the ECS.
381 type: bool
382 returned: success
383 enterprise_project_id:
384 description:
385 - Specifies the ID of the enterprise project to which the ECS belongs.
386 type: str
387 returned: success
388 security_groups:
389 description:
390 - Specifies the security groups of the ECS. If this parameter is left blank, the default security group is bound to the
391 ECS by default.
392 type: list
393 returned: success
394 server_metadata:
395 description:
396 - Specifies the metadata of ECS to be created.
397 type: dict
398 returned: success
399 server_tags:
400 description:
401 - Specifies the tags of an ECS. When you create ECSs, one ECS supports up to 10 tags.
402 type: dict
403 returned: success
404 ssh_key_name:
405 description:
406 - Specifies the name of the SSH key used for logging in to the ECS.
407 type: str
408 returned: success
409 user_data:
410 description:
411 - Specifies the user data to be injected during the ECS creation process. Text, text files, and gzip files can be injected.
412 The content to be injected must be encoded with base64. The maximum size of the content to be injected (before encoding)
413 is 32 KB. For Linux ECSs, this parameter does not take effect when adminPass is used.
414 type: str
415 returned: success
416 config_drive:
417 description:
418 - Specifies the configuration driver.
419 type: str
420 returned: success
421 created:
422 description:
423 - Specifies the time when an ECS was created.
424 type: str
425 returned: success
426 disk_config_type:
427 description:
428 - Specifies the disk configuration type. MANUAL is The image space is not expanded. AUTO is the image space of the system
429 disk is expanded to be as same as the flavor.
430 type: str
431 returned: success
432 host_name:
433 description:
434 - Specifies the host name of the ECS.
435 type: str
436 returned: success
437 image_name:
438 description:
439 - Specifies the image name of the ECS.
440 type: str
441 returned: success
442 power_state:
443 description:
444 - Specifies the power status of the ECS.
445 type: int
446 returned: success
447 server_alias:
448 description:
449 - Specifies the ECS alias.
450 type: str
451 returned: success
452 status:
453 description:
454 - Specifies the ECS status. Options are ACTIVE, REBOOT, HARD_REBOOT, REBUILD, MIGRATING, BUILD, SHUTOFF, RESIZE, VERIFY_RESIZE,
455 ERROR, and DELETED.
456 type: str
457 returned: success
458 """
459
460 from ansible_collections.community.general.plugins.module_utils._hwc_utils import (
461 Config,
462 HwcClientException,
463 HwcModule,
464 are_different_dicts,
465 build_path,
466 get_region,
467 is_empty_value,
468 navigate_value,
469 wait_to_finish,
470 )
471
472
473 def build_module():
474 return HwcModule(
475 argument_spec=dict(
476 state=dict(default="present", choices=["present", "absent"], type="str"),
477 timeouts=dict(
478 type="dict",
479 options=dict(
480 create=dict(default="30m", type="str"),
481 update=dict(default="30m", type="str"),
482 delete=dict(default="30m", type="str"),
483 ),
484 default=dict(),
485 ),
486 availability_zone=dict(type="str", required=True),
487 flavor_name=dict(type="str", required=True),
488 image_id=dict(type="str", required=True),
489 name=dict(type="str", required=True),
490 nics=dict(
491 type="list",
492 required=True,
493 elements="dict",
494 options=dict(ip_address=dict(type="str", required=True), subnet_id=dict(type="str", required=True)),
495 ),
496 root_volume=dict(
497 type="dict",
498 required=True,
499 options=dict(
500 volume_type=dict(type="str", required=True), size=dict(type="int"), snapshot_id=dict(type="str")
501 ),
502 ),
503 vpc_id=dict(type="str", required=True),
504 admin_pass=dict(type="str", no_log=True),
505 data_volumes=dict(
506 type="list",
507 elements="dict",
508 options=dict(volume_id=dict(type="str", required=True), device=dict(type="str")),
509 ),
510 description=dict(type="str"),
511 eip_id=dict(type="str"),
512 enable_auto_recovery=dict(type="bool"),
513 enterprise_project_id=dict(type="str"),
514 security_groups=dict(type="list", elements="str"),
515 server_metadata=dict(type="dict"),
516 server_tags=dict(type="dict"),
517 ssh_key_name=dict(type="str"),
518 user_data=dict(type="str"),
519 ),
520 supports_check_mode=True,
521 )
522
523
524 def main():
525 """Main function"""
526
527 module = build_module()
528 config = Config(module, "ecs")
529
530 try:
531 _init(config)
532 is_exist = module.params["id"]
533
534 result = None
535 changed = False
536 if module.params["state"] == "present":
537 if not is_exist:
538 if not module.check_mode:
539 create(config)
540 changed = True
541
542 inputv = user_input_parameters(module)
543 resp, array_index = read_resource(config)
544 result = build_state(inputv, resp, array_index)
545 set_readonly_options(inputv, result)
546 if are_different_dicts(inputv, result):
547 if not module.check_mode:
548 update(config, inputv, result)
549
550 inputv = user_input_parameters(module)
551 resp, array_index = read_resource(config)
552 result = build_state(inputv, resp, array_index)
553 set_readonly_options(inputv, result)
554 if are_different_dicts(inputv, result):
555 raise Exception("Update resource failed, some attributes are not updated")
556
557 changed = True
558
559 result["id"] = module.params.get("id")
560 else:
561 result = dict()
562 if is_exist:
563 if not module.check_mode:
564 delete(config)
565 changed = True
566
567 except Exception as ex:
568 module.fail_json(msg=str(ex))
569
570 else:
571 result["changed"] = changed
572 module.exit_json(**result)
573
574
575 def _init(config):
576 module = config.module
577 if module.params["id"]:
578 return
579
580 v = search_resource(config)
581 n = len(v)
582 if n > 1:
583 raise Exception(f"Found more than one resource({', '.join([navigate_value(i, ['id']) for i in v])})")
584
585 if n == 1:
586 module.params["id"] = navigate_value(v[0], ["id"])
587
588
589 def user_input_parameters(module):
590 return {
591 "admin_pass": module.params.get("admin_pass"),
592 "availability_zone": module.params.get("availability_zone"),
593 "data_volumes": module.params.get("data_volumes"),
594 "description": module.params.get("description"),
595 "eip_id": module.params.get("eip_id"),
596 "enable_auto_recovery": module.params.get("enable_auto_recovery"),
597 "enterprise_project_id": module.params.get("enterprise_project_id"),
598 "flavor_name": module.params.get("flavor_name"),
599 "image_id": module.params.get("image_id"),
600 "name": module.params.get("name"),
601 "nics": module.params.get("nics"),
602 "root_volume": module.params.get("root_volume"),
603 "security_groups": module.params.get("security_groups"),
604 "server_metadata": module.params.get("server_metadata"),
605 "server_tags": module.params.get("server_tags"),
606 "ssh_key_name": module.params.get("ssh_key_name"),
607 "user_data": module.params.get("user_data"),
608 "vpc_id": module.params.get("vpc_id"),
609 }
610
611
612 def create(config):
613 module = config.module
614 client = config.client(get_region(module), "ecs", "project")
615 timeout = 60 * int(module.params["timeouts"]["create"].rstrip("m"))
616 opts = user_input_parameters(module)
617 opts["ansible_module"] = module
618
619 params = build_create_parameters(opts)
620 r = send_create_request(module, params, client)
621 obj = async_wait(config, r, client, timeout)
622
623 sub_job_identity = {
624 "job_type": "createSingleServer",
625 }
626 for item in navigate_value(obj, ["entities", "sub_jobs"]):
627 for k, v in sub_job_identity.items():
628 if item[k] != v:
629 break
630 else:
631 obj = item
632 break
633 else:
634 raise Exception("Can't find the sub job")
635 module.params["id"] = navigate_value(obj, ["entities", "server_id"])
636
637
638 def update(config, expect_state, current_state):
639 module = config.module
640 expect_state["current_state"] = current_state
641 current_state["current_state"] = current_state
642 timeout = 60 * int(module.params["timeouts"]["update"].rstrip("m"))
643 client = config.client(get_region(module), "ecs", "project")
644
645 params = build_delete_nics_parameters(expect_state)
646 params1 = build_delete_nics_parameters(current_state)
647 if params and are_different_dicts(params, params1):
648 r = send_delete_nics_request(module, params, client)
649 async_wait(config, r, client, timeout)
650
651 params = build_set_auto_recovery_parameters(expect_state)
652 params1 = build_set_auto_recovery_parameters(current_state)
653 if params and are_different_dicts(params, params1):
654 send_set_auto_recovery_request(module, params, client)
655
656 params = build_attach_nics_parameters(expect_state)
657 params1 = build_attach_nics_parameters(current_state)
658 if params and are_different_dicts(params, params1):
659 r = send_attach_nics_request(module, params, client)
660 async_wait(config, r, client, timeout)
661
662 multi_invoke_delete_volume(config, expect_state, client, timeout)
663
664 multi_invoke_attach_data_disk(config, expect_state, client, timeout)
665
666
667 def delete(config):
668 module = config.module
669 client = config.client(get_region(module), "ecs", "project")
670 timeout = 60 * int(module.params["timeouts"]["delete"].rstrip("m"))
671
672 opts = user_input_parameters(module)
673 opts["ansible_module"] = module
674
675 params = build_delete_parameters(opts)
676 if params:
677 r = send_delete_request(module, params, client)
678 async_wait(config, r, client, timeout)
679
680
681 def read_resource(config):
682 module = config.module
683 client = config.client(get_region(module), "ecs", "project")
684
685 res = {}
686
687 r = send_read_request(module, client)
688 preprocess_read_response(r)
689 res["read"] = fill_read_resp_body(r)
690
691 r = send_read_auto_recovery_request(module, client)
692 res["read_auto_recovery"] = fill_read_auto_recovery_resp_body(r)
693
694 return res, None
695
696
697 def preprocess_read_response(resp):
698 v = resp.get("os-extended-volumes:volumes_attached")
699 if v and isinstance(v, list):
700 for i in range(len(v)):
701 if v[i].get("bootIndex") == "0":
702 root_volume = v[i]
703
704 if (i + 1) != len(v):
705 v[i] = v[-1]
706
707 v.pop()
708
709 resp["root_volume"] = root_volume
710 break
711
712 v = resp.get("addresses")
713 if v:
714 rv = {}
715 eips = []
716 for val in v.values():
717 for item in val:
718 if item["OS-EXT-IPS:type"] == "floating":
719 eips.append(item)
720 else:
721 rv[item["OS-EXT-IPS:port_id"]] = item
722
723 for item in eips:
724 k = item["OS-EXT-IPS:port_id"]
725 if k in rv:
726 rv[k]["eip_address"] = item.get("addr", "")
727 else:
728 rv[k] = item
729 item["eip_address"] = item.get("addr", "")
730 item["addr"] = ""
731
732 resp["address"] = rv.values()
733
734
735 def build_state(opts, response, array_index):
736 states = flatten_options(response, array_index)
737 set_unreadable_options(opts, states)
738 adjust_options(opts, states)
739 return states
740
741
742 def _build_query_link(opts):
743 query_params = []
744
745 v = navigate_value(opts, ["enterprise_project_id"])
746 if v or v in [False, 0]:
747 query_params.append(f"enterprise_project_id={str(v) if v else str(v).lower()}")
748
749 v = navigate_value(opts, ["name"])
750 if v or v in [False, 0]:
751 query_params.append(f"name={str(v) if v else str(v).lower()}")
752
753 query_link = "?limit=10&offset={offset}"
754 if query_params:
755 query_link += f"&{'&'.join(query_params)}"
756
757 return query_link
758
759
760 def search_resource(config):
761 module = config.module
762 client = config.client(get_region(module), "ecs", "project")
763 opts = user_input_parameters(module)
764 identity_obj = _build_identity_object(opts)
765 query_link = _build_query_link(opts)
766 link = f"cloudservers/detail{query_link}"
767
768 result = []
769 p = {"offset": 1}
770 while True:
771 url = link.format(**p)
772 r = send_list_request(module, client, url)
773 if not r:
774 break
775
776 for item in r:
777 item = fill_list_resp_body(item)
778 adjust_list_resp(identity_obj, item)
779 if not are_different_dicts(identity_obj, item):
780 result.append(item)
781
782 if len(result) > 1:
783 break
784
785 p["offset"] += 1
786
787 return result
788
789
790 def build_delete_nics_parameters(opts):
791 params = dict()
792
793 v = expand_delete_nics_nics(opts, None)
794 if not is_empty_value(v):
795 params["nics"] = v
796
797 return params
798
799
800 def expand_delete_nics_nics(d, array_index):
801 cv = d["current_state"].get("nics")
802 if not cv:
803 return None
804
805 val = cv
806
807 ev = d.get("nics")
808 if ev:
809 m = [item.get("ip_address") for item in ev]
810 val = [item for item in cv if item.get("ip_address") not in m]
811
812 r = []
813 for item in val:
814 transformed = dict()
815
816 v = item.get("port_id")
817 if not is_empty_value(v):
818 transformed["id"] = v
819
820 if transformed:
821 r.append(transformed)
822
823 return r
824
825
826 def send_delete_nics_request(module, params, client):
827 url = build_path(module, "cloudservers/{id}/nics/delete")
828
829 try:
830 r = client.post(url, params)
831 except HwcClientException as ex:
832 msg = f"module(hwc_ecs_instance): error running api(delete_nics), error: {ex}"
833 module.fail_json(msg=msg)
834
835 return r
836
837
838 def build_set_auto_recovery_parameters(opts):
839 params = dict()
840
841 v = expand_set_auto_recovery_support_auto_recovery(opts, None)
842 if v is not None:
843 params["support_auto_recovery"] = v
844
845 return params
846
847
848 def expand_set_auto_recovery_support_auto_recovery(d, array_index):
849 v = navigate_value(d, ["enable_auto_recovery"], None)
850 return None if v is None else str(v).lower()
851
852
853 def send_set_auto_recovery_request(module, params, client):
854 url = build_path(module, "cloudservers/{id}/autorecovery")
855
856 try:
857 r = client.put(url, params)
858 except HwcClientException as ex:
859 msg = f"module(hwc_ecs_instance): error running api(set_auto_recovery), error: {ex}"
860 module.fail_json(msg=msg)
861
862 return r
863
864
865 def build_create_parameters(opts):
866 params = dict()
867
868 v = navigate_value(opts, ["admin_pass"], None)
869 if not is_empty_value(v):
870 params["adminPass"] = v
871
872 v = navigate_value(opts, ["availability_zone"], None)
873 if not is_empty_value(v):
874 params["availability_zone"] = v
875
876 v = navigate_value(opts, ["description"], None)
877 if not is_empty_value(v):
878 params["description"] = v
879
880 v = expand_create_extendparam(opts, None)
881 if not is_empty_value(v):
882 params["extendparam"] = v
883
884 v = navigate_value(opts, ["flavor_name"], None)
885 if not is_empty_value(v):
886 params["flavorRef"] = v
887
888 v = navigate_value(opts, ["image_id"], None)
889 if not is_empty_value(v):
890 params["imageRef"] = v
891
892 v = navigate_value(opts, ["ssh_key_name"], None)
893 if not is_empty_value(v):
894 params["key_name"] = v
895
896 v = navigate_value(opts, ["server_metadata"], None)
897 if not is_empty_value(v):
898 params["metadata"] = v
899
900 v = navigate_value(opts, ["name"], None)
901 if not is_empty_value(v):
902 params["name"] = v
903
904 v = expand_create_nics(opts, None)
905 if not is_empty_value(v):
906 params["nics"] = v
907
908 v = expand_create_publicip(opts, None)
909 if not is_empty_value(v):
910 params["publicip"] = v
911
912 v = expand_create_root_volume(opts, None)
913 if not is_empty_value(v):
914 params["root_volume"] = v
915
916 v = expand_create_security_groups(opts, None)
917 if not is_empty_value(v):
918 params["security_groups"] = v
919
920 v = expand_create_server_tags(opts, None)
921 if not is_empty_value(v):
922 params["server_tags"] = v
923
924 v = navigate_value(opts, ["user_data"], None)
925 if not is_empty_value(v):
926 params["user_data"] = v
927
928 v = navigate_value(opts, ["vpc_id"], None)
929 if not is_empty_value(v):
930 params["vpcid"] = v
931
932 if not params:
933 return params
934
935 params = {"server": params}
936
937 return params
938
939
940 def expand_create_extendparam(d, array_index):
941 r = dict()
942
943 r["chargingMode"] = 0
944
945 v = navigate_value(d, ["enterprise_project_id"], array_index)
946 if not is_empty_value(v):
947 r["enterprise_project_id"] = v
948
949 v = navigate_value(d, ["enable_auto_recovery"], array_index)
950 if not is_empty_value(v):
951 r["support_auto_recovery"] = v
952
953 return r
954
955
956 def expand_create_nics(d, array_index):
957 new_ai = dict()
958 if array_index:
959 new_ai.update(array_index)
960
961 req = []
962
963 v = navigate_value(d, ["nics"], new_ai)
964
965 if not v:
966 return req
967 n = len(v)
968 for i in range(n):
969 new_ai["nics"] = i
970 transformed = dict()
971
972 v = navigate_value(d, ["nics", "ip_address"], new_ai)
973 if not is_empty_value(v):
974 transformed["ip_address"] = v
975
976 v = navigate_value(d, ["nics", "subnet_id"], new_ai)
977 if not is_empty_value(v):
978 transformed["subnet_id"] = v
979
980 if transformed:
981 req.append(transformed)
982
983 return req
984
985
986 def expand_create_publicip(d, array_index):
987 r = dict()
988
989 v = navigate_value(d, ["eip_id"], array_index)
990 if not is_empty_value(v):
991 r["id"] = v
992
993 return r
994
995
996 def expand_create_root_volume(d, array_index):
997 r = dict()
998
999 v = expand_create_root_volume_extendparam(d, array_index)
1000 if not is_empty_value(v):
1001 r["extendparam"] = v
1002
1003 v = navigate_value(d, ["root_volume", "size"], array_index)
1004 if not is_empty_value(v):
1005 r["size"] = v
1006
1007 v = navigate_value(d, ["root_volume", "volume_type"], array_index)
1008 if not is_empty_value(v):
1009 r["volumetype"] = v
1010
1011 return r
1012
1013
1014 def expand_create_root_volume_extendparam(d, array_index):
1015 r = dict()
1016
1017 v = navigate_value(d, ["root_volume", "snapshot_id"], array_index)
1018 if not is_empty_value(v):
1019 r["snapshotId"] = v
1020
1021 return r
1022
1023
1024 def expand_create_security_groups(d, array_index):
1025 v = d.get("security_groups")
1026 if not v:
1027 return None
1028
1029 return [{"id": i} for i in v]
1030
1031
1032 def expand_create_server_tags(d, array_index):
1033 v = d.get("server_tags")
1034 if not v:
1035 return None
1036
1037 return [{"key": k, "value": v1} for k, v1 in v.items()]
1038
1039
1040 def send_create_request(module, params, client):
1041 url = "cloudservers"
1042 try:
1043 r = client.post(url, params)
1044 except HwcClientException as ex:
1045 msg = f"module(hwc_ecs_instance): error running api(create), error: {ex}"
1046 module.fail_json(msg=msg)
1047
1048 return r
1049
1050
1051 def build_attach_nics_parameters(opts):
1052 params = dict()
1053
1054 v = expand_attach_nics_nics(opts, None)
1055 if not is_empty_value(v):
1056 params["nics"] = v
1057
1058 return params
1059
1060
1061 def expand_attach_nics_nics(d, array_index):
1062 ev = d.get("nics")
1063 if not ev:
1064 return None
1065
1066 val = ev
1067
1068 cv = d["current_state"].get("nics")
1069 if cv:
1070 m = [item.get("ip_address") for item in cv]
1071 val = [item for item in ev if item.get("ip_address") not in m]
1072
1073 r = []
1074 for item in val:
1075 transformed = dict()
1076
1077 v = item.get("ip_address")
1078 if not is_empty_value(v):
1079 transformed["ip_address"] = v
1080
1081 v = item.get("subnet_id")
1082 if not is_empty_value(v):
1083 transformed["subnet_id"] = v
1084
1085 if transformed:
1086 r.append(transformed)
1087
1088 return r
1089
1090
1091 def send_attach_nics_request(module, params, client):
1092 url = build_path(module, "cloudservers/{id}/nics")
1093
1094 try:
1095 r = client.post(url, params)
1096 except HwcClientException as ex:
1097 msg = f"module(hwc_ecs_instance): error running api(attach_nics), error: {ex}"
1098 module.fail_json(msg=msg)
1099
1100 return r
1101
1102
1103 def send_delete_volume_request(module, params, client, info):
1104 path_parameters = {
1105 "volume_id": ["volume_id"],
1106 }
1107 data = {key: navigate_value(info, path) for key, path in path_parameters.items()}
1108
1109 url = build_path(module, "cloudservers/{id}/detachvolume/{volume_id}", data)
1110
1111 try:
1112 r = client.delete(url, params)
1113 except HwcClientException as ex:
1114 msg = f"module(hwc_ecs_instance): error running api(delete_volume), error: {ex}"
1115 module.fail_json(msg=msg)
1116
1117 return r
1118
1119
1120 def build_attach_data_disk_parameters(opts, array_index):
1121 params = dict()
1122
1123 v = expand_attach_data_disk_volume_attachment(opts, array_index)
1124 if not is_empty_value(v):
1125 params["volumeAttachment"] = v
1126
1127 return params
1128
1129
1130 def expand_attach_data_disk_volume_attachment(d, array_index):
1131 r = dict()
1132
1133 v = navigate_value(d, ["data_volumes", "device"], array_index)
1134 if not is_empty_value(v):
1135 r["device"] = v
1136
1137 v = navigate_value(d, ["data_volumes", "volume_id"], array_index)
1138 if not is_empty_value(v):
1139 r["volumeId"] = v
1140
1141 return r
1142
1143
1144 def send_attach_data_disk_request(module, params, client):
1145 url = build_path(module, "cloudservers/{id}/attachvolume")
1146
1147 try:
1148 r = client.post(url, params)
1149 except HwcClientException as ex:
1150 msg = f"module(hwc_ecs_instance): error running api(attach_data_disk), error: {ex}"
1151 module.fail_json(msg=msg)
1152
1153 return r
1154
1155
1156 def build_delete_parameters(opts):
1157 params = dict()
1158
1159 params["delete_publicip"] = False
1160
1161 params["delete_volume"] = False
1162
1163 v = expand_delete_servers(opts, None)
1164 if not is_empty_value(v):
1165 params["servers"] = v
1166
1167 return params
1168
1169
1170 def expand_delete_servers(d, array_index):
1171 new_ai = dict()
1172 if array_index:
1173 new_ai.update(array_index)
1174
1175 req = []
1176
1177 transformed = dict()
1178
1179 v = expand_delete_servers_id(d, new_ai)
1180 if not is_empty_value(v):
1181 transformed["id"] = v
1182
1183 if transformed:
1184 req.append(transformed)
1185
1186 return req
1187
1188
1189 def expand_delete_servers_id(d, array_index):
1190 return d["ansible_module"].params.get("id")
1191
1192
1193 def send_delete_request(module, params, client):
1194 url = "cloudservers/delete"
1195 try:
1196 r = client.post(url, params)
1197 except HwcClientException as ex:
1198 msg = f"module(hwc_ecs_instance): error running api(delete), error: {ex}"
1199 module.fail_json(msg=msg)
1200
1201 return r
1202
1203
1204 def async_wait(config, result, client, timeout):
1205 module = config.module
1206
1207 url = build_path(module, "jobs/{job_id}", result)
1208
1209 def _query_status():
1210 r = None
1211 try:
1212 r = client.get(url, timeout=timeout)
1213 except HwcClientException:
1214 return None, ""
1215
1216 try:
1217 s = navigate_value(r, ["status"])
1218 return r, s
1219 except Exception:
1220 return None, ""
1221
1222 try:
1223 return wait_to_finish(["SUCCESS"], ["RUNNING", "INIT"], _query_status, timeout)
1224 except Exception as ex:
1225 module.fail_json(msg=f"module(hwc_ecs_instance): error waiting to be done, error= {ex}")
1226
1227
1228 def multi_invoke_delete_volume(config, opts, client, timeout):
1229 module = config.module
1230
1231 opts1 = None
1232 expect = opts["data_volumes"]
1233 current = opts["current_state"]["data_volumes"]
1234 if expect and current:
1235 v = [i["volume_id"] for i in expect]
1236 opts1 = {"data_volumes": [i for i in current if i["volume_id"] not in v]}
1237
1238 loop_val = navigate_value(opts1, ["data_volumes"])
1239 if not loop_val:
1240 return
1241
1242 for i in range(len(loop_val)):
1243 r = send_delete_volume_request(module, None, client, loop_val[i])
1244 async_wait(config, r, client, timeout)
1245
1246
1247 def multi_invoke_attach_data_disk(config, opts, client, timeout):
1248 module = config.module
1249
1250 opts1 = opts
1251 expect = opts["data_volumes"]
1252 current = opts["current_state"]["data_volumes"]
1253 if expect and current:
1254 v = [i["volume_id"] for i in current]
1255 opts1 = {"data_volumes": [i for i in expect if i["volume_id"] not in v]}
1256
1257 loop_val = navigate_value(opts1, ["data_volumes"])
1258 if not loop_val:
1259 return
1260
1261 for i in range(len(loop_val)):
1262 params = build_attach_data_disk_parameters(opts1, {"data_volumes": i})
1263 r = send_attach_data_disk_request(module, params, client)
1264 async_wait(config, r, client, timeout)
1265
1266
1267 def send_read_request(module, client):
1268 url = build_path(module, "cloudservers/{id}")
1269
1270 r = None
1271 try:
1272 r = client.get(url)
1273 except HwcClientException as ex:
1274 msg = f"module(hwc_ecs_instance): error running api(read), error: {ex}"
1275 module.fail_json(msg=msg)
1276
1277 return navigate_value(r, ["server"], None)
1278
1279
1280 def fill_read_resp_body(body):
1281 result = dict()
1282
1283 result["OS-DCF:diskConfig"] = body.get("OS-DCF:diskConfig")
1284
1285 result["OS-EXT-AZ:availability_zone"] = body.get("OS-EXT-AZ:availability_zone")
1286
1287 result["OS-EXT-SRV-ATTR:hostname"] = body.get("OS-EXT-SRV-ATTR:hostname")
1288
1289 result["OS-EXT-SRV-ATTR:instance_name"] = body.get("OS-EXT-SRV-ATTR:instance_name")
1290
1291 result["OS-EXT-SRV-ATTR:user_data"] = body.get("OS-EXT-SRV-ATTR:user_data")
1292
1293 result["OS-EXT-STS:power_state"] = body.get("OS-EXT-STS:power_state")
1294
1295 v = fill_read_resp_address(body.get("address"))
1296 result["address"] = v
1297
1298 result["config_drive"] = body.get("config_drive")
1299
1300 result["created"] = body.get("created")
1301
1302 result["description"] = body.get("description")
1303
1304 result["enterprise_project_id"] = body.get("enterprise_project_id")
1305
1306 v = fill_read_resp_flavor(body.get("flavor"))
1307 result["flavor"] = v
1308
1309 result["id"] = body.get("id")
1310
1311 v = fill_read_resp_image(body.get("image"))
1312 result["image"] = v
1313
1314 result["key_name"] = body.get("key_name")
1315
1316 v = fill_read_resp_metadata(body.get("metadata"))
1317 result["metadata"] = v
1318
1319 result["name"] = body.get("name")
1320
1321 v = fill_read_resp_os_extended_volumes_volumes_attached(body.get("os-extended-volumes:volumes_attached"))
1322 result["os-extended-volumes:volumes_attached"] = v
1323
1324 v = fill_read_resp_root_volume(body.get("root_volume"))
1325 result["root_volume"] = v
1326
1327 result["status"] = body.get("status")
1328
1329 result["tags"] = body.get("tags")
1330
1331 return result
1332
1333
1334 def fill_read_resp_address(value):
1335 if not value:
1336 return None
1337
1338 result = []
1339 for item in value:
1340 val = dict()
1341
1342 val["OS-EXT-IPS:port_id"] = item.get("OS-EXT-IPS:port_id")
1343
1344 val["OS-EXT-IPS:type"] = item.get("OS-EXT-IPS:type")
1345
1346 val["addr"] = item.get("addr")
1347
1348 result.append(val)
1349
1350 return result
1351
1352
1353 def fill_read_resp_flavor(value):
1354 if not value:
1355 return None
1356
1357 result = dict()
1358
1359 result["id"] = value.get("id")
1360
1361 return result
1362
1363
1364 def fill_read_resp_image(value):
1365 if not value:
1366 return None
1367
1368 result = dict()
1369
1370 result["id"] = value.get("id")
1371
1372 return result
1373
1374
1375 def fill_read_resp_metadata(value):
1376 if not value:
1377 return None
1378
1379 result = dict()
1380
1381 result["image_name"] = value.get("image_name")
1382
1383 result["vpc_id"] = value.get("vpc_id")
1384
1385 return result
1386
1387
1388 def fill_read_resp_os_extended_volumes_volumes_attached(value):
1389 if not value:
1390 return None
1391
1392 result = []
1393 for item in value:
1394 val = dict()
1395
1396 val["bootIndex"] = item.get("bootIndex")
1397
1398 val["device"] = item.get("device")
1399
1400 val["id"] = item.get("id")
1401
1402 result.append(val)
1403
1404 return result
1405
1406
1407 def fill_read_resp_root_volume(value):
1408 if not value:
1409 return None
1410
1411 result = dict()
1412
1413 result["device"] = value.get("device")
1414
1415 result["id"] = value.get("id")
1416
1417 return result
1418
1419
1420 def send_read_auto_recovery_request(module, client):
1421 url = build_path(module, "cloudservers/{id}/autorecovery")
1422
1423 r = None
1424 try:
1425 r = client.get(url)
1426 except HwcClientException as ex:
1427 msg = f"module(hwc_ecs_instance): error running api(read_auto_recovery), error: {ex}"
1428 module.fail_json(msg=msg)
1429
1430 return r
1431
1432
1433 def fill_read_auto_recovery_resp_body(body):
1434 result = dict()
1435
1436 result["support_auto_recovery"] = body.get("support_auto_recovery")
1437
1438 return result
1439
1440
1441 def flatten_options(response, array_index):
1442 r = dict()
1443
1444 v = navigate_value(response, ["read", "OS-EXT-AZ:availability_zone"], array_index)
1445 r["availability_zone"] = v
1446
1447 v = navigate_value(response, ["read", "config_drive"], array_index)
1448 r["config_drive"] = v
1449
1450 v = navigate_value(response, ["read", "created"], array_index)
1451 r["created"] = v
1452
1453 v = flatten_data_volumes(response, array_index)
1454 r["data_volumes"] = v
1455
1456 v = navigate_value(response, ["read", "description"], array_index)
1457 r["description"] = v
1458
1459 v = navigate_value(response, ["read", "OS-DCF:diskConfig"], array_index)
1460 r["disk_config_type"] = v
1461
1462 v = flatten_enable_auto_recovery(response, array_index)
1463 r["enable_auto_recovery"] = v
1464
1465 v = navigate_value(response, ["read", "enterprise_project_id"], array_index)
1466 r["enterprise_project_id"] = v
1467
1468 v = navigate_value(response, ["read", "flavor", "id"], array_index)
1469 r["flavor_name"] = v
1470
1471 v = navigate_value(response, ["read", "OS-EXT-SRV-ATTR:hostname"], array_index)
1472 r["host_name"] = v
1473
1474 v = navigate_value(response, ["read", "image", "id"], array_index)
1475 r["image_id"] = v
1476
1477 v = navigate_value(response, ["read", "metadata", "image_name"], array_index)
1478 r["image_name"] = v
1479
1480 v = navigate_value(response, ["read", "name"], array_index)
1481 r["name"] = v
1482
1483 v = flatten_nics(response, array_index)
1484 r["nics"] = v
1485
1486 v = navigate_value(response, ["read", "OS-EXT-STS:power_state"], array_index)
1487 r["power_state"] = v
1488
1489 v = flatten_root_volume(response, array_index)
1490 r["root_volume"] = v
1491
1492 v = navigate_value(response, ["read", "OS-EXT-SRV-ATTR:instance_name"], array_index)
1493 r["server_alias"] = v
1494
1495 v = flatten_server_tags(response, array_index)
1496 r["server_tags"] = v
1497
1498 v = navigate_value(response, ["read", "key_name"], array_index)
1499 r["ssh_key_name"] = v
1500
1501 v = navigate_value(response, ["read", "status"], array_index)
1502 r["status"] = v
1503
1504 v = navigate_value(response, ["read", "OS-EXT-SRV-ATTR:user_data"], array_index)
1505 r["user_data"] = v
1506
1507 v = navigate_value(response, ["read", "metadata", "vpc_id"], array_index)
1508 r["vpc_id"] = v
1509
1510 return r
1511
1512
1513 def flatten_data_volumes(d, array_index):
1514 v = navigate_value(d, ["read", "os-extended-volumes:volumes_attached"], array_index)
1515 if not v:
1516 return None
1517 n = len(v)
1518 result = []
1519
1520 new_ai = dict()
1521 if array_index:
1522 new_ai.update(array_index)
1523
1524 for i in range(n):
1525 new_ai["read.os-extended-volumes:volumes_attached"] = i
1526
1527 val = dict()
1528
1529 v = navigate_value(d, ["read", "os-extended-volumes:volumes_attached", "device"], new_ai)
1530 val["device"] = v
1531
1532 v = navigate_value(d, ["read", "os-extended-volumes:volumes_attached", "id"], new_ai)
1533 val["volume_id"] = v
1534
1535 for v in val.values():
1536 if v is not None:
1537 result.append(val)
1538 break
1539
1540 return result if result else None
1541
1542
1543 def flatten_enable_auto_recovery(d, array_index):
1544 v = navigate_value(d, ["read_auto_recovery", "support_auto_recovery"], array_index)
1545 return v == "true"
1546
1547
1548 def flatten_nics(d, array_index):
1549 v = navigate_value(d, ["read", "address"], array_index)
1550 if not v:
1551 return None
1552 n = len(v)
1553 result = []
1554
1555 new_ai = dict()
1556 if array_index:
1557 new_ai.update(array_index)
1558
1559 for i in range(n):
1560 new_ai["read.address"] = i
1561
1562 val = dict()
1563
1564 v = navigate_value(d, ["read", "address", "addr"], new_ai)
1565 val["ip_address"] = v
1566
1567 v = navigate_value(d, ["read", "address", "OS-EXT-IPS:port_id"], new_ai)
1568 val["port_id"] = v
1569
1570 for v in val.values():
1571 if v is not None:
1572 result.append(val)
1573 break
1574
1575 return result if result else None
1576
1577
1578 def flatten_root_volume(d, array_index):
1579 result = dict()
1580
1581 v = navigate_value(d, ["read", "root_volume", "device"], array_index)
1582 result["device"] = v
1583
1584 v = navigate_value(d, ["read", "root_volume", "id"], array_index)
1585 result["volume_id"] = v
1586
1587 for v in result.values():
1588 if v is not None:
1589 return result
1590 return None
1591
1592
1593 def flatten_server_tags(d, array_index):
1594 v = navigate_value(d, ["read", "tags"], array_index)
1595 if not v:
1596 return None
1597
1598 r = dict()
1599 for item in v:
1600 v1 = item.split("=")
1601 if v1:
1602 r[v1[0]] = v1[1]
1603 return r
1604
1605
1606 def adjust_options(opts, states):
1607 adjust_data_volumes(opts, states)
1608
1609 adjust_nics(opts, states)
1610
1611
1612 def adjust_data_volumes(parent_input, parent_cur):
1613 iv = parent_input.get("data_volumes")
1614 if not (iv and isinstance(iv, list)):
1615 return
1616
1617 cv = parent_cur.get("data_volumes")
1618 if not (cv and isinstance(cv, list)):
1619 return
1620
1621 lcv = len(cv)
1622 result = []
1623 q = []
1624 for iiv in iv:
1625 if len(q) == lcv:
1626 break
1627
1628 icv = None
1629 for j in range(lcv):
1630 if j in q:
1631 continue
1632
1633 icv = cv[j]
1634
1635 if iiv["volume_id"] != icv["volume_id"]:
1636 continue
1637
1638 result.append(icv)
1639 q.append(j)
1640 break
1641 else:
1642 break
1643
1644 if len(q) != lcv:
1645 for i in range(lcv):
1646 if i not in q:
1647 result.append(cv[i])
1648
1649 if len(result) != lcv:
1650 raise Exception("adjust property(data_volumes) failed, the array number is not equal")
1651
1652 parent_cur["data_volumes"] = result
1653
1654
1655 def adjust_nics(parent_input, parent_cur):
1656 iv = parent_input.get("nics")
1657 if not (iv and isinstance(iv, list)):
1658 return
1659
1660 cv = parent_cur.get("nics")
1661 if not (cv and isinstance(cv, list)):
1662 return
1663
1664 lcv = len(cv)
1665 result = []
1666 q = []
1667 for iiv in iv:
1668 if len(q) == lcv:
1669 break
1670
1671 icv = None
1672 for j in range(lcv):
1673 if j in q:
1674 continue
1675
1676 icv = cv[j]
1677
1678 if iiv["ip_address"] != icv["ip_address"]:
1679 continue
1680
1681 result.append(icv)
1682 q.append(j)
1683 break
1684 else:
1685 break
1686
1687 if len(q) != lcv:
1688 for i in range(lcv):
1689 if i not in q:
1690 result.append(cv[i])
1691
1692 if len(result) != lcv:
1693 raise Exception("adjust property(nics) failed, the array number is not equal")
1694
1695 parent_cur["nics"] = result
1696
1697
1698 def set_unreadable_options(opts, states):
1699 states["admin_pass"] = opts.get("admin_pass")
1700
1701 states["eip_id"] = opts.get("eip_id")
1702
1703 set_unread_nics(opts.get("nics"), states.get("nics"))
1704
1705 set_unread_root_volume(opts.get("root_volume"), states.get("root_volume"))
1706
1707 states["security_groups"] = opts.get("security_groups")
1708
1709 states["server_metadata"] = opts.get("server_metadata")
1710
1711
1712 def set_unread_nics(inputv, curv):
1713 if not (inputv and isinstance(inputv, list)):
1714 return
1715
1716 if not (curv and isinstance(curv, list)):
1717 return
1718
1719 lcv = len(curv)
1720 q = []
1721 for iv in inputv:
1722 if len(q) == lcv:
1723 break
1724
1725 cv = None
1726 for j in range(lcv):
1727 if j in q:
1728 continue
1729
1730 cv = curv[j]
1731
1732 if iv["ip_address"] != cv["ip_address"]:
1733 continue
1734
1735 q.append(j)
1736 break
1737 else:
1738 continue
1739
1740 cv["subnet_id"] = iv.get("subnet_id")
1741
1742
1743 def set_unread_root_volume(inputv, curv):
1744 if not (inputv and isinstance(inputv, dict)):
1745 return
1746
1747 if not (curv and isinstance(curv, dict)):
1748 return
1749
1750 curv["size"] = inputv.get("size")
1751
1752 curv["snapshot_id"] = inputv.get("snapshot_id")
1753
1754 curv["volume_type"] = inputv.get("volume_type")
1755
1756
1757 def set_readonly_options(opts, states):
1758 opts["config_drive"] = states.get("config_drive")
1759
1760 opts["created"] = states.get("created")
1761
1762 opts["disk_config_type"] = states.get("disk_config_type")
1763
1764 opts["host_name"] = states.get("host_name")
1765
1766 opts["image_name"] = states.get("image_name")
1767
1768 set_readonly_nics(opts.get("nics"), states.get("nics"))
1769
1770 opts["power_state"] = states.get("power_state")
1771
1772 set_readonly_root_volume(opts.get("root_volume"), states.get("root_volume"))
1773
1774 opts["server_alias"] = states.get("server_alias")
1775
1776 opts["status"] = states.get("status")
1777
1778
1779 def set_readonly_nics(inputv, curv):
1780 if not (curv and isinstance(curv, list)):
1781 return
1782
1783 if not (inputv and isinstance(inputv, list)):
1784 return
1785
1786 lcv = len(curv)
1787 q = []
1788 for iv in inputv:
1789 if len(q) == lcv:
1790 break
1791
1792 cv = None
1793 for j in range(lcv):
1794 if j in q:
1795 continue
1796
1797 cv = curv[j]
1798
1799 if iv["ip_address"] != cv["ip_address"]:
1800 continue
1801
1802 q.append(j)
1803 break
1804 else:
1805 continue
1806
1807 iv["port_id"] = cv.get("port_id")
1808
1809
1810 def set_readonly_root_volume(inputv, curv):
1811 if not (inputv and isinstance(inputv, dict)):
1812 return
1813
1814 if not (curv and isinstance(curv, dict)):
1815 return
1816
1817 inputv["device"] = curv.get("device")
1818
1819 inputv["volume_id"] = curv.get("volume_id")
1820
1821
1822 def send_list_request(module, client, url):
1823 r = None
1824 try:
1825 r = client.get(url)
1826 except HwcClientException as ex:
1827 msg = f"module(hwc_ecs_instance): error running api(list), error: {ex}"
1828 module.fail_json(msg=msg)
1829
1830 return navigate_value(r, ["servers"], None)
1831
1832
1833 def _build_identity_object(all_opts):
1834 result = dict()
1835
1836 result["OS-DCF:diskConfig"] = None
1837
1838 v = navigate_value(all_opts, ["availability_zone"], None)
1839 result["OS-EXT-AZ:availability_zone"] = v
1840
1841 result["OS-EXT-SRV-ATTR:hostname"] = None
1842
1843 result["OS-EXT-SRV-ATTR:instance_name"] = None
1844
1845 v = navigate_value(all_opts, ["user_data"], None)
1846 result["OS-EXT-SRV-ATTR:user_data"] = v
1847
1848 result["OS-EXT-STS:power_state"] = None
1849
1850 result["config_drive"] = None
1851
1852 result["created"] = None
1853
1854 v = navigate_value(all_opts, ["description"], None)
1855 result["description"] = v
1856
1857 v = navigate_value(all_opts, ["enterprise_project_id"], None)
1858 result["enterprise_project_id"] = v
1859
1860 v = expand_list_flavor(all_opts, None)
1861 result["flavor"] = v
1862
1863 result["id"] = None
1864
1865 v = expand_list_image(all_opts, None)
1866 result["image"] = v
1867
1868 v = navigate_value(all_opts, ["ssh_key_name"], None)
1869 result["key_name"] = v
1870
1871 v = expand_list_metadata(all_opts, None)
1872 result["metadata"] = v
1873
1874 v = navigate_value(all_opts, ["name"], None)
1875 result["name"] = v
1876
1877 result["status"] = None
1878
1879 v = expand_list_tags(all_opts, None)
1880 result["tags"] = v
1881
1882 return result
1883
1884
1885 def expand_list_flavor(d, array_index):
1886 r = dict()
1887
1888 v = navigate_value(d, ["flavor_name"], array_index)
1889 r["id"] = v
1890
1891 for v in r.values():
1892 if v is not None:
1893 return r
1894 return None
1895
1896
1897 def expand_list_image(d, array_index):
1898 r = dict()
1899
1900 v = navigate_value(d, ["image_id"], array_index)
1901 r["id"] = v
1902
1903 for v in r.values():
1904 if v is not None:
1905 return r
1906 return None
1907
1908
1909 def expand_list_metadata(d, array_index):
1910 r = dict()
1911
1912 v = navigate_value(d, ["vpc_id"], array_index)
1913 r["vpc_id"] = v
1914
1915 for v in r.values():
1916 if v is not None:
1917 return r
1918 return None
1919
1920
1921 def expand_list_tags(d, array_index):
1922 v = d.get("server_tags")
1923 if not v:
1924 return None
1925
1926 return [f"{k}={v1}" for k, v1 in v.items()]
1927
1928
1929 def fill_list_resp_body(body):
1930 result = dict()
1931
1932 result["OS-DCF:diskConfig"] = body.get("OS-DCF:diskConfig")
1933
1934 result["OS-EXT-AZ:availability_zone"] = body.get("OS-EXT-AZ:availability_zone")
1935
1936 result["OS-EXT-SRV-ATTR:hostname"] = body.get("OS-EXT-SRV-ATTR:hostname")
1937
1938 result["OS-EXT-SRV-ATTR:instance_name"] = body.get("OS-EXT-SRV-ATTR:instance_name")
1939
1940 result["OS-EXT-SRV-ATTR:user_data"] = body.get("OS-EXT-SRV-ATTR:user_data")
1941
1942 result["OS-EXT-STS:power_state"] = body.get("OS-EXT-STS:power_state")
1943
1944 result["config_drive"] = body.get("config_drive")
1945
1946 result["created"] = body.get("created")
1947
1948 result["description"] = body.get("description")
1949
1950 result["enterprise_project_id"] = body.get("enterprise_project_id")
1951
1952 v = fill_list_resp_flavor(body.get("flavor"))
1953 result["flavor"] = v
1954
1955 result["id"] = body.get("id")
1956
1957 v = fill_list_resp_image(body.get("image"))
1958 result["image"] = v
1959
1960 result["key_name"] = body.get("key_name")
1961
1962 v = fill_list_resp_metadata(body.get("metadata"))
1963 result["metadata"] = v
1964
1965 result["name"] = body.get("name")
1966
1967 result["status"] = body.get("status")
1968
1969 result["tags"] = body.get("tags")
1970
1971 return result
1972
1973
1974 def fill_list_resp_flavor(value):
1975 if not value:
1976 return None
1977
1978 result = dict()
1979
1980 result["id"] = value.get("id")
1981
1982 return result
1983
1984
1985 def fill_list_resp_image(value):
1986 if not value:
1987 return None
1988
1989 result = dict()
1990
1991 result["id"] = value.get("id")
1992
1993 return result
1994
1995
1996 def fill_list_resp_metadata(value):
1997 if not value:
1998 return None
1999
2000 result = dict()
2001
2002 result["vpc_id"] = value.get("vpc_id")
2003
2004 return result
2005
2006
2007 def adjust_list_resp(opts, resp):
2008 adjust_list_api_tags(opts, resp)
2009
2010
2011 def adjust_list_api_tags(parent_input, parent_cur):
2012 iv = parent_input.get("tags")
2013 if not (iv and isinstance(iv, list)):
2014 return
2015
2016 cv = parent_cur.get("tags")
2017 if not (cv and isinstance(cv, list)):
2018 return
2019
2020 result = []
2021 for iiv in iv:
2022 if iiv not in cv:
2023 break
2024
2025 result.append(iiv)
2026
2027 j = cv.index(iiv)
2028 cv[j] = cv[-1]
2029 cv.pop()
2030
2031 if cv:
2032 result.extend(cv)
2033 parent_cur["tags"] = result
2034
2035
2036 if __name__ == "__main__":
2037 main()