Debian Codegraph @

ansible_collections/community/proxmox/plugins/modules/proxmox.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright Ansible Project
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
8 DOCUMENTATION = r"""
9 module: proxmox
10 short_description: Management of instances in Proxmox VE cluster
11 description:
12 - Allows you to create/delete/stop instances in Proxmox VE cluster.
13 - The module automatically detects containerization type (lxc for PVE 4, openvz for older).
14 attributes:
15 check_mode:
16 support: none
17 diff_mode:
18 support: none
19 options:
20 password:
21 description:
22 - The instance root password.
23 type: str
24 hostname:
25 description:
26 - The instance hostname.
27 - Required only for O(state=present).
28 - Must be unique if vmid is not passed.
29 type: str
30 ostemplate:
31 description:
32 - The template for VM creating.
33 - Required only for O(state=present).
34 type: str
35 disk:
36 description:
37 - This option was previously described as "hard disk size in GiB for instance" however several formats describing a lxc
38 mount are permitted.
39 - Older versions of Proxmox will accept a numeric value for size using the O(storage) parameter to automatically choose
40 which storage to allocate from, however new versions enforce the C(<STORAGE>:<SIZE>) syntax.
41 - Additional options are available by using some combination of the following key-value pairs as a comma-delimited list
42 C([volume=]<volume>
43 [,acl=<1|0>] [,mountoptions=<opt[;opt...] [,quota=<1|0>] [,replicate=<1|0>] [,ro=<1|0>] [,shared=<1|0>]
44 [,size=<DiskSize>]).
45 - See U(https://pve.proxmox.com/wiki/Linux_Container) for a full description.
46 - This option is mutually exclusive with O(disk_volume).
47 type: str
48 disk_volume:
49 description:
50 - Specify a hash/dictionary of the C(rootfs) disk.
51 - See U(https://pve.proxmox.com/wiki/Linux_Container#pct_mount_points) for a full description.
52 - This option is mutually exclusive with O(storage) and O(disk).
53 type: dict
54 suboptions:
55 storage:
56 description:
57 - O(disk_volume.storage) is the storage identifier of the storage to use for the C(rootfs).
58 - Mutually exclusive with O(disk_volume.host_path).
59 type: str
60 volume:
61 description:
62 - O(disk_volume.volume) is the name of an existing volume.
63 - If not defined, the module will check if one exists. If not, a new volume will be created.
64 - If defined, the volume must exist under that name.
65 - Required only if O(disk_volume.storage) is defined, and mutually exclusive with O(disk_volume.host_path).
66 type: str
67 size:
68 description:
69 - O(disk_volume.size) is the size of the storage to use.
70 - The size is given in GiB.
71 - Required only if O(disk_volume.storage) is defined, and mutually exclusive with O(disk_volume.host_path).
72 type: int
73 host_path:
74 description:
75 - O(disk_volume.host_path) defines a bind or device path on the PVE host to use for the C(rootfs).
76 - Mutually exclusive with O(disk_volume.storage), O(disk_volume.volume), and O(disk_volume.size).
77 type: path
78 options:
79 description:
80 - O(disk_volume.options) is a dict of extra options.
81 - The value of any given option must be a string, for example V("1").
82 type: dict
83 cmode:
84 description:
85 - Console mode.
86 - If set to V(default), no C(cmode) will be provided on instance creation.
87 type: str
88 choices: ['default', 'tty', 'console', 'shell']
89 default: default
90 cores:
91 description:
92 - Specify number of cores per socket.
93 type: int
94 cpus:
95 description:
96 - Number of allocated cpus for instance.
97 type: int
98 memory:
99 description:
100 - Memory size in MB for instance.
101 type: int
102 swap:
103 description:
104 - Swap memory size in MB for instance.
105 type: int
106 netif:
107 description:
108 - Specifies network interfaces for the container. As a hash/dictionary defining interfaces.
109 type: dict
110 features:
111 description:
112 - Specifies a list of features to be enabled. For valid options, see U(https://pve.proxmox.com/wiki/Linux_Container#pct_options).
113 - Some features require the use of a privileged container.
114 type: list
115 elements: str
116 delete:
117 description:
118 - A list of settings you want to delete.
119 type: list
120 elements: str
121 startup:
122 description:
123 - Specifies the startup order of the container.
124 - Use C(order=#) where C(#) is a non-negative number to define the general startup order. Shutdown in done with reverse
125 ordering.
126 - Use C(up=#) where C(#) is in seconds, to specify a delay to wait before the next VM is started.
127 - Use C(down=#) where C(#) is in seconds, to specify a delay to wait before the next VM is stopped.
128 type: list
129 elements: str
130 mounts:
131 description:
132 - Specifies additional mounts (separate disks) for the container. As a hash/dictionary defining mount points as strings.
133 - This Option is mutually exclusive with O(mount_volumes).
134 type: dict
135 mount_volumes:
136 description:
137 - Specify additional mounts (separate disks) for the container. As a hash/dictionary defining mount points.
138 - See U(https://pve.proxmox.com/wiki/Linux_Container#pct_mount_points) for a full description.
139 - This Option is mutually exclusive with O(mounts).
140 type: list
141 elements: dict
142 suboptions:
143 id:
144 description:
145 - O(mount_volumes[].id) is the identifier of the mount point written as C(mp[n]).
146 type: str
147 required: true
148 storage:
149 description:
150 - O(mount_volumes[].storage) is the storage identifier of the storage to use.
151 - Mutually exclusive with O(mount_volumes[].host_path).
152 type: str
153 volume:
154 description:
155 - O(mount_volumes[].volume) is the name of an existing volume.
156 - If not defined, the module will check if one exists. If not, a new volume will be created.
157 - If defined, the volume must exist under that name.
158 - Required only if O(mount_volumes[].storage) is defined and mutually exclusive with O(mount_volumes[].host_path).
159 type: str
160 size:
161 description:
162 - O(mount_volumes[].size) is the size of the storage to use.
163 - The size is given in GiB.
164 - Required only if O(mount_volumes[].storage) is defined and mutually exclusive with O(mount_volumes[].host_path).
165 type: int
166 host_path:
167 description:
168 - O(mount_volumes[].host_path) defines a bind or device path on the PVE host to use for the C(rootfs).
169 - Mutually exclusive with O(mount_volumes[].storage), O(mount_volumes[].volume), and O(mount_volumes[].size).
170 type: path
171 mountpoint:
172 description:
173 - O(mount_volumes[].mountpoint) is the mount point of the volume.
174 type: path
175 required: true
176 options:
177 description:
178 - O(mount_volumes[].options) is a dict of extra options.
179 - The value of any given option must be a string, for example V("1").
180 type: dict
181 ip_address:
182 description:
183 - Specifies the address the container will be assigned.
184 type: str
185 onboot:
186 description:
187 - Specifies whether a VM will be started during system bootup.
188 type: bool
189 storage:
190 description:
191 - Target storage.
192 - This option is mutually exclusive with O(disk_volume) and O(mount_volumes).
193 type: str
194 default: 'local'
195 ostype:
196 description:
197 - Specifies the C(ostype) of the LXC container.
198 - If set to V(auto), no C(ostype) will be provided on instance creation.
199 choices: ['auto', 'debian', 'devuan', 'ubuntu', 'centos', 'fedora', 'opensuse', 'archlinux', 'alpine', 'gentoo', 'nixos',
200 'unmanaged']
201 type: str
202 default: 'auto'
203 cpuunits:
204 description:
205 - CPU weight for a VM.
206 type: int
207 nameserver:
208 description:
209 - Sets DNS server IP address for a container.
210 type: str
211 searchdomain:
212 description:
213 - Sets DNS search domain for a container.
214 type: str
215 tags:
216 description:
217 - List of tags to apply to the container.
218 - Tags must start with V([a-z0-9_]) followed by zero or more of the following characters V([a-z0-9_-+.]).
219 - Tags are only available in Proxmox 7+.
220 type: list
221 elements: str
222 timeout:
223 description:
224 - Timeout for operations.
225 type: int
226 default: 30
227 update:
228 description:
229 - If V(true), the container will be updated with new values.
230 This only happens if O(state=present), O(force=false), and O(clone) is not specified.
231 - If V(false), it will not be updated.
232 - The default changed from V(false) to V(true) in community.proxmox 1.0.0.
233 type: bool
234 default: true
235 force:
236 description:
237 - Forcing operations.
238 - Can be used only with states V(absent), V(present), V(stopped), and V(restarted).
239 - With O(state=present) force option allow to overwrite existing container.
240 - With O(state=absent) force option will force stop the container before deletion.
241 - With states V(stopped), V(restarted) allow to force stop instance.
242 - When specifying O(force), O(update) must not be specified.
243 type: bool
244 default: false
245 purge:
246 description:
247 - Remove container from all related configurations.
248 - For example backup jobs, replication jobs, or HA.
249 - Related ACLs and Firewall entries will always be removed.
250 - Used with O(state=absent).
251 type: bool
252 default: false
253 destroy_unreferenced_disks:
254 description:
255 - Remove unreferenced disks that belong to the container.
256 - Volumes referenced in the config (e.g. via rootfs or mpX parameters) will always be removed.
257 - Used with O(state=absent).
258 type: bool
259 default: false
260 state:
261 description:
262 - Indicate desired state of the instance.
263 type: str
264 choices: ['present', 'started', 'absent', 'stopped', 'restarted', 'template']
265 default: present
266 pubkey:
267 description:
268 - Public key to add to /root/.ssh/authorized_keys. This was added on Proxmox 4.2, it is ignored for earlier versions.
269 type: str
270 unprivileged:
271 description:
272 - Indicate if the container should be unprivileged.
273 type: bool
274 default: true
275 description:
276 description:
277 - Specify the description for the container. Only used on the configuration web interface.
278 - This is saved as a comment inside the configuration file.
279 type: str
280 hookscript:
281 description:
282 - Script that will be executed during various steps in the containers lifetime.
283 type: str
284 timezone:
285 description:
286 - Timezone used by the container, accepts values like V(Europe/Paris).
287 - The special value V(host) configures the same timezone used by Proxmox host.
288 type: str
289 clone:
290 description:
291 - ID of the container to be cloned.
292 - O(description), O(hostname), and O(pool) will be copied from the cloned container if not specified.
293 - The type of clone created is defined by the O(clone_type) parameter.
294 - This operator is only supported for Proxmox clusters that use LXC containerization (PVE version >= 4).
295 type: int
296 clone_type:
297 description:
298 - Type of the clone created.
299 - V(full) creates a full clone, and O(storage) must be specified.
300 - V(linked) creates a linked clone, and the cloned container must be a template container.
301 - V(opportunistic) creates a linked clone if the cloned container is a template container, and a full clone if not.
302 O(storage) may be specified, if not it will fall back to the default.
303 type: str
304 choices: ['full', 'linked', 'opportunistic']
305 default: opportunistic
306 author: Sergei Antipov (@UnderGreen)
307 seealso:
308 - module: community.proxmox.proxmox_vm_info
309 extends_documentation_fragment:
310 - community.proxmox.proxmox.actiongroup_proxmox
311 - community.proxmox.proxmox.documentation
312 - community.proxmox.proxmox.selection
313 - community.proxmox.attributes
314 """
315
316 EXAMPLES = r"""
317 - name: Create new container with minimal options
318 community.proxmox.proxmox:
319 vmid: 100
320 node: uk-mc02
321 password: 123456
322 hostname: example.org
323 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
324
325 - name: Create new container with minimal options specifying disk storage location and size
326 community.proxmox.proxmox:
327 vmid: 100
328 node: uk-mc02
329 password: 123456
330 hostname: example.org
331 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
332 disk: 'local-lvm:20'
333
334 - name: Create new container with minimal options specifying disk storage location and size via disk_volume
335 community.proxmox.proxmox:
336 vmid: 100
337 node: uk-mc02
338 password: 123456
339 hostname: example.org
340 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
341 disk_volume:
342 storage: local
343 size: 20
344
345 - name: Create new container with minimal options specifying console mode set to shell
346 community.proxmox.proxmox:
347 vmid: 100
348 node: uk-mc02
349 password: 123456
350 hostname: example.org
351 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
352 cmode: 'shell'
353
354 - name: Create new container with hookscript and description
355 community.proxmox.proxmox:
356 vmid: 100
357 node: uk-mc02
358 password: 123456
359 hostname: example.org
360 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
361 hookscript: 'local:snippets/vm_hook.sh'
362 description: created with ansible
363
364 - name: Create new container automatically selecting the next available vmid.
365 community.proxmox.proxmox:
366 node: 'uk-mc02'
367 password: '123456'
368 hostname: 'example.org'
369 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
370
371 - name: Create new container with minimal options with force(it will rewrite existing container)
372 community.proxmox.proxmox:
373 vmid: 100
374 node: uk-mc02
375 password: 123456
376 hostname: example.org
377 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
378 force: true
379
380 - name: Create new container with minimal options use environment PROXMOX_PASSWORD variable(you should export it before)
381 community.proxmox.proxmox:
382 vmid: 100
383 node: uk-mc02
384 password: 123456
385 hostname: example.org
386 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
387
388 - name: Create new container with minimal options defining network interface with dhcp
389 community.proxmox.proxmox:
390 vmid: 100
391 node: uk-mc02
392 password: 123456
393 hostname: example.org
394 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
395 netif:
396 net0: "name=eth0,ip=dhcp,ip6=dhcp,bridge=vmbr0"
397
398 - name: Create new container with minimal options defining network interface with static ip
399 community.proxmox.proxmox:
400 vmid: 100
401 node: uk-mc02
402 password: 123456
403 hostname: example.org
404 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
405 netif:
406 net0: "name=eth0,gw=192.168.0.1,ip=192.168.0.2/24,bridge=vmbr0"
407
408 - name: Create new container with more options defining network interface with static ip4 and ip6 with vlan-tag and mtu
409 community.proxmox.proxmox:
410 vmid: 100
411 node: uk-mc02
412 password: 123456
413 hostname: example.org
414 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
415 netif:
416 net0: "name=eth0,gw=192.168.0.1,ip=192.168.0.2/24,ip6=fe80::1227/64,gw6=fe80::1,bridge=vmbr0,firewall=1,tag=934,mtu=1500"
417
418 - name: Create new container with minimal options defining a mount with 8GiB
419 community.proxmox.proxmox:
420 vmid: 100
421 node: uk-mc02
422 password: 123456
423 hostname: example.org
424 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
425 mounts:
426 mp0: "local:8,mp=/mnt/test/"
427
428 - name: Create new container with minimal options defining a mount with 8GiB using mount_volumes
429 community.proxmox.proxmox:
430 vmid: 100
431 node: uk-mc02
432 password: 123456
433 hostname: example.org
434 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
435 mount_volumes:
436 - id: mp0
437 storage: local
438 size: 8
439 mountpoint: /mnt/test
440
441 - name: Create new container with minimal options defining a cpu core limit
442 community.proxmox.proxmox:
443 vmid: 100
444 node: uk-mc02
445 password: 123456
446 hostname: example.org
447 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
448 cores: 2
449
450 - name: Create new container with minimal options and same timezone as proxmox host
451 community.proxmox.proxmox:
452 vmid: 100
453 node: uk-mc02
454 password: 123456
455 hostname: example.org
456 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
457 timezone: host
458
459 - name: Create a new container with nesting enabled and allows the use of CIFS/NFS inside the container.
460 community.proxmox.proxmox:
461 vmid: 100
462 node: uk-mc02
463 password: 123456
464 hostname: example.org
465 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
466 features:
467 - nesting=1
468 - mount=cifs,nfs
469
470 - name: >
471 Create a linked clone of the template container with id 100. The newly created container with be a
472 linked clone, because no storage parameter is defined
473 community.proxmox.proxmox:
474 vmid: 201
475 node: uk-mc02
476 clone: 100
477 hostname: clone.example.org
478
479 - name: Create a full clone of the container with id 100
480 community.proxmox.proxmox:
481 vmid: 201
482 node: uk-mc02
483 clone: 100
484 hostname: clone.example.org
485 storage: local
486
487 - name: Update container configuration
488 community.proxmox.proxmox:
489 vmid: 100
490 node: uk-mc02
491 netif:
492 net0: "name=eth0,gw=192.168.0.1,ip=192.168.0.3/24,bridge=vmbr0"
493 update: true
494
495 - name: Start container
496 community.proxmox.proxmox:
497 vmid: 100
498 state: started
499
500 - name: >
501 Start container with mount. You should enter a 90-second timeout because servers
502 with additional disks take longer to boot
503 community.proxmox.proxmox:
504 vmid: 100
505 state: started
506 timeout: 90
507
508 - name: Stop container
509 community.proxmox.proxmox:
510 vmid: 100
511 state: stopped
512
513 - name: Stop container with force
514 community.proxmox.proxmox:
515 vmid: 100
516 force: true
517 state: stopped
518
519 - name: Restart container(stopped or mounted container you can't restart)
520 community.proxmox.proxmox:
521 vmid: 100
522 state: restarted
523
524 - name: Convert container to template
525 community.proxmox.proxmox:
526 vmid: 100
527 state: template
528
529 - name: Convert container to template (stop container if running)
530 community.proxmox.proxmox:
531 vmid: 100
532 state: template
533 force: true
534
535 - name: Remove container
536 community.proxmox.proxmox:
537 vmid: 100
538 state: absent
539
540 - name: >-
541 Remove container, deleting all volumes that use the container's ID, regardless
542 of whether they are mentioned in the container config or not
543 community.proxmox.proxmox:
544 vmid: 100
545 state: absent
546 destroy_unreferenced_disks: true
547
548 - name: >-
549 Create a new container automatically selecting the next available vmid
550 using a non-root API token
551 community.proxmox.proxmox:
552 node: 'uk-mc02'
553 password: '123456'
554 hostname: 'example.org'
555 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
556
557 - name: >-
558 Create a new container automatically selecting the next available vmid
559 and providing a public key for the root account the Ansible host can use
560 to connect to the new container
561 community.proxmox.proxmox:
562 node: 'uk-mc02'
563 password: '123456'
564 hostname: 'example.org'
565 ostemplate: 'local:vztmpl/ubuntu-14.04-x86_64.tar.gz'
566 pubkey: 'ssh-ed25519 AAAAC3NzaC1...hBWA ansibleuser@ansiblehost'
567 """
568
569 import re
570 import time
571
572 from ansible.module_utils.common.text.converters import to_native
573
574 from ansible_collections.community.proxmox.plugins.module_utils.proxmox import (
575 ProxmoxAnsible,
576 ansible_to_proxmox_bool,
577 create_proxmox_module,
578 )
579 from ansible_collections.community.proxmox.plugins.module_utils.version import LooseVersion
580
581 # Fields PVE stores as a delimited string but the module accepts as a list.
582 _LIST_FIELDS = {"tags": ";"}
583
584
585 def module_args():
586 return dict(
587 vmid=dict(type="int", required=False),
588 node=dict(),
589 pool=dict(),
590 password=dict(no_log=True),
591 hostname=dict(),
592 ostemplate=dict(),
593 disk=dict(type="str"),
594 disk_volume=dict(
595 type="dict",
596 options=dict(
597 storage=dict(type="str"),
598 volume=dict(type="str"),
599 size=dict(type="int"),
600 host_path=dict(type="path"),
601 options=dict(type="dict"),
602 ),
603 required_together=[("storage", "size")],
604 required_by={
605 "volume": ("storage", "size"),
606 },
607 mutually_exclusive=[
608 ("host_path", "storage"),
609 ("host_path", "volume"),
610 ("host_path", "size"),
611 ],
612 ),
613 cmode=dict(
614 default="default",
615 choices=[
616 "default",
617 "tty",
618 "console",
619 "shell",
620 ],
621 ),
622 cores=dict(type="int"),
623 cpus=dict(type="int"),
624 memory=dict(type="int"),
625 swap=dict(type="int"),
626 netif=dict(type="dict"),
627 mounts=dict(type="dict"),
628 mount_volumes=dict(
629 type="list",
630 elements="dict",
631 options=dict(
632 id=(dict(type="str", required=True)),
633 storage=dict(type="str"),
634 volume=dict(type="str"),
635 size=dict(type="int"),
636 host_path=dict(type="path"),
637 mountpoint=dict(type="path", required=True),
638 options=dict(type="dict"),
639 ),
640 required_together=[("storage", "size")],
641 required_by={
642 "volume": ("storage", "size"),
643 },
644 mutually_exclusive=[
645 ("host_path", "storage"),
646 ("host_path", "volume"),
647 ("host_path", "size"),
648 ],
649 ),
650 ip_address=dict(),
651 ostype=dict(
652 default="auto",
653 choices=[
654 "auto",
655 "debian",
656 "devuan",
657 "ubuntu",
658 "centos",
659 "fedora",
660 "opensuse",
661 "archlinux",
662 "alpine",
663 "gentoo",
664 "nixos",
665 "unmanaged",
666 ],
667 ),
668 onboot=dict(type="bool"),
669 features=dict(type="list", elements="str"),
670 delete=dict(type="list", elements="str"),
671 startup=dict(type="list", elements="str"),
672 storage=dict(default="local"),
673 cpuunits=dict(type="int"),
674 nameserver=dict(),
675 searchdomain=dict(),
676 timeout=dict(type="int", default=30),
677 update=dict(type="bool", default=True),
678 force=dict(type="bool", default=False),
679 purge=dict(type="bool", default=False),
680 destroy_unreferenced_disks=dict(type="bool", default=False),
681 state=dict(
682 default="present",
683 choices=[
684 "present",
685 "absent",
686 "stopped",
687 "started",
688 "restarted",
689 "template",
690 ],
691 ),
692 pubkey=dict(type="str"),
693 unprivileged=dict(type="bool", default=True),
694 description=dict(type="str"),
695 hookscript=dict(type="str"),
696 timezone=dict(type="str"),
697 clone=dict(type="int"),
698 clone_type=dict(default="opportunistic", choices=["full", "linked", "opportunistic"]),
699 tags=dict(type="list", elements="str"),
700 )
701
702
703 def module_options():
704 return dict(
705 supports_check_mode=False,
706 required_if=[
707 ("state", "present", ["node", "hostname"]),
708 ("state", "present", ("clone", "ostemplate", "update"), True),
709 ],
710 required_one_of=[("vmid", "hostname")],
711 mutually_exclusive=[
712 ("clone", "ostemplate"),
713 ("clone", "update"),
714 ("force", "update"),
715 ("disk", "disk_volume"),
716 ("storage", "disk_volume"),
717 ("mounts", "mount_volumes"),
718 ],
719 )
720
721
722 class ProxmoxLxcAnsible(ProxmoxAnsible):
723 MINIMUM_VERSIONS = {
724 "disk_volume": "5.0",
725 "mount_volumes": "5.0",
726 "tags": "6.1",
727 "timezone": "6.3",
728 }
729
730 def __init__(self, module):
731 super().__init__(module)
732
733 self.VZ_TYPE = "openvz" if self.version() < LooseVersion("4.0") else "lxc"
734 self.params = self.module.params
735
736 def run(self):
737 self.check_supported_features()
738
739 state = self.params.get("state")
740
741 vmid = self.params.get("vmid")
742 hostname = self.params.get("hostname")
743
744 if not vmid and not hostname:
745 self.module.fail_json(msg="Either VMID or hostname must be provided.")
746
747 if state == "present":
748 self.lxc_present(
749 vmid,
750 hostname,
751 node=self.params.get("node"),
752 update=self.params.get("update"),
753 force=self.params.get("force"),
754 )
755 elif state == "absent":
756 self.lxc_absent(
757 vmid,
758 hostname,
759 node=self.params.get("node"),
760 timeout=self.params.get("timeout"),
761 purge=self.params.get("purge"),
762 destroy_unreferenced_disks=self.params.get("destroy_unreferenced_disks"),
763 force=self.params.get("force"),
764 )
765 elif state == "started":
766 self.lxc_started(
767 vmid,
768 hostname,
769 node=self.params.get("node"),
770 timeout=self.params.get("timeout"),
771 )
772 elif state == "stopped":
773 self.lxc_stopped(
774 vmid,
775 hostname,
776 node=self.params.get("node"),
777 timeout=self.params.get("timeout"),
778 force=self.params.get("force"),
779 )
780 elif state == "restarted":
781 self.lxc_restarted(
782 vmid,
783 hostname,
784 node=self.params.get("node"),
785 timeout=self.params.get("timeout"),
786 force=self.params.get("force"),
787 )
788 elif state == "template":
789 self.lxc_to_template(
790 vmid,
791 hostname,
792 node=self.params.get("node"),
793 timeout=self.params.get("timeout"),
794 force=self.params.get("force"),
795 )
796
797 def lxc_present(self, vmid, hostname, node, update, force):
798 if self.params.get("clone") is not None:
799 update = False
800
801 try:
802 lxc = self.get_lxc_resource(vmid, hostname)
803 vmid = vmid or lxc["id"].split("/")[-1]
804 node = node or lxc["node"]
805 except LookupError:
806 lxc = None
807 vmid = vmid or self.get_nextvmid()
808
809 if node is None:
810 raise ValueError("Argument 'node' is None, but should be found from VMID/hostname or provided.")
811
812 # check if the container exists already
813 if lxc is not None:
814 if update and not force:
815 # Update it if we should
816 identifier = self.format_vm_identifier(vmid, hostname)
817 self.update_lxc_instance(
818 vmid,
819 node,
820 cmode=self.params.get("cmode"),
821 cores=self.params.get("cores"),
822 cpus=self.params.get("cpus"),
823 cpuunits=self.params.get("cpuunits"),
824 description=self.params.get("description"),
825 disk=self.params.get("disk"),
826 disk_volume=self.params.get("disk_volume"),
827 features=self.params.get("features"),
828 delete=self.params.get("delete"),
829 hookscript=self.params.get("hookscript"),
830 hostname=self.params.get("hostname"),
831 ip_address=self.params.get("ip_address"),
832 memory=self.params.get("memory"),
833 mounts=self.params.get("mounts"),
834 mount_volumes=self.params.get("mount_volumes"),
835 nameserver=self.params.get("nameserver"),
836 netif=self.params.get("netif"),
837 onboot=ansible_to_proxmox_bool(self.params.get("onboot")),
838 searchdomain=self.params.get("searchdomain"),
839 startup=self.params.get("startup"),
840 swap=self.params.get("swap"),
841 tags=self.params.get("tags"),
842 timezone=self.params.get("timezone"),
843 )
844 self.module.exit_json(changed=True, vmid=vmid, msg=f"VM {identifier} has been updated.")
845 elif not force:
846 # We're done if it shouldn't be forcefully created
847 identifier = self.format_vm_identifier(vmid, lxc["name"])
848 self.module.exit_json(changed=False, vmid=vmid, msg=f"VM {identifier} already exists.")
849 identifier = self.format_vm_identifier(vmid, lxc["name"])
850 self.module.debug(
851 f"VM {identifier} already exists, but we don't update and instead forcefully recreate it."
852 )
853
854 self.new_lxc_instance(
855 vmid,
856 hostname,
857 node=self.params.get("node"),
858 clone_from=self.params.get("clone"),
859 ostemplate=self.params.get("ostemplate"),
860 force=force,
861 )
862
863 def lxc_absent(self, vmid, hostname, node, timeout, purge, destroy_unreferenced_disks, force): # noqa: PLR0913
864 try:
865 lxc = self.get_lxc_resource(vmid, hostname)
866 except LookupError:
867 identifier = self.format_vm_identifier(vmid, hostname)
868 self.module.exit_json(changed=False, vmid=vmid, msg=f"VM {identifier} is already absent.")
869
870 vmid = vmid or lxc["id"].split("/")[-1]
871 node = node or lxc["node"]
872
873 lxc_status = self.get_lxc_status(vmid, node)
874 identifier = self.format_vm_identifier(vmid, hostname)
875
876 if lxc_status == "running" and not force:
877 self.module.exit_json(
878 changed=False,
879 vmid=vmid,
880 msg=f"VM {identifier} is running. Stop it before deletion.",
881 )
882 if lxc_status == "mounted":
883 self.module.exit_json(
884 changed=False,
885 vmid=vmid,
886 msg=f"VM {identifier} is mounted. Stop it with force option before deletion.",
887 )
888
889 self.remove_lxc_instance(vmid, node, timeout, purge, destroy_unreferenced_disks, force)
890 self.module.exit_json(changed=True, vmid=vmid, msg=f"VM {identifier} removed.")
891
892 def lxc_started(self, vmid, hostname, node, timeout):
893 lxc = self.get_lxc_resource(vmid, hostname)
894 vmid = vmid or lxc["id"].split("/")[-1]
895 hostname = hostname or lxc["name"]
896 identifier = self.format_vm_identifier(vmid, hostname)
897 node = node or lxc["node"]
898 lxc_status = self.get_lxc_status(vmid, lxc["node"])
899
900 if lxc_status == "running":
901 self.module.exit_json(changed=False, vmid=vmid, msg=f"VM {identifier} is already running.")
902
903 self.start_lxc_instance(vmid, node, timeout)
904 self.module.exit_json(changed=True, vmid=vmid, msg=f"VM {identifier} started.")
905
906 def lxc_stopped(self, vmid, hostname, node, timeout, force):
907 lxc = self.get_lxc_resource(vmid, hostname)
908 vmid = vmid or lxc["id"].split("/")[-1]
909 hostname = hostname or lxc["name"]
910 identifier = self.format_vm_identifier(vmid, hostname)
911 node = node or lxc["node"]
912 lxc_status = self.get_lxc_status(vmid, node)
913
914 if lxc_status == "mounted":
915 if force:
916 self.umount_lxc_instance(vmid, hostname, timeout)
917 else:
918 self.module.exit_json(
919 changed=False,
920 vmid=vmid,
921 msg=f"VM {identifier} is already stopped, but mounted. Use force option to umount it.",
922 )
923
924 if lxc_status == "stopped":
925 self.module.exit_json(changed=False, vmid=vmid, msg=f"VM {identifier} is already stopped.")
926
927 self.stop_lxc_instance(vmid, node, timeout, force)
928 self.module.exit_json(changed=True, vmid=vmid, msg=f"VM {identifier} stopped.")
929
930 def lxc_restarted(self, vmid, hostname, node, timeout, force):
931 lxc = self.get_lxc_resource(vmid, hostname)
932
933 vmid = vmid or lxc["id"].split("/")[-1]
934 hostname = hostname or lxc["name"]
935 node = node or lxc["node"]
936
937 identifier = self.format_vm_identifier(vmid, hostname)
938 lxc_status = self.get_lxc_status(vmid, node)
939
940 if lxc_status in ["stopped", "mounted"]:
941 self.module.exit_json(changed=False, vmid=vmid, msg=f"VM {identifier} is not running.")
942
943 self.stop_lxc_instance(vmid, node, timeout, force)
944 self.start_lxc_instance(vmid, node, timeout)
945 self.module.exit_json(changed=True, vmid=vmid, msg=f"VM {identifier} is restarted.")
946
947 def lxc_to_template(self, vmid, hostname, node, timeout, force):
948 lxc = self.get_lxc_resource(vmid, hostname)
949 vmid = vmid or lxc["id"].split("/")[-1]
950 hostname = hostname or lxc["name"]
951 node = node or lxc["node"]
952 identifier = self.format_vm_identifier(vmid, hostname)
953
954 if self.is_template_container(node, vmid):
955 self.module.exit_json(
956 changed=False,
957 vmid=vmid,
958 msg=f"VM {identifier} is already a template.",
959 )
960
961 lxc_status = self.get_lxc_status(vmid, node)
962 if lxc_status == "running" and force:
963 self.stop_instance(vmid, hostname, node, timeout, force)
964
965 proxmox_node = self.proxmox_api.nodes(node)
966 getattr(proxmox_node, self.VZ_TYPE)(vmid).template.post()
967 self.module.exit_json(changed=True, vmid=vmid, msg=f"VM {identifier} converted to template.")
968
969 def update_lxc_instance(self, vmid, node, **kwargs): # noqa: PLR0912
970 if self.VZ_TYPE != "lxc":
971 self.module.fail_json(
972 msg="Updating LXC containers is only supported for LXC-enabled clusters in PVE 4.0 and above."
973 )
974
975 kwargs = {k: v for k, v in kwargs.items() if v is not None}
976
977 self.validate_tags(kwargs.get("tags", []))
978
979 if "features" in kwargs:
980 kwargs["features"] = ",".join(kwargs.pop("features"))
981 if "startup" in kwargs:
982 kwargs["startup"] = ",".join(kwargs.pop("startup"))
983 if "delete" in kwargs:
984 kwargs["delete"] = ",".join(kwargs.pop("delete"))
985
986 disk_updates = self.process_disk_keys(
987 vmid,
988 node,
989 kwargs.pop("disk", None),
990 kwargs.pop("disk_volume", None),
991 )
992 mounts_updates = self.process_mount_keys(
993 vmid,
994 node,
995 kwargs.pop("mounts", None),
996 kwargs.pop("mount_volumes", None),
997 )
998 kwargs.update(disk_updates)
999 kwargs.update(mounts_updates)
1000
1001 if "cpus" in kwargs:
1002 kwargs["cpulimit"] = kwargs.pop("cpus")
1003 if "netif" in kwargs:
1004 kwargs.update(kwargs.pop("netif"))
1005
1006 if "pubkey" in kwargs:
1007 pubkey = kwargs.pop("pubkey")
1008 if self.version() >= LooseVersion("4.2"):
1009 kwargs["ssh-public-keys"] = pubkey
1010 else:
1011 self.module.warn("'pubkey' is not supported for PVE 4.1 and below. Ignoring keyword.")
1012
1013 # fetch current config
1014 proxmox_node = self.proxmox_api.nodes(node)
1015 current_config = getattr(proxmox_node, self.VZ_TYPE)(vmid).config.get()
1016
1017 # create diff between the current and requested config
1018 diff = {}
1019
1020 for arg, value in kwargs.items():
1021 if arg in _LIST_FIELDS and isinstance(value, list):
1022 sep = _LIST_FIELDS[arg]
1023 current = {x for x in current_config.get(arg, "").split(sep) if x}
1024 if current != set(value):
1025 diff[arg] = value
1026 continue
1027 # if the arg isn't in the current config, it needs to be added
1028 if arg not in current_config:
1029 diff[arg] = value
1030 elif isinstance(value, str):
1031 # compare all string values as lists as some of them may be lists separated by commas. order doesn't matter
1032 current_values = current_config[arg].split(",")
1033 requested_values = value.split(",")
1034 for new_value in requested_values:
1035 if new_value not in current_values:
1036 diff[arg] = value
1037 break
1038 # if it's not a list (or string) just compare the values
1039 # some types don't match with the API, so force a string comparison
1040 elif str(value) != str(current_config[arg]):
1041 diff[arg] = value
1042
1043 if not diff:
1044 self.module.exit_json(changed=False, vmid=vmid, msg="Container config is already up to date.")
1045
1046 # update the config
1047 getattr(proxmox_node, self.VZ_TYPE)(vmid).config.put(vmid=vmid, node=node, **kwargs)
1048
1049 def new_lxc_instance(self, vmid, hostname, node, clone_from, ostemplate, force): # noqa: PLR0913
1050 identifier = self.format_vm_identifier(vmid, hostname)
1051
1052 if clone_from is not None:
1053 self.clone_lxc_instance(
1054 vmid,
1055 node,
1056 clone_from,
1057 clone_type=self.params.get("clone_type"),
1058 timeout=self.params.get("timeout"),
1059 description=self.params.get("description"),
1060 hostname=hostname,
1061 pool=self.params.get("pool"),
1062 storage=self.params.get("storage"),
1063 )
1064 self.module.exit_json(
1065 changed=True,
1066 vmid=vmid,
1067 msg=f"Cloned VM {identifier} from {clone_from}",
1068 )
1069
1070 if ostemplate is not None:
1071 self.create_lxc_instance(
1072 vmid,
1073 node,
1074 ostemplate,
1075 timeout=self.params.get("timeout"),
1076 cmode=self.params.get("cmode"),
1077 cores=self.params.get("cores"),
1078 cpus=self.params.get("cpus"),
1079 cpuunits=self.params.get("cpuunits"),
1080 description=self.params.get("description"),
1081 disk=self.params.get("disk"),
1082 disk_volume=self.params.get("disk_volume"),
1083 features=self.params.get("features"),
1084 force=ansible_to_proxmox_bool(force),
1085 hookscript=self.params.get("hookscript"),
1086 hostname=hostname,
1087 ip_address=self.params.get("ip_address"),
1088 memory=self.params.get("memory"),
1089 mounts=self.params.get("mounts"),
1090 mount_volumes=self.params.get("mount_volumes"),
1091 nameserver=self.params.get("nameserver"),
1092 netif=self.params.get("netif"),
1093 onboot=ansible_to_proxmox_bool(self.params.get("onboot")),
1094 ostype=self.params.get("ostype"),
1095 password=self.params.get("password"),
1096 pool=self.params.get("pool"),
1097 pubkey=self.params.get("pubkey"),
1098 searchdomain=self.params.get("searchdomain"),
1099 startup=self.params.get("startup"),
1100 storage=self.params.get("storage"),
1101 swap=self.params.get("swap"),
1102 tags=self.params.get("tags"),
1103 timezone=self.params.get("timezone"),
1104 unprivileged=ansible_to_proxmox_bool(self.params.get("unprivileged")),
1105 )
1106 self.module.exit_json(
1107 changed=True,
1108 vmid=vmid,
1109 msg=f"Created VM {identifier} from template {ostemplate}",
1110 )
1111
1112 self.module.fail_json(
1113 vmid=vmid,
1114 msg=f"VM {identifier} does not exist but neither clone nor ostemplate were specified!",
1115 )
1116
1117 def create_lxc_instance(self, vmid, node, ostemplate, timeout, **kwargs):
1118 template_store = ostemplate.split(":")[0]
1119 if not self.content_check(node, ostemplate, template_store):
1120 self.module.fail_json(
1121 vmid=vmid,
1122 msg=f"ostemplate {ostemplate} does not exist on node {node} and storage {template_store}.",
1123 )
1124
1125 disk_updates = self.process_disk_keys(
1126 vmid,
1127 node,
1128 kwargs.pop("disk"),
1129 kwargs.pop("disk_volume"),
1130 )
1131 mounts_updates = self.process_mount_keys(
1132 vmid,
1133 node,
1134 kwargs.pop("mounts"),
1135 kwargs.pop("mount_volumes"),
1136 )
1137 kwargs.update(disk_updates)
1138 kwargs.update(mounts_updates)
1139
1140 # Remove empty values from kwargs
1141 kwargs = {k: v for k, v in kwargs.items() if v is not None}
1142
1143 if "features" in kwargs:
1144 kwargs["features"] = ",".join(kwargs.pop("features"))
1145
1146 if "startup" in kwargs:
1147 kwargs["startup"] = ",".join(kwargs.pop("startup"))
1148
1149 self.validate_tags(kwargs.get("tags", []))
1150
1151 if self.VZ_TYPE == "lxc":
1152 if "cpus" in kwargs:
1153 kwargs["cpuunits"] = kwargs.pop("cpus")
1154 kwargs.update(kwargs.pop("netif", {}))
1155 elif "mount_volumes" in kwargs:
1156 kwargs.pop("mount_volumes")
1157 self.module.warn("'mount_volumes' is not supported for non-LXC clusters. Ignoring keyword.")
1158
1159 if "pubkey" in kwargs:
1160 pubkey = kwargs.pop("pubkey")
1161 if self.version() >= LooseVersion("4.2"):
1162 kwargs["ssh-public-keys"] = pubkey
1163 else:
1164 self.module.warn("'pubkey' is not supported for PVE 4.1 and below. Ignoring keyword.")
1165
1166 if kwargs.get("ostype") == "auto":
1167 kwargs.pop("ostype")
1168
1169 if kwargs.get("cmode") == "default":
1170 kwargs.pop("cmode")
1171
1172 proxmox_node = self.proxmox_api.nodes(node)
1173 taskid = getattr(proxmox_node, self.VZ_TYPE).create(vmid=vmid, ostemplate=ostemplate, **kwargs)
1174 self.handle_api_timeout(
1175 vmid,
1176 node,
1177 taskid,
1178 timeout,
1179 f"Reached timeout while waiting for creation of VM {vmid} from template {ostemplate}",
1180 )
1181
1182 def clone_lxc_instance(self, vmid, node, clone_from, clone_type, timeout, **kwargs):
1183 if self.VZ_TYPE != "lxc":
1184 self.module.fail_json(msg="Cloning is only supported for LXC-enabled clusters in PVE 4.0 and above.")
1185
1186 # Remove empty values from kwargs
1187 kwargs = {k: v for k, v in kwargs.items() if v is not None}
1188
1189 target_is_template = self.is_template_container(node, clone_from)
1190 # By default, create a full copy only when the cloned container is not a template.
1191 create_full_copy = not target_is_template
1192
1193 # Only accept parameters that are compatible with the clone endpoint.
1194 valid_clone_parameters = ["hostname", "pool", "description"]
1195
1196 if "storage" not in kwargs and target_is_template:
1197 # Cloning a template, so create a full copy instead of a linked copy
1198 create_full_copy = True
1199 elif "storage" not in kwargs and not target_is_template:
1200 self.module.fail_json(
1201 changed=False,
1202 msg="Clone target container is not a template, storage needs to be specified.",
1203 )
1204
1205 if clone_type == "linked" and not target_is_template:
1206 self.module.fail_json(
1207 changed=False,
1208 msg="Cloning type 'linked' is only supported for template containers.",
1209 )
1210 elif clone_type == "opportunistic" and not target_is_template:
1211 # Cloned container is not a template, so we need our 'storage' parameter
1212 valid_clone_parameters.append("storage")
1213 elif clone_type == "full":
1214 create_full_copy = True
1215 valid_clone_parameters.append("storage")
1216
1217 clone_parameters = {}
1218 clone_parameters["full"] = ansible_to_proxmox_bool(create_full_copy)
1219
1220 for param in valid_clone_parameters:
1221 if param in kwargs:
1222 clone_parameters[param] = kwargs[param]
1223
1224 proxmox_node = self.proxmox_api.nodes(node)
1225 taskid = getattr(proxmox_node, self.VZ_TYPE)(clone_from).clone.post(newid=vmid, **clone_parameters)
1226 self.handle_api_timeout(
1227 vmid,
1228 node,
1229 taskid,
1230 timeout,
1231 timeout_msg="Reached timeout while waiting for VM to clone.",
1232 )
1233
1234 def start_lxc_instance(self, vmid, node, timeout):
1235 proxmox_node = self.proxmox_api.nodes(node)
1236 taskid = getattr(proxmox_node, self.VZ_TYPE)(vmid).status.start.post()
1237
1238 self.handle_api_timeout(
1239 vmid,
1240 node,
1241 taskid,
1242 timeout,
1243 timeout_msg="Reached timeout while waiting for VM to start.",
1244 )
1245
1246 def stop_lxc_instance(self, vmid, node, timeout, force):
1247 stop_params = {}
1248 if force:
1249 stop_params["forceStop"] = 1
1250
1251 proxmox_node = self.proxmox_api.nodes(node)
1252 taskid = getattr(proxmox_node, self.VZ_TYPE)(vmid).status.shutdown.post(**stop_params)
1253
1254 self.handle_api_timeout(
1255 vmid,
1256 node,
1257 taskid,
1258 timeout,
1259 timeout_msg="Reached timeout while waiting for VM to stop.",
1260 )
1261
1262 def umount_lxc_instance(self, vmid, node, timeout):
1263 proxmox_node = self.proxmox_api.nodes(node)
1264 taskid = getattr(proxmox_node, self.VZ_TYPE)(vmid).status.unmount.post()
1265
1266 self.handle_api_timeout(
1267 vmid,
1268 node,
1269 taskid,
1270 timeout,
1271 timeout_msg="Reached timeout while waiting for VM to be unmounted.",
1272 )
1273
1274 def remove_lxc_instance(self, vmid, node, timeout, purge, destroy_unreferenced_disks, force): # noqa: PLR0913
1275 delete_params = {}
1276 if purge:
1277 delete_params["purge"] = 1
1278
1279 if destroy_unreferenced_disks:
1280 delete_params["destroy-unreferenced-disks"] = 1
1281
1282 if force:
1283 delete_params["force"] = 1
1284
1285 proxmox_node = self.proxmox_api.nodes(node)
1286 taskid = getattr(proxmox_node, self.VZ_TYPE).delete(vmid, **delete_params)
1287
1288 self.handle_api_timeout(
1289 vmid,
1290 node,
1291 taskid,
1292 timeout,
1293 timeout_msg="Reached timeout while waiting for VM to be removed.",
1294 )
1295
1296 def process_disk_keys(self, vmid, node, disk, disk_volume):
1297 """
1298 Process disk keys and return a formatted disk volume with the `rootfs` key.
1299
1300 Args:
1301 vmid (int): VM identifier.
1302 node (str): Node identifier.
1303 disk (str, optional): Disk key in the format 'storage:volume'. Defaults to None.
1304 disk_volume (Dict[str, Any], optional): Disk volume data. Defaults to None.
1305
1306 Returns:
1307 Dict[str, str]: Formatted disk volume with the `rootfs` or `disk` key (depending on the `VZ_TYPE`), or an empty dict if no disk volume is specified.
1308 """
1309 if disk is None and disk_volume is None:
1310 return {}
1311
1312 disk_dict = {}
1313
1314 if disk is not None:
1315 if disk.isdigit():
1316 disk_dict["rootfs"] = disk
1317 else:
1318 disk_volume = self.parse_disk_string(disk)
1319
1320 if disk_volume is not None:
1321 disk_dict = self.build_volume(vmid, node, key="rootfs", **disk_volume)
1322
1323 if self.VZ_TYPE != "lxc":
1324 disk_dict["disk"] = disk_dict.pop("rootfs")
1325
1326 return disk_dict
1327
1328 def process_mount_keys(self, vmid, node, mounts, mount_volumes):
1329 """
1330 Process mount keys and return a formatted mount volumes with the `mp[n]` keys.
1331
1332 Args:
1333 vmid (str): VM identifier.
1334 node (str): Node identifier.
1335 mounts (str, optional): Mount key in the format 'pool:volume'. Defaults to None.
1336 mount_volumes (Dict[str, Any], optional): Mount volume data. Defaults to None.
1337
1338 Returns:
1339 Dict[str, str]: Formatted mount volumes with the `mp[n]` keys, or an empty dict if no mount volumes are specified.
1340 """
1341 if mounts is not None:
1342 mount_volumes = []
1343 for mount_key, mount_string in mounts.items():
1344 mount_config = self.parse_disk_string(mount_string)
1345 mount_volumes.append(dict(id=mount_key, **mount_config))
1346 elif mount_volumes is None or mount_volumes == []:
1347 return {}
1348
1349 mounts_dict = {}
1350 for mount_config in mount_volumes:
1351 mount_key = mount_config.pop("id")
1352 mount_dict = self.build_volume(vmid, node, key=mount_key, **mount_config)
1353 mounts_dict.update(mount_dict)
1354
1355 return mounts_dict
1356
1357 def parse_disk_string(self, disk_string):
1358 """
1359 Parse a disk string and return a dictionary with the disk details.
1360
1361 Args:
1362 disk_string (str): Disk string.
1363
1364 Returns:
1365 Dict[str, Any]: Disk details.
1366
1367 Note: Below are some example disk strings that this function MUST be able to parse:
1368 "acl=0,thin1:base-100-disk-1,size=8G"
1369 "thin1:10,backup=0"
1370 "local:20"
1371 "local-lvm:0.50"
1372 "tmp-dir:300/subvol-300-disk-0.subvol,acl=1,size=0T"
1373 "tmplog-dir:300/vm-300-disk-0.raw,mp=/var/log,mountoptions=noatime,size=32M"
1374 "volume=local-lvm:base-100-disk-1,size=20G"
1375 "/mnt/bindmounts/shared,mp=/shared"
1376 "volume=/dev/USB01,mp=/mnt/usb01"
1377 """
1378 args = disk_string.split(",")
1379 # If the volume is not explicitly defined but implicit by only passing a key,
1380 # add the "volume=" key prefix for ease of parsing.
1381 args = ["volume=" + arg if "=" not in arg else arg for arg in args]
1382 # Then create a dictionary from the arguments
1383 disk_kwargs = dict(map(lambda item: item.split("="), args))
1384
1385 VOLUME_PATTERN = r"""(?x)
1386 ^
1387 (?:
1388 (?:
1389 (?P<storage>[\w\-.]+):
1390 (?:
1391 (?P<size>\d+\.?\d*)|
1392 (?P<volume>[^,\s]+)
1393 )
1394 )|
1395 (?P<host_path>[^,\s]+)
1396 )
1397 $
1398 """
1399 # DISCLAIMER:
1400 # There are two things called a "volume":
1401 # 1. The "volume" key which describes the storage volume, device or directory to mount into the container.
1402 # 2. The storage volume of a storage-backed mount point in the PVE storage sub system.
1403 # In this section, we parse the "volume" key and check which type of mount point we are dealing with.
1404 pattern = re.compile(VOLUME_PATTERN)
1405 volume_string = disk_kwargs.pop("volume")
1406 match = pattern.match(volume_string)
1407 if match is None:
1408 raise ValueError(("Invalid volume string: %s", volume_string))
1409 match_dict = match.groupdict()
1410 match_dict = {k: v for k, v in match_dict.items() if v is not None}
1411
1412 if "storage" in match_dict and "volume" in match_dict:
1413 disk_kwargs["storage"] = match_dict["storage"]
1414 disk_kwargs["volume"] = match_dict["volume"]
1415 elif "storage" in match_dict and "size" in match_dict:
1416 disk_kwargs["storage"] = match_dict["storage"]
1417 disk_kwargs["size"] = match_dict["size"]
1418 elif "host_path" in match_dict:
1419 disk_kwargs["host_path"] = match_dict["host_path"]
1420
1421 # Pattern matching only available in Python 3.10+
1422 # TODO: Uncomment the following code once only Python 3.10+ is supported
1423 # match match_dict:
1424 # case {"storage": storage, "volume": volume}:
1425 # disk_kwargs["storage"] = storage
1426 # disk_kwargs["volume"] = volume
1427
1428 # case {"storage": storage, "size": size}:
1429 # disk_kwargs["storage"] = storage
1430 # disk_kwargs["size"] = size
1431
1432 # case {"host_path": host_path}:
1433 # disk_kwargs["host_path"] = host_path
1434
1435 return disk_kwargs
1436
1437 def build_volume( # noqa: PLR0912, PLR0913
1438 self,
1439 vmid,
1440 node,
1441 key,
1442 storage=None,
1443 volume=None,
1444 host_path=None,
1445 size=None,
1446 mountpoint=None,
1447 options=None,
1448 **kwargs,
1449 ):
1450 """
1451 Build a volume string for the specified VM.
1452
1453 Args:
1454 vmid (str): The VM ID.
1455 node (str): The node where the VM resides.
1456 key (str): The key for the volume in the VM's config.
1457 storage (str, optional): The storage pool where the volume resides. Defaults to None.
1458 volume (str, optional): The name of the volume. Defaults to None.
1459 host_path (str, optional): The host path to mount. Defaults to None.
1460 size (str | int, optional): The size of the volume in GiB. Defaults to None.
1461 mountpoint (str, optional): The mountpoint for the volume. Defaults to None.
1462 options (Dict[str, Any], optional): Additional options for the volume. Defaults to None.
1463 **kwargs: Additional keyword arguments.
1464
1465 Returns:
1466 Dict[str, str]: The built volume string in the format {'volume_key': 'volume_string'}.
1467
1468 Note: Further documentation can be found in the proxmox-api documentation: https://pve.proxmox.com/wiki/Linux_Container#pct_mount_points
1469 Note: To build a valid volume string, we need ONE of the following:
1470 A volume name, storage name, and size
1471 Only a storage name and size (to create a new volume or assign the volume automatically)
1472 A host directory to mount into the container
1473 """
1474 if isinstance(size, int):
1475 size = str(size)
1476 if size is not None and isfloat(size):
1477 size += "G" # default to GiB
1478 # Handle volume checks/creation
1479 # TODO: Change the code below to pattern matching once only Python 3.10+ is supported
1480 # 1. Check if defined volume exists
1481 if volume is not None:
1482 storage_content = self.get_storage_content(node, storage, vmid=vmid)
1483 vol_ids = [vol["volid"] for vol in storage_content]
1484 volid = f"{storage}:{volume}"
1485 if volid not in vol_ids:
1486 self.module.fail_json(
1487 changed=False,
1488 msg=f"Storage {storage} does not contain volume {volume}",
1489 )
1490 vol_parts = [
1491 f"{storage}:{volume}",
1492 f"size={size}",
1493 ]
1494 # 2. If volume not defined (but storage is), check if it exists
1495 elif storage is not None:
1496 proxmox_node = self.proxmox_api.nodes(node) # The node must exist, but not the LXC
1497 try:
1498 vol = proxmox_node.lxc(vmid).get("config").get(key)
1499 volume = self.parse_disk_string(vol).get("volume")
1500 vol_parts = [
1501 f"{storage}:{volume}",
1502 f"size={size}",
1503 ]
1504
1505 # If not, we have proxmox create one using the special syntax
1506 except Exception as e:
1507 if size is None:
1508 raise ValueError("Size must be provided for storage-backed volume creation.") from e
1509 elif size.endswith("G"):
1510 size = size.rstrip("G")
1511 vol_parts = [f"{storage}:{size}"]
1512 else:
1513 raise ValueError(
1514 "Size must be provided in GiB for storage-backed volume creation. Convert it to GiB or allocate a new storage manually."
1515 ) from e
1516 # 3. If we have a host_path, we don't have storage, a volume, or a size
1517 # Then we don't have to do anything, just build and return the vol_string
1518 elif host_path is not None:
1519 vol_parts = []
1520 else:
1521 raise ValueError(
1522 "Could not build a valid volume string. One of volume, storage, or host_path must be provided."
1523 )
1524
1525 if host_path is not None:
1526 vol_parts += [host_path]
1527
1528 if mountpoint is not None:
1529 vol_parts += [f"mp={mountpoint}"]
1530
1531 if options is not None:
1532 vol_parts += [f"{k}={v}" for k, v in options.items()]
1533
1534 if kwargs:
1535 vol_parts += [f"{k}={v}" for k, v in kwargs.items()]
1536 return {key: ",".join(vol_parts)}
1537
1538 def get_lxc_resource(self, vmid, hostname):
1539 if not vmid and not hostname:
1540 self.module.fail_json(msg="Either VMID or hostname must be provided.")
1541
1542 if vmid:
1543 vm = self.get_lxc_resource_by_id(vmid)
1544 elif hostname:
1545 vm = self.get_lxc_resource_by_hostname(hostname)
1546
1547 vmid = vm["vmid"]
1548 if vm["type"] != self.VZ_TYPE:
1549 identifier = self.format_vm_identifier(vmid, hostname)
1550 self.module.fail_json(msg=f"The specified VM {identifier} is not an {self.VZ_TYPE}.")
1551
1552 return vm
1553
1554 def get_lxc_resource_by_id(self, vmid):
1555 vms = self.get_vm_resources()
1556
1557 vms = [vm for vm in vms if vm["vmid"] == vmid]
1558 if len(vms) == 0:
1559 raise LookupError(f"VM with VMID {vmid} does not exist in cluster.")
1560
1561 return vms[0]
1562
1563 def get_lxc_resource_by_hostname(self, hostname):
1564 vms = self.get_vm_resources()
1565
1566 vms = [vm for vm in vms if vm["name"] == hostname]
1567 if len(vms) == 0:
1568 raise LookupError(f"VM with hostname {hostname} does not exist in cluster.")
1569 elif len(vms) > 1:
1570 raise ValueError(f"Multiple VMs found with hostname {hostname}. Please specify VMID.")
1571
1572 return vms[0]
1573
1574 def get_vm_resources(self):
1575 try:
1576 return self.proxmox_api.cluster.resources.get(type="vm")
1577 except Exception as e:
1578 self.module.fail_json(msg=f"Unable to retrieve list of {self.VZ_TYPE} VMs from cluster resources: {e}")
1579
1580 def get_lxc_status(self, vmid, node_name):
1581 try:
1582 proxmox_node = self.proxmox_api.nodes(node_name)
1583 except Exception as e:
1584 self.module.fail_json(msg=f"Unable to retrieve node information: {e}")
1585 return getattr(proxmox_node, self.VZ_TYPE)(vmid).status.current.get()["status"]
1586
1587 def format_vm_identifier(self, vmid, hostname):
1588 if vmid and hostname:
1589 return f"{hostname} ({vmid})"
1590 elif hostname:
1591 return hostname
1592 else:
1593 return to_native(vmid)
1594
1595 def handle_api_timeout(self, vmid, node, taskid, timeout, timeout_msg=""):
1596 if timeout_msg != "":
1597 timeout_msg = f"{timeout_msg} "
1598
1599 while timeout > 0:
1600 if self.api_task_ok(node, taskid):
1601 return
1602 timeout -= 1
1603 time.sleep(1)
1604
1605 self.module.fail_json(
1606 vmid=vmid,
1607 taskid=taskid,
1608 msg=f"{timeout_msg}Last line in task before timeout: {self.proxmox_api.nodes(node).tasks(taskid).log.get()[:1]}",
1609 )
1610
1611 def is_template_container(self, node, target):
1612 """Check if the specified container is a template."""
1613 proxmox_node = self.proxmox_api.nodes(node)
1614 config = getattr(proxmox_node, self.VZ_TYPE)(target).config.get()
1615 return config.get("template", False)
1616
1617 def content_check(self, node, ostemplate, template_store):
1618 """Check if the specified ostemplate is present in the specified storage."""
1619 proxmox_node = self.proxmox_api.nodes(node)
1620 storage_contents = proxmox_node.storage(template_store).content.get()
1621 return any(content["volid"] == ostemplate for content in storage_contents)
1622
1623 def validate_tags(self, tags):
1624 """Check if the specified tags are valid."""
1625 re_tag = re.compile(r"^[a-zA-Z0-9_][a-zA-Z0-9_\-\+\.]*$")
1626 for tag in tags:
1627 if not re_tag.match(tag):
1628 self.module.fail_json(msg=f"{tag} is not a valid tag")
1629 return False
1630 return True
1631
1632 def check_supported_features(self):
1633 for option, version in self.MINIMUM_VERSIONS.items():
1634 if self.version() < LooseVersion(version) and option in self.module.params:
1635 self.module.fail_json(
1636 changed=False,
1637 msg=f"Feature {option} is only supported in PVE {version}+, and you're using PVE {self.version()}",
1638 )
1639
1640
1641 def isfloat(value):
1642 if value is None:
1643 return False
1644 try:
1645 float(value)
1646 return True
1647 except ValueError:
1648 return False
1649
1650
1651 def main():
1652 module = create_proxmox_module(module_args(), **module_options())
1653 proxmox = ProxmoxLxcAnsible(module)
1654
1655 try:
1656 proxmox.run()
1657 except Exception as e:
1658 module.fail_json(msg=f"An error occurred: {to_native(e)}")
1659
1660
1661 if __name__ == "__main__":
1662 main()