Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # Copyright (c) 2017, Milan Ilic <[email protected]>
3 # Copyright (c) 2019, Jan Meerkamp <[email protected]>
4 # Copyright (c) 2025, Tom Paine <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 # Make coding more python3-ish
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: one_vm
13 short_description: Creates or terminates OpenNebula instances
14 description:
15 - Manages OpenNebula instances.
16 requirements:
17 - pyone
18 extends_documentation_fragment:
19 - community.general._attributes
20 attributes:
21 check_mode:
22 support: full
23 diff_mode:
24 support: none
25 options:
26 api_url:
27 description:
28 - URL of the OpenNebula RPC server.
29 - It is recommended to use HTTPS so that the username/password are not transferred over the network unencrypted.
30 - If not set then the value of the E(ONE_URL) environment variable is used.
31 type: str
32 api_username:
33 description:
34 - Name of the user to login into the OpenNebula RPC server. If not set then the value of the E(ONE_USERNAME) environment
35 variable is used.
36 type: str
37 api_password:
38 description:
39 - Password of the user to login into OpenNebula RPC server. If not set then the value of the E(ONE_PASSWORD) environment
40 variable is used. if both O(api_username) or O(api_password) are not set, then it tries to authenticate with ONE auth
41 file. Default path is C(~/.one/one_auth).
42 - Set environment variable E(ONE_AUTH) to override this path.
43 type: str
44 template_name:
45 description:
46 - Name of VM template to use to create a new instance.
47 type: str
48 template_id:
49 description:
50 - ID of a VM template to use to create a new instance.
51 type: int
52 vm_start_on_hold:
53 description:
54 - Set to true to put VM on hold while creating.
55 default: false
56 type: bool
57 instance_ids:
58 description:
59 - 'A list of instance IDs used for states: V(absent), V(running), V(rebooted), V(poweredoff).'
60 aliases: ['ids']
61 type: list
62 elements: int
63 state:
64 description:
65 - V(present) - create instances from a template specified with C(template_id)/C(template_name).
66 - V(running) - run instances.
67 - V(poweredoff) - power-off instances.
68 - V(rebooted) - reboot instances.
69 - V(absent) - terminate instances.
70 choices: ["present", "absent", "running", "rebooted", "poweredoff"]
71 default: present
72 type: str
73 hard:
74 description:
75 - Reboot, power-off or terminate instances C(hard).
76 default: false
77 type: bool
78 wait:
79 description:
80 - Wait for the instance to reach its desired state before returning. Keep in mind if you are waiting for instance to
81 be in running state it does not mean that you are able to SSH on that machine only that boot process have started
82 on that instance. See the example using the M(ansible.builtin.wait_for) module for details.
83 default: true
84 type: bool
85 wait_timeout:
86 description:
87 - How long before wait gives up, in seconds.
88 default: 300
89 type: int
90 attributes:
91 description:
92 - A dictionary of key/value attributes to add to new instances, or for setting C(state) of instances with these attributes.
93 - Keys are case insensitive and OpenNebula automatically converts them to upper case.
94 - Be aware V(NAME) is a special attribute which sets the name of the VM when it is deployed.
95 - C(#) character(s) can be appended to the C(NAME) and the module automatically adds indexes to the names of VMs.
96 - 'For example: V(NAME: foo-###) would create VMs with names V(foo-000), V(foo-001),...'
97 - When used with O(count_attributes) and O(exact_count) the module matches the base name without the index part.
98 default: {}
99 type: dict
100 labels:
101 description:
102 - A list of labels to associate with new instances, or for setting C(state) of instances with these labels.
103 default: []
104 type: list
105 elements: str
106 count_attributes:
107 description:
108 - A dictionary of key/value attributes that can only be used with O(exact_count) to determine how many nodes based on
109 a specific attributes criteria should be deployed. This can be expressed in multiple ways and is shown in the EXAMPLES
110 section.
111 type: dict
112 count_labels:
113 description:
114 - A list of labels that can only be used with O(exact_count) to determine how many nodes based on a specific labels
115 criteria should be deployed. This can be expressed in multiple ways and is shown in the EXAMPLES section.
116 type: list
117 elements: str
118 count:
119 description:
120 - Number of instances to launch.
121 default: 1
122 type: int
123 exact_count:
124 description:
125 - Indicates how many instances that match O(count_attributes) and O(count_labels) parameters should be deployed. Instances
126 are either created or terminated based on this value.
127 - B(NOTE:) Instances with the least IDs are terminated first.
128 type: int
129 mode:
130 description:
131 - Set permission mode of the instance in octet format, for example V(0600) to give owner C(use) and C(manage) and nothing
132 to group and others.
133 type: str
134 owner_id:
135 description:
136 - ID of the user which is set as the owner of the instance.
137 type: int
138 group_id:
139 description:
140 - ID of the group which is set as the group of the instance.
141 type: int
142 memory:
143 description:
144 - The size of the memory for new instances (in MB, GB, ..).
145 type: str
146 disk_size:
147 description:
148 - The size of the disk created for new instances (in MB, GB, TB,...).
149 - B(NOTE:) If The Template hats Multiple Disks the Order of the Sizes is matched against the order specified in O(template_id)/O(template_name).
150 type: list
151 elements: str
152 cpu:
153 description:
154 - Percentage of CPU divided by 100 required for the new instance. Half a processor is written 0.5.
155 type: float
156 vcpu:
157 description:
158 - Number of CPUs (cores) the new VM uses.
159 type: int
160 networks:
161 description:
162 - A list of dictionaries with network parameters. See examples for more details.
163 default: []
164 type: list
165 elements: dict
166 disk_saveas:
167 description:
168 - Creates an image from a VM disk.
169 - It is a dictionary where you have to specify C(name) of the new image.
170 - Optionally you can specify C(disk_id) of the disk you want to save. By default C(disk_id) is 0.
171 - B(NOTE:) This operation is only performed on the first VM (if more than one VM ID is passed) and the VM has to be
172 in the C(poweredoff) state.
173 - Also this operation fails if an image with specified C(name) already exists.
174 type: dict
175 persistent:
176 description:
177 - Create a private persistent copy of the template plus any image defined in DISK, and instantiate that copy.
178 default: false
179 type: bool
180 version_added: '0.2.0'
181 datastore_id:
182 description:
183 - Name of Datastore to use to create a new instance.
184 version_added: '0.2.0'
185 type: int
186 datastore_name:
187 description:
188 - Name of Datastore to use to create a new instance.
189 version_added: '0.2.0'
190 type: str
191 updateconf:
192 description:
193 - When O(instance_ids) is provided, updates running VMs with the C(updateconf) API call.
194 - When new VMs are being created, emulates the C(updateconf) API call using direct template merge.
195 - Allows for complete modifications of the C(CONTEXT) attribute.
196 - 'Supported attributes include:'
197 - B(BACKUP_CONFIG:) V(BACKUP_VOLATILE), V(FS_FREEZE), V(INCREMENT_MODE), V(KEEP_LAST), V(MODE);
198 - B(CONTEXT:) (Any value, except V(ETH*). Variable substitutions are made);
199 - B(CPU_MODEL:) V(FEATURES), V(MODEL);
200 - B(FEATURES:) V(ACPI), V(APIC), V(GUEST_AGENT), V(HYPERV), V(IOTHREADS), V(LOCALTIME), V(PAE), V(VIRTIO_BLK_QUEUES),
201 V(VIRTIO_SCSI_QUEUES);
202 - B(GRAPHICS:) V(COMMAND), V(KEYMAP), V(LISTEN), V(PASSWD), V(PORT), V(TYPE);
203 - B(INPUT:) V(BUS), V(TYPE);
204 - B(OS:) V(ARCH), V(BOOT), V(BOOTLOADER), V(FIRMWARE), V(INITRD), V(KERNEL), V(KERNEL_CMD), V(MACHINE), V(ROOT), V(SD_DISK_BUS),
205 V(UUID);
206 - B(RAW:) V(DATA), V(DATA_VMX), V(TYPE), V(VALIDATE);
207 - B(VIDEO:) V(ATS), V(IOMMU), V(RESOLUTION), V(TYPE), V(VRAM).
208 type: dict
209 version_added: 6.3.0
210 author:
211 - "Milan Ilic (@ilicmilan)"
212 - "Jan Meerkamp (@meerkampdvv)"
213 """
214
215
216 EXAMPLES = r"""
217 - name: Create a new instance
218 community.general.one_vm:
219 template_id: 90
220 register: result
221
222 - name: Print VM properties
223 ansible.builtin.debug:
224 msg: result
225
226 - name: Deploy a new VM on hold
227 community.general.one_vm:
228 template_name: 'app1_template'
229 vm_start_on_hold: 'True'
230
231 - name: Deploy a new VM and set its name to 'foo'
232 community.general.one_vm:
233 template_name: 'app1_template'
234 attributes:
235 name: foo
236
237 - name: Deploy a new VM and set its group_id and mode
238 community.general.one_vm:
239 template_id: 90
240 group_id: 16
241 mode: 660
242
243 - name: Deploy a new VM as persistent
244 community.general.one_vm:
245 template_id: 90
246 persistent: true
247
248 - name: Change VM's permissions to 640
249 community.general.one_vm:
250 instance_ids: 5
251 mode: 640
252
253 - name: Deploy 2 new instances and set memory, vcpu, disk_size and 3 networks
254 community.general.one_vm:
255 template_id: 15
256 disk_size: 35.2 GB
257 memory: 4 GB
258 vcpu: 4
259 count: 2
260 networks:
261 - NETWORK_ID: 27
262 - NETWORK: "default-network"
263 NETWORK_UNAME: "app-user"
264 SECURITY_GROUPS: "120,124"
265 - NETWORK_ID: 27
266 SECURITY_GROUPS: "10"
267
268 - name: Deploy a new instance which uses a Template with two Disks
269 community.general.one_vm:
270 template_id: 42
271 disk_size:
272 - 35.2 GB
273 - 50 GB
274 memory: 4 GB
275 vcpu: 4
276 count: 1
277 networks:
278 - NETWORK_ID: 27
279
280 - name: "Deploy an new instance with attribute 'bar: bar1' and set its name to 'foo'"
281 community.general.one_vm:
282 template_id: 53
283 attributes:
284 name: foo
285 bar: bar1
286
287 - name: "Enforce that 2 instances with attributes 'foo1: app1' and 'foo2: app2' are deployed"
288 community.general.one_vm:
289 template_id: 53
290 attributes:
291 foo1: app1
292 foo2: app2
293 exact_count: 2
294 count_attributes:
295 foo1: app1
296 foo2: app2
297
298 - name: Enforce that 4 instances with an attribute 'bar' are deployed
299 community.general.one_vm:
300 template_id: 53
301 attributes:
302 name: app
303 bar: bar2
304 exact_count: 4
305 count_attributes:
306 bar:
307
308 # Deploy 2 new instances with attribute 'foo: bar' and labels 'app1' and 'app2' and names in format 'fooapp-##'
309 # Names will be: fooapp-00 and fooapp-01
310 - name: Deploy 2 new instances
311 community.general.one_vm:
312 template_id: 53
313 attributes:
314 name: fooapp-##
315 foo: bar
316 labels:
317 - app1
318 - app2
319 count: 2
320
321 # Deploy 2 new instances with attribute 'app: app1' and names in format 'fooapp-###'
322 # Names will be: fooapp-002 and fooapp-003
323 - name: Deploy 2 new instances
324 community.general.one_vm:
325 template_id: 53
326 attributes:
327 name: fooapp-###
328 app: app1
329 count: 2
330
331 # Reboot all instances with name in format 'fooapp-#'
332 # Instances 'fooapp-00', 'fooapp-01', 'fooapp-002' and 'fooapp-003' will be rebooted
333 - name: Reboot all instances with names in a certain format
334 community.general.one_vm:
335 attributes:
336 name: fooapp-#
337 state: rebooted
338
339 # Enforce that only 1 instance with name in format 'fooapp-#' is deployed
340 # The task will delete oldest instances, so only the 'fooapp-003' will remain
341 - name: Enforce that only 1 instance with name in a certain format is deployed
342 community.general.one_vm:
343 template_id: 53
344 exact_count: 1
345 count_attributes:
346 name: fooapp-#
347
348 - name: Deploy an new instance with a network
349 community.general.one_vm:
350 template_id: 53
351 networks:
352 - NETWORK_ID: 27
353 register: vm
354
355 - name: Wait for SSH to come up
356 ansible.builtin.wait_for:
357 port: 22
358 host: '{{ vm.instances[0].networks[0].ip }}'
359
360 - name: Terminate VMs by ids
361 community.general.one_vm:
362 instance_ids:
363 - 153
364 - 160
365 state: absent
366
367 - name: Reboot all VMs that have labels 'foo' and 'app1'
368 community.general.one_vm:
369 labels:
370 - foo
371 - app1
372 state: rebooted
373
374 - name: "Fetch all VMs that have name 'foo' and attribute 'app: bar'"
375 community.general.one_vm:
376 attributes:
377 name: foo
378 app: bar
379 register: results
380
381 - name: Deploy 2 new instances with labels 'foo1' and 'foo2'
382 community.general.one_vm:
383 template_name: app_template
384 labels:
385 - foo1
386 - foo2
387 count: 2
388
389 - name: Enforce that only 1 instance with label 'foo1' will be running
390 community.general.one_vm:
391 template_name: app_template
392 labels:
393 - foo1
394 exact_count: 1
395 count_labels:
396 - foo1
397
398 - name: Terminate all instances that have attribute foo
399 community.general.one_vm:
400 template_id: 53
401 exact_count: 0
402 count_attributes:
403 foo:
404
405 - name: "Power-off the VM and save VM's disk with id=0 to the image with name 'foo-image'"
406 community.general.one_vm:
407 instance_ids: 351
408 state: poweredoff
409 disk_saveas:
410 name: foo-image
411
412 - name: "Save VM's disk with id=1 to the image with name 'bar-image'"
413 community.general.one_vm:
414 instance_ids: 351
415 disk_saveas:
416 name: bar-image
417 disk_id: 1
418
419 - name: "Deploy 2 new instances with a custom 'start script'"
420 community.general.one_vm:
421 template_name: app_template
422 count: 2
423 updateconf:
424 CONTEXT:
425 START_SCRIPT: ip r r 169.254.16.86/32 dev eth0
426
427 - name: "Add a custom 'start script' to a running VM"
428 community.general.one_vm:
429 instance_ids: 351
430 updateconf:
431 CONTEXT:
432 START_SCRIPT: ip r r 169.254.16.86/32 dev eth0
433
434 - name: "Update SSH public keys inside the VM's context"
435 community.general.one_vm:
436 instance_ids: 351
437 updateconf:
438 CONTEXT:
439 SSH_PUBLIC_KEY: |-
440 ssh-rsa ...
441 ssh-ed25519 ...
442 """
443
444 RETURN = r"""
445 instances_ids:
446 description: A list of instances IDs whose state is changed or which are fetched with O(instance_ids) option.
447 type: list
448 returned: success
449 sample: [1234, 1235]
450 instances:
451 description: A list of instances info whose state is changed or which are fetched with O(instance_ids) option.
452 type: list
453 elements: dict
454 returned: success
455 contains:
456 vm_id:
457 description: VM ID.
458 type: int
459 sample: 153
460 vm_name:
461 description: VM name.
462 type: str
463 sample: foo
464 template_id:
465 description: VM's template ID.
466 type: int
467 sample: 153
468 group_id:
469 description: VM's group ID.
470 type: int
471 sample: 1
472 group_name:
473 description: VM's group name.
474 type: str
475 sample: one-users
476 owner_id:
477 description: VM's owner ID.
478 type: int
479 sample: 143
480 owner_name:
481 description: VM's owner name.
482 type: str
483 sample: app-user
484 mode:
485 description: VM's mode.
486 type: str
487 returned: success
488 sample: 660
489 state:
490 description: State of an instance.
491 type: str
492 sample: ACTIVE
493 lcm_state:
494 description: Lcm state of an instance that is only relevant when the state is ACTIVE.
495 type: str
496 sample: RUNNING
497 cpu:
498 description: Percentage of CPU divided by 100.
499 type: float
500 sample: 0.2
501 vcpu:
502 description: Number of CPUs (cores).
503 type: int
504 sample: 2
505 memory:
506 description: The size of the memory in MB.
507 type: str
508 sample: 4096 MB
509 disk_size:
510 description: The size of the disk in MB.
511 type: str
512 sample: 20480 MB
513 networks:
514 description: A list of dictionaries with info about IP, NAME, MAC, SECURITY_GROUPS for each NIC.
515 type: list
516 sample:
517 [
518 {
519 "ip": "10.120.5.33",
520 "mac": "02:00:0a:78:05:21",
521 "name": "default-test-private",
522 "security_groups": "0,10"
523 },
524 {
525 "ip": "10.120.5.34",
526 "mac": "02:00:0a:78:05:22",
527 "name": "default-test-private",
528 "security_groups": "0"
529 }
530 ]
531 uptime_h:
532 description: Uptime of the instance in hours.
533 type: int
534 sample: 35
535 labels:
536 description: A list of string labels that are associated with the instance.
537 type: list
538 sample: ["foo", "spec-label"]
539 attributes:
540 description: A dictionary of key/values attributes that are associated with the instance.
541 type: dict
542 sample:
543 {
544 "HYPERVISOR": "kvm",
545 "LOGO": "images/logos/centos.png",
546 "TE_GALAXY": "bar",
547 "USER_INPUTS": null
548 }
549 updateconf:
550 description: A dictionary of key/values attributes that are set with the updateconf API call.
551 type: dict
552 version_added: 6.3.0
553 sample:
554 {
555 "OS": {
556 "ARCH": "x86_64"
557 },
558 "CONTEXT": {
559 "START_SCRIPT": "ip r r 169.254.16.86/32 dev eth0",
560 "SSH_PUBLIC_KEY": "ssh-rsa ...\\nssh-ed25519 ..."
561 }
562 }
563 tagged_instances:
564 description:
565 - A list of instances info based on a specific attributes and/or labels that are specified with O(count_attributes) and
566 O(count_labels) options.
567 type: list
568 elements: dict
569 returned: success
570 contains:
571 vm_id:
572 description: VM ID.
573 type: int
574 sample: 153
575 vm_name:
576 description: VM name.
577 type: str
578 sample: foo
579 template_id:
580 description: VM's template ID.
581 type: int
582 sample: 153
583 group_id:
584 description: VM's group ID.
585 type: int
586 sample: 1
587 group_name:
588 description: VM's group name.
589 type: str
590 sample: one-users
591 owner_id:
592 description: VM's user ID.
593 type: int
594 sample: 143
595 owner_name:
596 description: VM's user name.
597 type: str
598 sample: app-user
599 mode:
600 description: VM's mode.
601 type: str
602 returned: success
603 sample: 660
604 state:
605 description: State of an instance.
606 type: str
607 sample: ACTIVE
608 lcm_state:
609 description: Lcm state of an instance that is only relevant when the state is ACTIVE.
610 type: str
611 sample: RUNNING
612 cpu:
613 description: Percentage of CPU divided by 100.
614 type: float
615 sample: 0.2
616 vcpu:
617 description: Number of CPUs (cores).
618 type: int
619 sample: 2
620 memory:
621 description: The size of the memory in MB.
622 type: str
623 sample: 4096 MB
624 disk_size:
625 description: The size of the disk in MB.
626 type: list
627 sample: ["20480 MB", "10240 MB"]
628 networks:
629 description: A list of dictionaries with info about IP, NAME, MAC, SECURITY_GROUPS for each NIC.
630 type: list
631 sample:
632 [
633 {
634 "ip": "10.120.5.33",
635 "mac": "02:00:0a:78:05:21",
636 "name": "default-test-private",
637 "security_groups": "0,10"
638 },
639 {
640 "ip": "10.120.5.34",
641 "mac": "02:00:0a:78:05:22",
642 "name": "default-test-private",
643 "security_groups": "0"
644 }
645 ]
646 uptime_h:
647 description: Uptime of the instance in hours.
648 type: int
649 sample: 35
650 labels:
651 description: A list of string labels that are associated with the instance.
652 type: list
653 sample: ["foo", "spec-label"]
654 attributes:
655 description: A dictionary of key/values attributes that are associated with the instance.
656 type: dict
657 sample:
658 {
659 "HYPERVISOR": "kvm",
660 "LOGO": "images/logos/centos.png",
661 "TE_GALAXY": "bar",
662 "USER_INPUTS": null
663 }
664 updateconf:
665 description: A dictionary of key/values attributes that are set with the updateconf API call.
666 type: dict
667 version_added: 6.3.0
668 sample:
669 {
670 "OS": {
671 "ARCH": "x86_64"
672 },
673 "CONTEXT": {
674 "START_SCRIPT": "ip r r 169.254.16.86/32 dev eth0",
675 "SSH_PUBLIC_KEY": "ssh-rsa ...\\nssh-ed25519 ..."
676 }
677 }
678 """
679
680 try:
681 import pyone
682
683 HAS_PYONE = True
684 except ImportError:
685 HAS_PYONE = False
686
687 import copy
688 import os
689 import re
690 import time
691 from dataclasses import dataclass
692
693 from ansible.module_utils.basic import AnsibleModule
694 from ansible.module_utils.common.dict_transformations import dict_merge
695
696 from ansible_collections.community.general.plugins.module_utils._opennebula import flatten, render
697
698
699 @dataclass
700 class AuthParams:
701 url: str
702 username: str
703 password: str
704
705
706 # Updateconf attributes documentation: https://docs.opennebula.io/6.10/integration_and_development/system_interfaces/api.html#one-vm-updateconf
707 UPDATECONF_ATTRIBUTES = {
708 "OS": ["ARCH", "MACHINE", "KERNEL", "INITRD", "BOOTLOADER", "BOOT", "SD_DISK_BUS", "UUID", "FIRMWARE"],
709 "CPU_MODEL": ["MODEL", "FEATURES"],
710 "FEATURES": [
711 "ACPI",
712 "PAE",
713 "APIC",
714 "LOCALTIME",
715 "HYPERV",
716 "GUEST_AGENT",
717 "VIRTIO_BLK_QUEUES",
718 "VIRTIO_SCSI_QUEUES",
719 "IOTHREADS",
720 ],
721 "INPUT": ["TYPE", "BUS"],
722 "GRAPHICS": ["TYPE", "LISTEN", "PORT", "PASSWD", "KEYMAP", "COMMAND"],
723 "VIDEO": ["ATS", "IOMMU", "RESOLUTION", "TYPE", "VRAM"],
724 "RAW": ["DATA", "DATA_VMX", "TYPE", "VALIDATE"],
725 "CONTEXT": [],
726 "BACKUP_CONFIG": ["FS_FREEZE", "KEEP_LAST", "BACKUP_VOLATILE", "MODE", "INCREMENT_MODE"],
727 }
728
729
730 def check_updateconf(module, to_check):
731 """Checks if attributes are compatible with one.vm.updateconf API call."""
732 for attr, subattributes in to_check.items():
733 if attr not in UPDATECONF_ATTRIBUTES:
734 module.fail_json(msg=f"'{attr}' is not a valid VM attribute.")
735 if not UPDATECONF_ATTRIBUTES[attr]:
736 continue
737 for subattr in subattributes:
738 if subattr not in UPDATECONF_ATTRIBUTES[attr]:
739 module.fail_json(msg=f"'{subattr}' is not a valid VM subattribute of '{attr}'")
740
741
742 def parse_updateconf(vm_template):
743 """Extracts 'updateconf' attributes from a VM template."""
744 updateconf = {}
745 for attr, subattributes in vm_template.items():
746 if attr not in UPDATECONF_ATTRIBUTES:
747 continue
748 tmp = {}
749 for subattr, value in subattributes.items():
750 if UPDATECONF_ATTRIBUTES[attr] and subattr not in UPDATECONF_ATTRIBUTES[attr]:
751 continue
752 tmp[subattr] = value
753 if tmp:
754 updateconf[attr] = tmp
755 return updateconf
756
757
758 def get_template(module, client, predicate):
759 pool = client.templatepool.info(-2, -1, -1, -1)
760 # Filter -2 means fetch all templates user can Use
761 found = 0
762 found_template = None
763 template_name = ""
764
765 for template in pool.VMTEMPLATE:
766 if predicate(template):
767 found = found + 1
768 found_template = template
769 template_name = template.NAME
770
771 if found == 0:
772 return None
773 elif found > 1:
774 module.fail_json(msg=f"There are more templates with name: {template_name}")
775 return found_template
776
777
778 def get_template_by_name(module, client, template_name):
779 return get_template(module, client, lambda template: template_name == template.NAME)
780
781
782 def get_template_by_id(module, client, template_id):
783 return get_template(module, client, lambda template: template_id == template.ID)
784
785
786 def get_template_id(module, client, requested_id, requested_name):
787 template = (
788 get_template_by_id(module, client, requested_id)
789 if requested_id is not None
790 else get_template_by_name(module, client, requested_name)
791 )
792 if template:
793 return template.ID
794 else:
795 return None
796
797
798 def get_datastore(module, client, predicate):
799 pool = client.datastorepool.info()
800 found = 0
801 found_datastore = None
802 datastore_name = ""
803
804 for datastore in pool.DATASTORE:
805 if predicate(datastore):
806 found = found + 1
807 found_datastore = datastore
808 datastore_name = datastore.NAME
809
810 if found == 0:
811 return None
812 elif found > 1:
813 module.fail_json(msg=f"There are more datastores with name: {datastore_name}")
814 return found_datastore
815
816
817 def get_datastore_by_name(module, client, datastore_name):
818 return get_datastore(module, client, lambda datastore: datastore_name == datastore.NAME)
819
820
821 def get_datastore_by_id(module, client, datastore_id):
822 return get_datastore(module, client, lambda datastore: datastore_id == datastore.ID)
823
824
825 def get_datastore_id(module, client, requested_id, requested_name):
826 datastore = (
827 get_datastore_by_id(module, client, requested_id)
828 if requested_id
829 else get_datastore_by_name(module, client, requested_name)
830 )
831 if datastore:
832 return datastore.ID
833 else:
834 return None
835
836
837 def get_vm_by_id(client, vm_id):
838 try:
839 vm = client.vm.info(int(vm_id))
840 except BaseException:
841 return None
842 return vm
843
844
845 def get_vms_by_ids(module, client, state, ids):
846 vms = []
847
848 for vm_id in ids:
849 vm = get_vm_by_id(client, vm_id)
850 if vm is None and state != "absent":
851 module.fail_json(msg=f"There is no VM with id={vm_id}")
852 vms.append(vm)
853
854 return vms
855
856
857 def get_vm_info(client, vm):
858 vm = client.vm.info(vm.ID)
859
860 networks_info = []
861
862 disk_size = []
863 if "DISK" in vm.TEMPLATE:
864 if isinstance(vm.TEMPLATE["DISK"], list):
865 for disk in vm.TEMPLATE["DISK"]:
866 disk_size.append(f"{disk['SIZE']} MB")
867 else:
868 disk_size.append(f"{vm.TEMPLATE['DISK']['SIZE']} MB")
869
870 if "NIC" in vm.TEMPLATE:
871 if isinstance(vm.TEMPLATE["NIC"], list):
872 for nic in vm.TEMPLATE["NIC"]:
873 networks_info.append(
874 {
875 "ip": nic.get("IP", ""),
876 "mac": nic.get("MAC", ""),
877 "name": nic.get("NETWORK", ""),
878 "security_groups": nic.get("SECURITY_GROUPS", ""),
879 }
880 )
881 else:
882 networks_info.append(
883 {
884 "ip": vm.TEMPLATE["NIC"].get("IP", ""),
885 "mac": vm.TEMPLATE["NIC"].get("MAC", ""),
886 "name": vm.TEMPLATE["NIC"].get("NETWORK", ""),
887 "security_groups": vm.TEMPLATE["NIC"].get("SECURITY_GROUPS", ""),
888 }
889 )
890
891 current_time = time.localtime()
892 vm_start_time = time.localtime(vm.STIME)
893
894 vm_uptime = time.mktime(current_time) - time.mktime(vm_start_time)
895 vm_uptime /= 60 * 60
896
897 permissions_str = parse_vm_permissions(client, vm)
898
899 # LCM_STATE is VM's sub-state that is relevant only when STATE is ACTIVE
900 vm_lcm_state = None
901 if VM_STATES.index("ACTIVE") == vm.STATE:
902 vm_lcm_state = LCM_STATES[vm.LCM_STATE]
903
904 vm_labels, vm_attributes = get_vm_labels_and_attributes_dict(client, vm.ID)
905
906 updateconf = parse_updateconf(vm.TEMPLATE)
907
908 info = {
909 "template_id": int(vm.TEMPLATE["TEMPLATE_ID"]),
910 "vm_id": vm.ID,
911 "vm_name": vm.NAME,
912 "state": VM_STATES[vm.STATE],
913 "lcm_state": vm_lcm_state,
914 "owner_name": vm.UNAME,
915 "owner_id": vm.UID,
916 "networks": networks_info,
917 "disk_size": disk_size,
918 "memory": f"{vm.TEMPLATE['MEMORY']} MB",
919 "vcpu": vm.TEMPLATE["VCPU"],
920 "cpu": vm.TEMPLATE["CPU"],
921 "group_name": vm.GNAME,
922 "group_id": vm.GID,
923 "uptime_h": int(vm_uptime),
924 "attributes": vm_attributes,
925 "mode": permissions_str,
926 "labels": vm_labels,
927 "updateconf": updateconf,
928 }
929
930 return info
931
932
933 def parse_vm_permissions(client, vm):
934 vm_PERMISSIONS = client.vm.info(vm.ID).PERMISSIONS
935
936 owner_octal = int(vm_PERMISSIONS.OWNER_U) * 4 + int(vm_PERMISSIONS.OWNER_M) * 2 + int(vm_PERMISSIONS.OWNER_A)
937 group_octal = int(vm_PERMISSIONS.GROUP_U) * 4 + int(vm_PERMISSIONS.GROUP_M) * 2 + int(vm_PERMISSIONS.GROUP_A)
938 other_octal = int(vm_PERMISSIONS.OTHER_U) * 4 + int(vm_PERMISSIONS.OTHER_M) * 2 + int(vm_PERMISSIONS.OTHER_A)
939
940 permissions = str(owner_octal) + str(group_octal) + str(other_octal)
941
942 return permissions
943
944
945 def set_vm_permissions(module, client, vms, permissions):
946 changed = False
947
948 for vm in vms:
949 vm = client.vm.info(vm.ID)
950 old_permissions = parse_vm_permissions(client, vm)
951 changed = changed or old_permissions != permissions
952
953 if not module.check_mode and old_permissions != permissions:
954 permissions_str = bin(int(permissions, base=8))[2:] # 600 -> 110000000
955 mode_bits = [int(d) for d in permissions_str]
956 try:
957 client.vm.chmod(
958 vm.ID,
959 mode_bits[0],
960 mode_bits[1],
961 mode_bits[2],
962 mode_bits[3],
963 mode_bits[4],
964 mode_bits[5],
965 mode_bits[6],
966 mode_bits[7],
967 mode_bits[8],
968 )
969 except pyone.OneAuthorizationException:
970 module.fail_json(
971 msg="Permissions changing is unsuccessful, but instances are present if you deployed them."
972 )
973
974 return changed
975
976
977 def set_vm_ownership(module, client, vms, owner_id, group_id):
978 changed = False
979
980 for vm in vms:
981 vm = client.vm.info(vm.ID)
982 if owner_id is None:
983 owner_id = vm.UID
984 if group_id is None:
985 group_id = vm.GID
986
987 changed = changed or owner_id != vm.UID or group_id != vm.GID
988
989 if not module.check_mode and (owner_id != vm.UID or group_id != vm.GID):
990 try:
991 client.vm.chown(vm.ID, owner_id, group_id)
992 except pyone.OneAuthorizationException:
993 module.fail_json(
994 msg="Ownership changing is unsuccessful, but instances are present if you deployed them."
995 )
996
997 return changed
998
999
1000 def update_vm(module, client, vm, updateconf_dict):
1001 changed = False
1002 if not updateconf_dict:
1003 return changed
1004
1005 before = client.vm.info(vm.ID).TEMPLATE
1006
1007 client.vm.updateconf(vm.ID, render(updateconf_dict), 1) # 1: Merge new template with the existing one.
1008
1009 after = client.vm.info(vm.ID).TEMPLATE
1010
1011 changed = before != after
1012 return changed
1013
1014
1015 def update_vms(module, client, vms, *args):
1016 changed = False
1017 for vm in vms:
1018 changed = update_vm(module, client, vm, *args) or changed
1019 return changed
1020
1021
1022 def get_size_in_MB(module, size_str):
1023 SYMBOLS = ["B", "KB", "MB", "GB", "TB"]
1024
1025 s = size_str
1026 init = size_str
1027 num = ""
1028 while s and s[0:1].isdigit() or s[0:1] == ".":
1029 num += s[0]
1030 s = s[1:]
1031 num = float(num)
1032 symbol = s.strip()
1033
1034 if symbol not in SYMBOLS:
1035 module.fail_json(msg=f"Cannot interpret {init!r} {symbol!r} {num}")
1036
1037 prefix = {"B": 1}
1038
1039 for i, s in enumerate(SYMBOLS[1:]):
1040 prefix[s] = 1 << (i + 1) * 10
1041
1042 size_in_bytes = int(num * prefix[symbol])
1043 size_in_MB = size_in_bytes / (1024 * 1024)
1044
1045 return size_in_MB
1046
1047
1048 def create_vm(
1049 module,
1050 client,
1051 template_id,
1052 attributes_dict,
1053 labels_list,
1054 disk_size,
1055 network_attrs_list,
1056 vm_start_on_hold,
1057 vm_persistent,
1058 updateconf_dict,
1059 ):
1060 if attributes_dict:
1061 vm_name = attributes_dict.get("NAME", "")
1062
1063 template = client.template.info(template_id).TEMPLATE
1064
1065 disk_count = len(flatten(template.get("DISK", [])))
1066 if disk_size:
1067 size_count = len(flatten(disk_size))
1068 # check if the number of disks is correct
1069 if disk_count != size_count:
1070 module.fail_json(msg=f"This template has {disk_count} disks but you defined {size_count}")
1071
1072 vm_extra_template = dict_merge(template or {}, attributes_dict or {})
1073 vm_extra_template = dict_merge(
1074 vm_extra_template,
1075 {
1076 "LABELS": ",".join(labels_list),
1077 "NIC": flatten(network_attrs_list, extract=True),
1078 "DISK": flatten(
1079 [
1080 disk
1081 if not size
1082 else dict_merge(
1083 disk,
1084 {
1085 "SIZE": str(int(get_size_in_MB(module, size))),
1086 },
1087 )
1088 for disk, size in zip(
1089 flatten(template.get("DISK", [])),
1090 flatten(disk_size or [None] * disk_count),
1091 )
1092 if disk is not None
1093 ],
1094 extract=True,
1095 ),
1096 },
1097 )
1098 vm_extra_template = dict_merge(vm_extra_template, updateconf_dict or {})
1099
1100 try:
1101 vm_id = client.template.instantiate(
1102 template_id, vm_name, vm_start_on_hold, render(vm_extra_template), vm_persistent
1103 )
1104 except pyone.OneException as e:
1105 module.fail_json(msg=str(e))
1106
1107 vm = get_vm_by_id(client, vm_id)
1108 return get_vm_info(client, vm)
1109
1110
1111 def generate_next_index(vm_filled_indexes_list, num_sign_cnt):
1112 counter = 0
1113 cnt_str = str(counter).zfill(num_sign_cnt)
1114
1115 while cnt_str in vm_filled_indexes_list:
1116 counter = counter + 1
1117 cnt_str = str(counter).zfill(num_sign_cnt)
1118
1119 return cnt_str
1120
1121
1122 def get_vm_labels_and_attributes_dict(client, vm_id):
1123 vm_USER_TEMPLATE = client.vm.info(vm_id).USER_TEMPLATE
1124
1125 attrs_dict = {}
1126 labels_list = []
1127
1128 for key, value in vm_USER_TEMPLATE.items():
1129 if key != "LABELS":
1130 attrs_dict[key] = value
1131 else:
1132 if key is not None and value is not None:
1133 labels_list = value.split(",")
1134
1135 return labels_list, attrs_dict
1136
1137
1138 def get_all_vms_by_attributes(client, attributes_dict, labels_list):
1139 pool = client.vmpool.info(-2, -1, -1, -1).VM
1140 vm_list = []
1141 name = ""
1142 if attributes_dict:
1143 name = attributes_dict.pop("NAME", "")
1144
1145 if name != "":
1146 base_name = name[: len(name) - name.count("#")]
1147 # Check does the name have indexed format
1148 with_hash = name.endswith("#")
1149
1150 for vm in pool:
1151 if vm.NAME.startswith(base_name):
1152 if with_hash and vm.NAME[len(base_name) :].isdigit():
1153 # If the name has indexed format and after base_name it has only digits it'll be matched
1154 vm_list.append(vm)
1155 elif not with_hash and name == vm.NAME:
1156 # If the name is not indexed it has to be same
1157 vm_list.append(vm)
1158 pool = vm_list
1159
1160 vm_list = copy.copy(pool)
1161
1162 for vm in pool:
1163 remove_list = []
1164 vm_labels_list, vm_attributes_dict = get_vm_labels_and_attributes_dict(client, vm.ID)
1165
1166 if attributes_dict and len(attributes_dict) > 0:
1167 for key, val in attributes_dict.items():
1168 if key in vm_attributes_dict:
1169 if val and vm_attributes_dict[key] != val:
1170 remove_list.append(vm)
1171 break
1172 else:
1173 remove_list.append(vm)
1174 break
1175 vm_list = list(set(vm_list).difference(set(remove_list)))
1176
1177 remove_list = []
1178 if labels_list and len(labels_list) > 0:
1179 for label in labels_list:
1180 if label not in vm_labels_list:
1181 remove_list.append(vm)
1182 break
1183 vm_list = list(set(vm_list).difference(set(remove_list)))
1184
1185 return vm_list
1186
1187
1188 def create_count_of_vms(
1189 module,
1190 client,
1191 template_id,
1192 count,
1193 attributes_dict,
1194 labels_list,
1195 disk_size,
1196 network_attrs_list,
1197 wait,
1198 wait_timeout,
1199 vm_start_on_hold,
1200 vm_persistent,
1201 updateconf_dict,
1202 ):
1203 new_vms_list = []
1204
1205 vm_name = ""
1206 if attributes_dict:
1207 vm_name = attributes_dict.get("NAME", "")
1208
1209 if module.check_mode:
1210 return True, [], []
1211
1212 # Create list of used indexes
1213 vm_filled_indexes_list = None
1214 num_sign_cnt = vm_name.count("#")
1215 if vm_name != "" and num_sign_cnt > 0:
1216 vm_list = get_all_vms_by_attributes(client, {"NAME": vm_name}, None)
1217 base_name = vm_name[: len(vm_name) - num_sign_cnt]
1218 vm_name = base_name
1219 # Make list which contains used indexes in format ['000', '001',...]
1220 vm_filled_indexes_list = [vm.NAME[len(base_name) :].zfill(num_sign_cnt) for vm in vm_list]
1221
1222 while count > 0:
1223 new_vm_name = vm_name
1224 # Create indexed name
1225 if vm_filled_indexes_list is not None:
1226 next_index = generate_next_index(vm_filled_indexes_list, num_sign_cnt)
1227 vm_filled_indexes_list.append(next_index)
1228 new_vm_name += next_index
1229 # Update NAME value in the attributes in case there is index
1230 attributes_dict["NAME"] = new_vm_name
1231 new_vm_dict = create_vm(
1232 module,
1233 client,
1234 template_id,
1235 attributes_dict,
1236 labels_list,
1237 disk_size,
1238 network_attrs_list,
1239 vm_start_on_hold,
1240 vm_persistent,
1241 updateconf_dict,
1242 )
1243 new_vm_id = new_vm_dict.get("vm_id")
1244 new_vm = get_vm_by_id(client, new_vm_id)
1245 new_vms_list.append(new_vm)
1246 count -= 1
1247
1248 if vm_start_on_hold:
1249 if wait:
1250 for vm in new_vms_list:
1251 wait_for_hold(module, client, vm, wait_timeout)
1252 else:
1253 if wait:
1254 for vm in new_vms_list:
1255 wait_for_running(module, client, vm, wait_timeout)
1256
1257 return True, new_vms_list, []
1258
1259
1260 def create_exact_count_of_vms(
1261 module,
1262 client,
1263 template_id,
1264 exact_count,
1265 attributes_dict,
1266 count_attributes_dict,
1267 labels_list,
1268 count_labels_list,
1269 disk_size,
1270 network_attrs_list,
1271 hard,
1272 wait,
1273 wait_timeout,
1274 vm_start_on_hold,
1275 vm_persistent,
1276 updateconf_dict,
1277 ):
1278 vm_list = get_all_vms_by_attributes(client, count_attributes_dict, count_labels_list)
1279
1280 vm_count_diff = exact_count - len(vm_list)
1281 changed = vm_count_diff != 0
1282
1283 instances_list = []
1284 tagged_instances_list = vm_list
1285
1286 if module.check_mode:
1287 return changed, instances_list, tagged_instances_list
1288
1289 if vm_count_diff > 0:
1290 # Add more VMs
1291 changed, instances_list, tagged_instances = create_count_of_vms(
1292 module,
1293 client,
1294 template_id,
1295 vm_count_diff,
1296 attributes_dict,
1297 labels_list,
1298 disk_size,
1299 network_attrs_list,
1300 wait,
1301 wait_timeout,
1302 vm_start_on_hold,
1303 vm_persistent,
1304 updateconf_dict,
1305 )
1306
1307 tagged_instances_list += instances_list
1308 elif vm_count_diff < 0:
1309 # Delete surplus VMs
1310 old_vms_list = []
1311
1312 while vm_count_diff < 0:
1313 old_vm = vm_list.pop(0)
1314 old_vms_list.append(old_vm)
1315 terminate_vm(module, client, old_vm, hard)
1316 vm_count_diff += 1
1317
1318 if wait:
1319 for vm in old_vms_list:
1320 wait_for_done(module, client, vm, wait_timeout)
1321
1322 instances_list = old_vms_list
1323 # store only the remaining instances
1324 old_vms_set = set(old_vms_list)
1325 tagged_instances_list = [vm for vm in vm_list if vm not in old_vms_set]
1326
1327 return changed, instances_list, tagged_instances_list
1328
1329
1330 VM_STATES = [
1331 "INIT",
1332 "PENDING",
1333 "HOLD",
1334 "ACTIVE",
1335 "STOPPED",
1336 "SUSPENDED",
1337 "DONE",
1338 "",
1339 "POWEROFF",
1340 "UNDEPLOYED",
1341 "CLONING",
1342 "CLONING_FAILURE",
1343 ]
1344 LCM_STATES = [
1345 "LCM_INIT",
1346 "PROLOG",
1347 "BOOT",
1348 "RUNNING",
1349 "MIGRATE",
1350 "SAVE_STOP",
1351 "SAVE_SUSPEND",
1352 "SAVE_MIGRATE",
1353 "PROLOG_MIGRATE",
1354 "PROLOG_RESUME",
1355 "EPILOG_STOP",
1356 "EPILOG",
1357 "SHUTDOWN",
1358 "STATE13",
1359 "STATE14",
1360 "CLEANUP_RESUBMIT",
1361 "UNKNOWN",
1362 "HOTPLUG",
1363 "SHUTDOWN_POWEROFF",
1364 "BOOT_UNKNOWN",
1365 "BOOT_POWEROFF",
1366 "BOOT_SUSPENDED",
1367 "BOOT_STOPPED",
1368 "CLEANUP_DELETE",
1369 "HOTPLUG_SNAPSHOT",
1370 "HOTPLUG_NIC",
1371 "HOTPLUG_SAVEAS",
1372 "HOTPLUG_SAVEAS_POWEROFF",
1373 "HOTPULG_SAVEAS_SUSPENDED",
1374 "SHUTDOWN_UNDEPLOY",
1375 ]
1376
1377
1378 def wait_for_state(module, client, vm, wait_timeout, state_predicate):
1379 start_time = time.time()
1380
1381 while (time.time() - start_time) < wait_timeout:
1382 vm = client.vm.info(vm.ID)
1383 state = vm.STATE
1384 lcm_state = vm.LCM_STATE
1385
1386 if state_predicate(state, lcm_state):
1387 return vm
1388 elif state not in [
1389 VM_STATES.index("INIT"),
1390 VM_STATES.index("PENDING"),
1391 VM_STATES.index("HOLD"),
1392 VM_STATES.index("ACTIVE"),
1393 VM_STATES.index("CLONING"),
1394 VM_STATES.index("POWEROFF"),
1395 ]:
1396 module.fail_json(msg=f"Action is unsuccessful. VM state: {VM_STATES[state]}")
1397
1398 time.sleep(1)
1399
1400 module.fail_json(msg="Wait timeout has expired!")
1401
1402
1403 def wait_for_running(module, client, vm, wait_timeout):
1404 return wait_for_state(
1405 module,
1406 client,
1407 vm,
1408 wait_timeout,
1409 lambda state, lcm_state: state in [VM_STATES.index("ACTIVE")] and lcm_state in [LCM_STATES.index("RUNNING")],
1410 )
1411
1412
1413 def wait_for_done(module, client, vm, wait_timeout):
1414 return wait_for_state(module, client, vm, wait_timeout, lambda state, lcm_state: state in [VM_STATES.index("DONE")])
1415
1416
1417 def wait_for_hold(module, client, vm, wait_timeout):
1418 return wait_for_state(module, client, vm, wait_timeout, lambda state, lcm_state: state in [VM_STATES.index("HOLD")])
1419
1420
1421 def wait_for_poweroff(module, client, vm, wait_timeout):
1422 return wait_for_state(
1423 module, client, vm, wait_timeout, lambda state, lcm_state: state in [VM_STATES.index("POWEROFF")]
1424 )
1425
1426
1427 def terminate_vm(module, client, vm, hard=False):
1428 changed = False
1429
1430 if not vm:
1431 return changed
1432
1433 changed = True
1434
1435 if not module.check_mode:
1436 if hard:
1437 client.vm.action("terminate-hard", vm.ID)
1438 else:
1439 client.vm.action("terminate", vm.ID)
1440
1441 return changed
1442
1443
1444 def terminate_vms(module, client, vms, hard):
1445 changed = False
1446
1447 for vm in vms:
1448 changed = terminate_vm(module, client, vm, hard) or changed
1449
1450 return changed
1451
1452
1453 def poweroff_vm(module, client, vm, hard):
1454 vm = client.vm.info(vm.ID)
1455 changed = False
1456
1457 lcm_state = vm.LCM_STATE
1458 state = vm.STATE
1459
1460 if lcm_state not in [LCM_STATES.index("SHUTDOWN"), LCM_STATES.index("SHUTDOWN_POWEROFF")] and state not in [
1461 VM_STATES.index("POWEROFF")
1462 ]:
1463 changed = True
1464
1465 if changed and not module.check_mode:
1466 if not hard:
1467 client.vm.action("poweroff", vm.ID)
1468 else:
1469 client.vm.action("poweroff-hard", vm.ID)
1470
1471 return changed
1472
1473
1474 def poweroff_vms(module, client, vms, hard):
1475 changed = False
1476
1477 for vm in vms:
1478 changed = poweroff_vm(module, client, vm, hard) or changed
1479
1480 return changed
1481
1482
1483 def reboot_vms(module, client, vms, wait_timeout, hard):
1484 if not module.check_mode:
1485 # Firstly, power-off all instances
1486 for vm in vms:
1487 vm = client.vm.info(vm.ID)
1488 lcm_state = vm.LCM_STATE
1489 state = vm.STATE
1490 if lcm_state not in [LCM_STATES.index("SHUTDOWN_POWEROFF")] and state not in [VM_STATES.index("POWEROFF")]:
1491 poweroff_vm(module, client, vm, hard)
1492
1493 # Wait for all to be power-off
1494 for vm in vms:
1495 wait_for_poweroff(module, client, vm, wait_timeout)
1496
1497 for vm in vms:
1498 resume_vm(module, client, vm)
1499
1500 return True
1501
1502
1503 def resume_vm(module, client, vm):
1504 vm = client.vm.info(vm.ID)
1505 changed = False
1506
1507 state = vm.STATE
1508 if state in [VM_STATES.index("HOLD")]:
1509 changed = release_vm(module, client, vm)
1510 return changed
1511
1512 lcm_state = vm.LCM_STATE
1513 if lcm_state == LCM_STATES.index("SHUTDOWN_POWEROFF"):
1514 module.fail_json(
1515 msg="Cannot perform action 'resume' because this action is not available "
1516 "for LCM_STATE: 'SHUTDOWN_POWEROFF'. Wait for the VM to shutdown properly"
1517 )
1518 if lcm_state not in [LCM_STATES.index("RUNNING")]:
1519 changed = True
1520
1521 if changed and not module.check_mode:
1522 client.vm.action("resume", vm.ID)
1523
1524 return changed
1525
1526
1527 def resume_vms(module, client, vms):
1528 changed = False
1529
1530 for vm in vms:
1531 changed = resume_vm(module, client, vm) or changed
1532
1533 return changed
1534
1535
1536 def release_vm(module, client, vm):
1537 vm = client.vm.info(vm.ID)
1538 changed = False
1539
1540 state = vm.STATE
1541 if state != VM_STATES.index("HOLD"):
1542 module.fail_json(
1543 msg="Cannot perform action 'release' because this action is not available "
1544 "because VM is not in state 'HOLD'."
1545 )
1546 else:
1547 changed = True
1548
1549 if changed and not module.check_mode:
1550 client.vm.action("release", vm.ID)
1551
1552 return changed
1553
1554
1555 def check_name_attribute(module, attributes):
1556 if attributes.get("NAME"):
1557 if re.match(r"^[^#]+#*$", attributes.get("NAME")) is None:
1558 module.fail_json(
1559 msg=f"Illegal 'NAME' attribute: '{attributes.get('NAME')}"
1560 "' .Signs '#' are allowed only at the end of the name and the name cannot contain only '#'."
1561 )
1562
1563
1564 TEMPLATE_RESTRICTED_ATTRIBUTES = [
1565 "CPU",
1566 "VCPU",
1567 "OS",
1568 "FEATURES",
1569 "MEMORY",
1570 "DISK",
1571 "NIC",
1572 "INPUT",
1573 "GRAPHICS",
1574 "CONTEXT",
1575 "CREATED_BY",
1576 "CPU_COST",
1577 "DISK_COST",
1578 "MEMORY_COST",
1579 "TEMPLATE_ID",
1580 "VMID",
1581 "AUTOMATIC_DS_REQUIREMENTS",
1582 "DEPLOY_FOLDER",
1583 "LABELS",
1584 ]
1585
1586
1587 def check_attributes(module, attributes):
1588 for key in attributes.keys():
1589 if key in TEMPLATE_RESTRICTED_ATTRIBUTES:
1590 module.fail_json(msg=f"Restricted attribute `{key}` cannot be used when filtering VMs.")
1591 # Check the format of the name attribute
1592 check_name_attribute(module, attributes)
1593
1594
1595 def disk_save_as(module, client, vm, disk_saveas, wait_timeout):
1596 if not disk_saveas.get("name"):
1597 module.fail_json(msg="Key 'name' is required for 'disk_saveas' option")
1598
1599 image_name = disk_saveas.get("name")
1600 disk_id = disk_saveas.get("disk_id", 0)
1601
1602 if not module.check_mode:
1603 if VM_STATES.index("POWEROFF") != vm.STATE:
1604 module.fail_json(msg="'disksaveas' option can be used only when the VM is in 'POWEROFF' state")
1605 try:
1606 client.vm.disksaveas(vm.ID, disk_id, image_name, "OS", -1)
1607 except pyone.OneException as e:
1608 module.fail_json(msg=str(e))
1609 wait_for_poweroff(module, client, vm, wait_timeout) # wait for VM to leave the hotplug_saveas_poweroff state
1610
1611
1612 def get_connection_info(module):
1613 url = module.params.get("api_url")
1614 username = module.params.get("api_username")
1615 password = module.params.get("api_password")
1616
1617 if not url:
1618 url = os.environ.get("ONE_URL")
1619
1620 if not username:
1621 username = os.environ.get("ONE_USERNAME")
1622
1623 if not password:
1624 password = os.environ.get("ONE_PASSWORD")
1625
1626 if not username:
1627 if not password:
1628 authfile = os.environ.get("ONE_AUTH")
1629 if authfile is None:
1630 authfile = os.path.join(os.environ.get("HOME"), ".one", "one_auth")
1631 try:
1632 with open(authfile) as fp:
1633 authstring = fp.read().rstrip()
1634 username = authstring.split(":")[0]
1635 password = authstring.split(":")[1]
1636 except OSError:
1637 module.fail_json(msg=f"Could not find or read ONE_AUTH file at '{authfile}'")
1638 except Exception:
1639 module.fail_json(msg=f"Error occurs when read ONE_AUTH file at '{authfile}'")
1640 if not url:
1641 module.fail_json(msg="Opennebula API url (api_url) is not specified")
1642
1643 return AuthParams(url=url, username=username, password=password)
1644
1645
1646 def main():
1647 fields = {
1648 "api_url": {"required": False, "type": "str"},
1649 "api_username": {"required": False, "type": "str"},
1650 "api_password": {"required": False, "type": "str", "no_log": True},
1651 "instance_ids": {"required": False, "aliases": ["ids"], "type": "list", "elements": "int"},
1652 "template_name": {"required": False, "type": "str"},
1653 "template_id": {"required": False, "type": "int"},
1654 "vm_start_on_hold": {"default": False, "type": "bool"},
1655 "state": {
1656 "default": "present",
1657 "choices": ["present", "absent", "rebooted", "poweredoff", "running"],
1658 "type": "str",
1659 },
1660 "mode": {"required": False, "type": "str"},
1661 "owner_id": {"required": False, "type": "int"},
1662 "group_id": {"required": False, "type": "int"},
1663 "wait": {"default": True, "type": "bool"},
1664 "wait_timeout": {"default": 300, "type": "int"},
1665 "hard": {"default": False, "type": "bool"},
1666 "memory": {"required": False, "type": "str"},
1667 "cpu": {"required": False, "type": "float"},
1668 "vcpu": {"required": False, "type": "int"},
1669 "disk_size": {"required": False, "type": "list", "elements": "str"},
1670 "datastore_name": {"required": False, "type": "str"},
1671 "datastore_id": {"required": False, "type": "int"},
1672 "networks": {"default": [], "type": "list", "elements": "dict"},
1673 "count": {"default": 1, "type": "int"},
1674 "exact_count": {"required": False, "type": "int"},
1675 "attributes": {"default": {}, "type": "dict"},
1676 "count_attributes": {"required": False, "type": "dict"},
1677 "labels": {"default": [], "type": "list", "elements": "str"},
1678 "count_labels": {"required": False, "type": "list", "elements": "str"},
1679 "disk_saveas": {"type": "dict"},
1680 "persistent": {"default": False, "type": "bool"},
1681 "updateconf": {"type": "dict"},
1682 }
1683
1684 module = AnsibleModule(
1685 argument_spec=fields,
1686 mutually_exclusive=[
1687 ["template_id", "template_name", "instance_ids"],
1688 ["template_id", "template_name", "disk_saveas"],
1689 ["instance_ids", "count_attributes", "count"],
1690 ["instance_ids", "count_labels", "count"],
1691 ["instance_ids", "exact_count"],
1692 ["instance_ids", "attributes"],
1693 ["instance_ids", "labels"],
1694 ["disk_saveas", "attributes"],
1695 ["disk_saveas", "labels"],
1696 ["exact_count", "count"],
1697 ["count", "hard"],
1698 ["instance_ids", "cpu"],
1699 ["instance_ids", "vcpu"],
1700 ["instance_ids", "memory"],
1701 ["instance_ids", "disk_size"],
1702 ["instance_ids", "networks"],
1703 ["persistent", "disk_size"],
1704 ],
1705 supports_check_mode=True,
1706 )
1707
1708 if not HAS_PYONE:
1709 module.fail_json(msg="This module requires pyone to work!")
1710
1711 auth = get_connection_info(module)
1712 params = module.params
1713 instance_ids = params.get("instance_ids")
1714 requested_template_name = params.get("template_name")
1715 requested_template_id = params.get("template_id")
1716 put_vm_on_hold = params.get("vm_start_on_hold")
1717 state = params.get("state")
1718 permissions = params.get("mode")
1719 owner_id = params.get("owner_id")
1720 group_id = params.get("group_id")
1721 wait = params.get("wait")
1722 wait_timeout = params.get("wait_timeout")
1723 hard = params.get("hard")
1724 memory = params.get("memory")
1725 cpu = params.get("cpu")
1726 vcpu = params.get("vcpu")
1727 disk_size = params.get("disk_size")
1728 requested_datastore_id = params.get("datastore_id")
1729 requested_datastore_name = params.get("datastore_name")
1730 networks = params.get("networks")
1731 count = params.get("count")
1732 exact_count = params.get("exact_count")
1733 attributes = params.get("attributes")
1734 count_attributes = params.get("count_attributes")
1735 labels = params.get("labels")
1736 count_labels = params.get("count_labels")
1737 disk_saveas = params.get("disk_saveas")
1738 persistent = params.get("persistent")
1739 updateconf = params.get("updateconf")
1740
1741 if not (auth.username and auth.password):
1742 module.warn("Credentials missing")
1743 else:
1744 one_client = pyone.OneServer(auth.url, session=f"{auth.username}:{auth.password}")
1745
1746 if attributes:
1747 attributes = {key.upper(): value for key, value in attributes.items()}
1748 check_attributes(module, attributes)
1749
1750 if count_attributes:
1751 count_attributes = {key.upper(): value for key, value in count_attributes.items()}
1752 if not attributes:
1753 module.warn(
1754 "When you pass `count_attributes` without `attributes` option when deploying, `attributes` option will have same values implicitly."
1755 )
1756 attributes = copy.copy(count_attributes)
1757 check_attributes(module, count_attributes)
1758
1759 if updateconf:
1760 check_updateconf(module, updateconf)
1761
1762 if count_labels and not labels:
1763 module.warn(
1764 "When you pass `count_labels` without `labels` option when deploying, `labels` option will have same values implicitly."
1765 )
1766 labels = count_labels
1767
1768 # Fetch template
1769 template_id = None
1770 if requested_template_id is not None or requested_template_name:
1771 template_id = get_template_id(module, one_client, requested_template_id, requested_template_name)
1772 if template_id is None:
1773 if requested_template_id is not None:
1774 module.fail_json(msg=f"There is no template with template_id: {requested_template_id}")
1775 elif requested_template_name:
1776 module.fail_json(msg=f"There is no template with name: {requested_template_name}")
1777
1778 # Fetch datastore
1779 datastore_id = None
1780 if requested_datastore_id or requested_datastore_name:
1781 datastore_id = get_datastore_id(module, one_client, requested_datastore_id, requested_datastore_name)
1782 if datastore_id is None:
1783 if requested_datastore_id:
1784 module.fail_json(msg=f"There is no datastore with datastore_id: {requested_datastore_id}")
1785 elif requested_datastore_name:
1786 module.fail_json(msg=f"There is no datastore with name: {requested_datastore_name}")
1787 else:
1788 attributes["SCHED_DS_REQUIREMENTS"] = f"ID={datastore_id}"
1789
1790 if exact_count and template_id is None:
1791 module.fail_json(msg="Option `exact_count` needs template_id or template_name")
1792
1793 if exact_count is not None and not (count_attributes or count_labels):
1794 module.fail_json(
1795 msg="Either `count_attributes` or `count_labels` has to be specified with option `exact_count`."
1796 )
1797 if (count_attributes or count_labels) and exact_count is None:
1798 module.fail_json(
1799 msg="Option `exact_count` has to be specified when either `count_attributes` or `count_labels` is used."
1800 )
1801 if template_id is not None and state != "present":
1802 module.fail_json(msg="Only state 'present' is valid for the template")
1803
1804 if memory:
1805 attributes["MEMORY"] = str(int(get_size_in_MB(module, memory)))
1806 if cpu:
1807 attributes["CPU"] = str(cpu)
1808 if vcpu:
1809 attributes["VCPU"] = str(vcpu)
1810
1811 if exact_count is not None and state != "present":
1812 module.fail_json(msg="The `exact_count` option is valid only for the `present` state")
1813 if exact_count is not None and exact_count < 0:
1814 module.fail_json(msg="`exact_count` cannot be less than 0")
1815 if count <= 0:
1816 module.fail_json(msg="`count` has to be greater than 0")
1817
1818 if permissions is not None:
1819 if re.match("^[0-7]{3}$", permissions) is None:
1820 module.fail_json(msg="Option `mode` has to have exactly 3 digits and be in the octet format e.g. 600")
1821
1822 if exact_count is not None:
1823 # Deploy an exact count of VMs
1824 changed, instances_list, tagged_instances_list = create_exact_count_of_vms(
1825 module,
1826 one_client,
1827 template_id,
1828 exact_count,
1829 attributes,
1830 count_attributes,
1831 labels,
1832 count_labels,
1833 disk_size,
1834 networks,
1835 hard,
1836 wait,
1837 wait_timeout,
1838 put_vm_on_hold,
1839 persistent,
1840 updateconf,
1841 )
1842 vms = tagged_instances_list
1843 elif template_id is not None and state == "present":
1844 # Deploy count VMs
1845 changed, instances_list, tagged_instances_list = create_count_of_vms(
1846 module,
1847 one_client,
1848 template_id,
1849 count,
1850 attributes,
1851 labels,
1852 disk_size,
1853 networks,
1854 wait,
1855 wait_timeout,
1856 put_vm_on_hold,
1857 persistent,
1858 updateconf,
1859 )
1860 # instances_list - new instances
1861 # tagged_instances_list - all instances with specified `count_attributes` and `count_labels`
1862 vms = instances_list
1863 else:
1864 # Fetch data of instances, or change their state
1865 if not (instance_ids or attributes or labels):
1866 module.fail_json(msg="At least one of `instance_ids`,`attributes`,`labels` must be passed!")
1867
1868 if memory or cpu or vcpu or disk_size or networks:
1869 module.fail_json(
1870 msg="Parameters as `memory`, `cpu`, `vcpu`, `disk_size` and `networks` you can only set when deploying a VM!"
1871 )
1872
1873 if hard and state not in ["rebooted", "poweredoff", "absent", "present"]:
1874 module.fail_json(
1875 msg="The 'hard' option can be used only for one of these states: 'rebooted', 'poweredoff', 'absent' and 'present'"
1876 )
1877
1878 vms = []
1879 tagged = False
1880 changed = False
1881
1882 if instance_ids:
1883 vms = get_vms_by_ids(module, one_client, state, instance_ids)
1884 else:
1885 tagged = True
1886 vms = get_all_vms_by_attributes(one_client, attributes, labels)
1887
1888 if len(vms) == 0 and state != "absent" and state != "present":
1889 module.fail_json(msg="There are no instances with specified `instance_ids`, `attributes` and/or `labels`")
1890
1891 if len(vms) == 0 and state == "present" and not tagged:
1892 module.fail_json(msg="There are no instances with specified `instance_ids`.")
1893
1894 if tagged and state == "absent":
1895 module.fail_json(msg="Option `instance_ids` is required when state is `absent`.")
1896
1897 if state == "absent":
1898 changed = terminate_vms(module, one_client, vms, hard)
1899 elif state == "rebooted":
1900 changed = reboot_vms(module, one_client, vms, wait_timeout, hard)
1901 elif state == "poweredoff":
1902 changed = poweroff_vms(module, one_client, vms, hard)
1903 elif state == "running":
1904 changed = resume_vms(module, one_client, vms)
1905
1906 instances_list = vms
1907 tagged_instances_list = []
1908
1909 if permissions is not None:
1910 changed = set_vm_permissions(module, one_client, vms, permissions) or changed
1911
1912 if owner_id is not None or group_id is not None:
1913 changed = set_vm_ownership(module, one_client, vms, owner_id, group_id) or changed
1914
1915 if template_id is None and updateconf is not None:
1916 changed = update_vms(module, one_client, vms, updateconf) or changed
1917
1918 if wait and not module.check_mode and state != "present":
1919 wait_for = {
1920 "absent": wait_for_done,
1921 "rebooted": wait_for_running,
1922 "poweredoff": wait_for_poweroff,
1923 "running": wait_for_running,
1924 }
1925 for vm in vms:
1926 if vm is not None:
1927 wait_for[state](module, one_client, vm, wait_timeout)
1928
1929 if disk_saveas is not None:
1930 if len(vms) == 0:
1931 module.fail_json(msg="There is no VM whose disk will be saved.")
1932 disk_save_as(module, one_client, vms[0], disk_saveas, wait_timeout)
1933 changed = True
1934
1935 # instances - a list of instances info whose state is changed or which are fetched with C(instance_ids) option
1936 instances = list(get_vm_info(one_client, vm) for vm in instances_list if vm is not None)
1937 instances_ids = list(vm.ID for vm in instances_list if vm is not None)
1938 # tagged_instances - A list of instances info based on a specific attributes and/or labels that are specified with C(count_attributes) and C(count_labels)
1939 tagged_instances = list(get_vm_info(one_client, vm) for vm in tagged_instances_list if vm is not None)
1940
1941 result = {
1942 "changed": changed,
1943 "instances": instances,
1944 "instances_ids": instances_ids,
1945 "tagged_instances": tagged_instances,
1946 }
1947
1948 module.exit_json(**result)
1949
1950
1951 if __name__ == "__main__":
1952 main()