Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Hiroaki Nakamura <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: lxd_container
11 short_description: Manage LXD instances
12 description:
13 - Management of LXD containers and virtual machines.
14 author: "Hiroaki Nakamura (@hnakamur)"
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: full
20 version_added: 6.4.0
21 diff_mode:
22 support: full
23 version_added: 6.4.0
24 options:
25 name:
26 description:
27 - Name of an instance.
28 type: str
29 required: true
30 project:
31 description:
32 - Project of an instance.
33 - See U(https://documentation.ubuntu.com/lxd/en/latest/projects/).
34 type: str
35 version_added: 4.8.0
36 architecture:
37 description:
38 - The architecture for the instance (for example V(x86_64) or V(i686)).
39 - See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/instances/instance_get).
40 type: str
41 config:
42 description:
43 - 'The config for the instance (for example V({"limits.cpu": "2"})).'
44 - All values in O(config) must be strings, as required by the LXD/Incus API.
45 Using non-string values (such as integers or booleans) will cause an API error.
46 Make sure to quote numeric and boolean values in YAML (for example, use V("2") instead of V(2)).
47 - See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/instances/instance_get).
48 - If the instance already exists and its "config" values in metadata obtained from the LXD API
49 U(https://documentation.ubuntu.com/lxd/en/latest/api/#/instances/instance_get)
50 are different, then this module tries to apply the configurations U(https://documentation.ubuntu.com/lxd/en/latest/api/#/instances/instance_put).
51 - The keys starting with C(volatile.) are ignored for this comparison when O(ignore_volatile_options=true).
52 type: dict
53 ignore_volatile_options:
54 description:
55 - If set to V(true), options starting with C(volatile.) are ignored. As a result, they are reapplied for each execution.
56 - This default behavior can be changed by setting this option to V(false).
57 - The default value changed from V(true) to V(false) in community.general 6.0.0.
58 type: bool
59 default: false
60 version_added: 3.7.0
61 profiles:
62 description:
63 - Profile to be used by the instance.
64 type: list
65 elements: str
66 devices:
67 description:
68 - 'The devices for the instance (for example V({ "rootfs": { "path": "/dev/kvm", "type": "unix-char" }})).'
69 - See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/instances/instance_get).
70 type: dict
71 ephemeral:
72 description:
73 - Whether or not the instance is ephemeral (for example V(true) or V(false)).
74 - See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/instances/instance_get).
75 type: bool
76 source:
77 description:
78 - 'The source for the instance (for example V({ "type": "image", "mode": "pull", "server": "https://cloud-images.ubuntu.com/releases/",
79 "protocol": "simplestreams", "alias": "22.04" })).'
80 - See U(https://documentation.ubuntu.com/lxd/en/latest/api/) for complete API documentation.
81 - 'Note that C(protocol) accepts two choices: V(lxd) or V(simplestreams).'
82 type: dict
83 state:
84 choices:
85 - started
86 - stopped
87 - restarted
88 - absent
89 - frozen
90 description:
91 - Define the state of an instance.
92 default: started
93 type: str
94 target:
95 description:
96 - For cluster deployments. It attempts to create an instance on a target node. If the instance exists elsewhere in a
97 cluster, then it is not replaced nor moved. The name should respond to same name of the node you see in C(lxc cluster
98 list).
99 type: str
100 version_added: 1.0.0
101 timeout:
102 description:
103 - A timeout for changing the state of the instance.
104 - This is also used as a timeout for waiting until IPv4 addresses are set to the all network interfaces in the instance
105 after starting or restarting.
106 default: 30
107 type: int
108 type:
109 description:
110 - Instance type can be either V(virtual-machine) or V(container).
111 default: container
112 choices:
113 - container
114 - virtual-machine
115 type: str
116 version_added: 4.1.0
117 wait_for_ipv4_addresses:
118 description:
119 - If this is V(true), the C(lxd_container) waits until IPv4 addresses are set to the all network interfaces in the instance
120 after starting or restarting.
121 default: false
122 type: bool
123 wait_for_container:
124 description:
125 - If set to V(true), the tasks wait until the task reports a success status when performing container operations.
126 default: false
127 type: bool
128 version_added: 4.4.0
129 force_stop:
130 description:
131 - If this is V(true), the C(lxd_container) forces to stop the instance when it stops or restarts the instance.
132 default: false
133 type: bool
134 url:
135 description:
136 - The unix domain socket path or the https URL for the LXD server.
137 default: unix:/var/lib/lxd/unix.socket
138 type: str
139 snap_url:
140 description:
141 - The unix domain socket path when LXD is installed by snap package manager.
142 default: unix:/var/snap/lxd/common/lxd/unix.socket
143 type: str
144 client_key:
145 description:
146 - The client certificate key file path.
147 - If not specified, it defaults to C(${HOME}/.config/lxc/client.key).
148 aliases: [key_file]
149 type: path
150 client_cert:
151 description:
152 - The client certificate file path.
153 - If not specified, it defaults to C(${HOME}/.config/lxc/client.crt).
154 aliases: [cert_file]
155 type: path
156 trust_password:
157 description:
158 - The client trusted password.
159 - 'You need to set this password on the LXD server before running this module using the following command: C(lxc config
160 set core.trust_password <some random password>). See U(https://www.stgraber.org/2016/04/18/lxd-api-direct-interaction/).'
161 - If trust_password is set, this module send a request for authentication before sending any requests.
162 type: str
163 notes:
164 - Instances can be a container or a virtual machine, both of them must have unique name. If you attempt to create an instance
165 with a name that already existed in the users namespace, the module simply returns as "unchanged".
166 - There are two ways to run commands inside a container or virtual machine, using the command module or using the ansible
167 lxd connection plugin bundled in Ansible >= 2.1, the later requires python to be installed in the instance which can be
168 done with the command module.
169 - You can copy a file from the host to the instance with the Ansible M(ansible.builtin.copy) and M(ansible.builtin.template)
170 module and the P(community.general.lxd#connection) connection plugin. See the example below.
171 - You can copy a file in the created instance to the localhost with C(command=lxc file pull instance_name/dir/filename filename).
172 See the first example below.
173 - Linuxcontainers.org has phased out LXC/LXD support with March 2024
174 (U(https://discuss.linuxcontainers.org/t/important-notice-for-lxd-users-image-server/18479)).
175 Currently only Ubuntu is still providing images.
176 """
177
178 EXAMPLES = r"""
179 # An example for creating a Ubuntu container and install python
180 - hosts: localhost
181 connection: local
182 tasks:
183 - name: Create a started container
184 community.general.lxd_container:
185 name: mycontainer
186 ignore_volatile_options: true
187 state: started
188 source:
189 type: image
190 mode: pull
191 server: https://cloud-images.ubuntu.com/releases/
192 protocol: simplestreams
193 alias: "22.04"
194 profiles: ["default"]
195 wait_for_ipv4_addresses: true
196 timeout: 600
197
198 - name: Check python is installed in container
199 delegate_to: mycontainer
200 ansible.builtin.raw: dpkg -s python
201 register: python_install_check
202 failed_when: python_install_check.rc not in [0, 1]
203 changed_when: false
204
205 - name: Install python in container
206 delegate_to: mycontainer
207 ansible.builtin.raw: apt-get install -y python
208 when: python_install_check.rc == 1
209
210 # An example for creating an Ubuntu 14.04 container using an image fingerprint.
211 # This requires changing 'server' and 'protocol' key values, replacing the
212 # 'alias' key with with 'fingerprint' and supplying an appropriate value that
213 # matches the container image you wish to use.
214 - hosts: localhost
215 connection: local
216 tasks:
217 - name: Create a started container
218 community.general.lxd_container:
219 name: mycontainer
220 ignore_volatile_options: true
221 state: started
222 source:
223 type: image
224 mode: pull
225 # Provides current (and older) Ubuntu images with listed fingerprints
226 server: https://cloud-images.ubuntu.com/releases
227 # Protocol used by 'ubuntu' remote (as shown by 'lxc remote list')
228 protocol: simplestreams
229 # This provides an Ubuntu 14.04 LTS amd64 image from 20150814.
230 fingerprint: e9a8bdfab6dc
231 profiles: ["default"]
232 wait_for_ipv4_addresses: true
233 timeout: 600
234
235 # An example of creating a ubuntu-minial container
236 - hosts: localhost
237 connection: local
238 tasks:
239 - name: Create a started container
240 community.general.lxd_container:
241 name: mycontainer
242 ignore_volatile_options: true
243 state: started
244 source:
245 type: image
246 mode: pull
247 # Provides Ubuntu minimal images
248 server: https://cloud-images.ubuntu.com/minimal/releases/
249 protocol: simplestreams
250 alias: "22.04"
251 profiles: ["default"]
252 wait_for_ipv4_addresses: true
253 timeout: 600
254
255 # An example for creating container in project other than default
256 - hosts: localhost
257 connection: local
258 tasks:
259 - name: Create a started container in project mytestproject
260 community.general.lxd_container:
261 name: mycontainer
262 project: mytestproject
263 ignore_volatile_options: true
264 state: started
265 source:
266 protocol: simplestreams
267 type: image
268 mode: pull
269 server: https://cloud-images.ubuntu.com/releases/
270 alias: "22.04"
271 profiles: ["default"]
272 wait_for_ipv4_addresses: true
273 timeout: 600
274
275 # An example for deleting a container
276 - hosts: localhost
277 connection: local
278 tasks:
279 - name: Delete a container
280 community.general.lxd_container:
281 name: mycontainer
282 state: absent
283 type: container
284
285 # An example for restarting a container
286 - hosts: localhost
287 connection: local
288 tasks:
289 - name: Restart a container
290 community.general.lxd_container:
291 name: mycontainer
292 state: restarted
293 type: container
294
295 # An example for restarting a container using https to connect to the LXD server
296 - hosts: localhost
297 connection: local
298 tasks:
299 - name: Restart a container
300 community.general.lxd_container:
301 url: https://127.0.0.1:8443
302 # These client_cert and client_key values are equal to the default values.
303 # client_cert: "{{ lookup('env', 'HOME') }}/.config/lxc/client.crt"
304 # client_key: "{{ lookup('env', 'HOME') }}/.config/lxc/client.key"
305 trust_password: mypassword
306 name: mycontainer
307 state: restarted
308
309 # Note your container must be in the inventory for the below example.
310 #
311 # [containers]
312 # mycontainer ansible_connection=lxd
313 #
314 - hosts:
315 - mycontainer
316 tasks:
317 - name: Copy /etc/hosts in the created container to localhost with name "mycontainer-hosts"
318 ansible.builtin.fetch:
319 src: /etc/hosts
320 dest: /tmp/mycontainer-hosts
321 flat: true
322
323 # An example for LXD cluster deployments. This example will create two new container on specific
324 # nodes - 'node01' and 'node02'. In 'target:', 'node01' and 'node02' are names of LXD cluster
325 # members that LXD cluster recognizes, not ansible inventory names, see: 'lxc cluster list'.
326 # LXD API calls can be made to any LXD member, in this example, we send API requests to
327 # 'node01.example.com', which matches ansible inventory name.
328 - hosts: node01.example.com
329 tasks:
330 - name: Create LXD container
331 community.general.lxd_container:
332 name: new-container-1
333 ignore_volatile_options: true
334 state: started
335 source:
336 type: image
337 mode: pull
338 alias: "22.04"
339 target: node01
340
341 - name: Create container on another node
342 community.general.lxd_container:
343 name: new-container-2
344 ignore_volatile_options: true
345 state: started
346 source:
347 type: image
348 mode: pull
349 alias: "22.04"
350 target: node02
351
352 # An example for creating a virtual machine
353 - hosts: localhost
354 connection: local
355 tasks:
356 - name: Create container on another node
357 community.general.lxd_container:
358 name: new-vm-1
359 type: virtual-machine
360 state: started
361 ignore_volatile_options: true
362 wait_for_ipv4_addresses: true
363 profiles: ["default"]
364 source:
365 protocol: simplestreams
366 type: image
367 mode: pull
368 server: ['...'] # URL to the image server
369 alias: debian/11
370 timeout: 600
371 """
372
373 RETURN = r"""
374 addresses:
375 description: Mapping from the network device name to a list of IPv4 addresses in the instance.
376 returned: when state is started or restarted
377 type: dict
378 sample:
379 {
380 "eth0": [
381 "10.155.92.191"
382 ]
383 }
384 old_state:
385 description: The old state of the instance.
386 returned: when state is started or restarted
387 type: str
388 sample: "stopped"
389 logs:
390 description: The logs of requests and responses.
391 returned: when ansible-playbook is invoked with -vvvv.
392 type: list
393 sample: "(too long to be placed here)"
394 actions:
395 description: List of actions performed for the instance.
396 returned: success
397 type: list
398 sample: ["create", "start"]
399 """
400
401 import copy
402 import datetime
403 import os
404 import time
405 from urllib.parse import urlencode
406
407 from ansible.module_utils.basic import AnsibleModule
408
409 from ansible_collections.community.general.plugins.module_utils._lxd import LXDClient, LXDClientException
410
411 # LXD_ANSIBLE_STATES is a map of states that contain values of methods used
412 # when a particular state is evoked.
413 LXD_ANSIBLE_STATES = {
414 "started": "_started",
415 "stopped": "_stopped",
416 "restarted": "_restarted",
417 "absent": "_destroyed",
418 "frozen": "_frozen",
419 }
420
421 # ANSIBLE_LXD_STATES is a map of states of lxd containers to the Ansible
422 # lxc_container module state parameter value.
423 ANSIBLE_LXD_STATES = {
424 "Running": "started",
425 "Stopped": "stopped",
426 "Frozen": "frozen",
427 }
428
429 # ANSIBLE_LXD_DEFAULT_URL is a default value of the lxd endpoint
430 ANSIBLE_LXD_DEFAULT_URL = "unix:/var/lib/lxd/unix.socket"
431
432 # CONFIG_PARAMS is a list of config attribute names.
433 CONFIG_PARAMS = ["architecture", "config", "devices", "ephemeral", "profiles", "source", "type"]
434
435 # CONFIG_CREATION_PARAMS is a list of attribute names that are only applied
436 # on instance creation.
437 CONFIG_CREATION_PARAMS = ["source", "type"]
438
439
440 class LXDContainerManagement:
441 def __init__(self, module):
442 """Management of LXC containers via Ansible.
443
444 :param module: Processed Ansible Module.
445 :type module: ``object``
446 """
447 self.module = module
448 self.name = self.module.params["name"]
449 self.project = self.module.params["project"]
450 self._build_config()
451
452 self.state = self.module.params["state"]
453
454 self.timeout = self.module.params["timeout"]
455 self.wait_for_ipv4_addresses = self.module.params["wait_for_ipv4_addresses"]
456 self.force_stop = self.module.params["force_stop"]
457 self.addresses = None
458 self.target = self.module.params["target"]
459 self.wait_for_container = self.module.params["wait_for_container"]
460
461 self.type = self.module.params["type"]
462
463 self.key_file = self.module.params.get("client_key")
464 if self.key_file is None:
465 self.key_file = f"{os.environ['HOME']}/.config/lxc/client.key"
466 self.cert_file = self.module.params.get("client_cert")
467 if self.cert_file is None:
468 self.cert_file = f"{os.environ['HOME']}/.config/lxc/client.crt"
469 self.debug = self.module._verbosity >= 4
470
471 try:
472 if self.module.params["url"] != ANSIBLE_LXD_DEFAULT_URL:
473 self.url = self.module.params["url"]
474 elif os.path.exists(self.module.params["snap_url"].replace("unix:", "")):
475 self.url = self.module.params["snap_url"]
476 else:
477 self.url = self.module.params["url"]
478 except Exception as e:
479 self.module.fail_json(msg=e.msg)
480
481 try:
482 self.client = LXDClient(self.url, key_file=self.key_file, cert_file=self.cert_file, debug=self.debug)
483 except LXDClientException as e:
484 self.module.fail_json(msg=e.msg)
485
486 # LXD (3.19) Rest API provides instances endpoint, failback to containers and virtual-machines
487 # https://documentation.ubuntu.com/lxd/en/latest/rest-api/#instances-containers-and-virtual-machines
488 self.api_endpoint = "/1.0/instances"
489 check_api_endpoint = self.client.do("GET", f"{self.api_endpoint}?project=", ok_error_codes=[404])
490
491 if check_api_endpoint["error_code"] == 404:
492 if self.type == "container":
493 self.api_endpoint = "/1.0/containers"
494 elif self.type == "virtual-machine":
495 self.api_endpoint = "/1.0/virtual-machines"
496
497 self.trust_password = self.module.params.get("trust_password", None)
498 self.actions = []
499 self.diff = {"before": {}, "after": {}}
500 self.old_instance_json = {}
501 self.old_sections = {}
502
503 def _build_config(self):
504 self.config = {}
505 for attr in CONFIG_PARAMS:
506 param_val = self.module.params.get(attr, None)
507 if param_val is not None:
508 self.config[attr] = param_val
509
510 def _get_instance_json(self):
511 url = f"{self.api_endpoint}/{self.name}"
512 if self.project:
513 url = f"{url}?{urlencode(dict(project=self.project))}"
514 return self.client.do("GET", url, ok_error_codes=[404])
515
516 def _get_instance_state_json(self):
517 url = f"{self.api_endpoint}/{self.name}/state"
518 if self.project:
519 url = f"{url}?{urlencode(dict(project=self.project))}"
520 return self.client.do("GET", url, ok_error_codes=[404])
521
522 @staticmethod
523 def _instance_json_to_module_state(resp_json):
524 if resp_json["type"] == "error":
525 return "absent"
526 return ANSIBLE_LXD_STATES[resp_json["metadata"]["status"]]
527
528 def _change_state(self, action, force_stop=False):
529 url = f"{self.api_endpoint}/{self.name}/state"
530 if self.project:
531 url = f"{url}?{urlencode(dict(project=self.project))}"
532 body_json = {"action": action, "timeout": self.timeout}
533 if force_stop:
534 body_json["force"] = True
535 if not self.module.check_mode:
536 return self.client.do("PUT", url, body_json=body_json)
537
538 def _create_instance(self):
539 url = self.api_endpoint
540 url_params = dict()
541 if self.target:
542 url_params["target"] = self.target
543 if self.project:
544 url_params["project"] = self.project
545 if url_params:
546 url = f"{url}?{urlencode(url_params)}"
547 config = self.config.copy()
548 config["name"] = self.name
549 if self.type not in self.api_endpoint:
550 config["type"] = self.type
551 if not self.module.check_mode:
552 self.client.do("POST", url, config, wait_for_container=self.wait_for_container)
553 self.actions.append("create")
554
555 def _start_instance(self):
556 self._change_state("start")
557 self.actions.append("start")
558
559 def _stop_instance(self):
560 self._change_state("stop", self.force_stop)
561 self.actions.append("stop")
562
563 def _restart_instance(self):
564 self._change_state("restart", self.force_stop)
565 self.actions.append("restart")
566
567 def _delete_instance(self):
568 url = f"{self.api_endpoint}/{self.name}"
569 if self.project:
570 url = f"{url}?{urlencode(dict(project=self.project))}"
571 if not self.module.check_mode:
572 self.client.do("DELETE", url)
573 self.actions.append("delete")
574
575 def _freeze_instance(self):
576 self._change_state("freeze")
577 self.actions.append("freeze")
578
579 def _unfreeze_instance(self):
580 self._change_state("unfreeze")
581 self.actions.append("unfreeze")
582
583 def _instance_ipv4_addresses(self, ignore_devices=None):
584 ignore_devices = ["lo"] if ignore_devices is None else ignore_devices
585 data = (self._get_instance_state_json() or {}).get("metadata", None) or {}
586 network = {k: v for k, v in (data.get("network") or {}).items() if k not in ignore_devices}
587 addresses = {k: [a["address"] for a in v["addresses"] if a["family"] == "inet"] for k, v in network.items()}
588 return addresses
589
590 @staticmethod
591 def _has_all_ipv4_addresses(addresses):
592 return len(addresses) > 0 and all(len(v) > 0 for v in addresses.values())
593
594 def _get_addresses(self):
595 try:
596 due = datetime.datetime.now() + datetime.timedelta(seconds=self.timeout)
597 while datetime.datetime.now() < due:
598 time.sleep(1)
599 addresses = self._instance_ipv4_addresses()
600 if self._has_all_ipv4_addresses(addresses) or self.module.check_mode:
601 self.addresses = addresses
602 return
603 except LXDClientException as e:
604 e.msg = "timeout for getting IPv4 addresses"
605 raise
606
607 def _started(self):
608 if self.old_state == "absent":
609 self._create_instance()
610 self._start_instance()
611 else:
612 if self.old_state == "frozen":
613 self._unfreeze_instance()
614 elif self.old_state == "stopped":
615 self._start_instance()
616 if self._needs_to_apply_instance_configs():
617 self._apply_instance_configs()
618 if self.wait_for_ipv4_addresses:
619 self._get_addresses()
620
621 def _stopped(self):
622 if self.old_state == "absent":
623 self._create_instance()
624 else:
625 if self.old_state == "stopped":
626 if self._needs_to_apply_instance_configs():
627 self._start_instance()
628 self._apply_instance_configs()
629 self._stop_instance()
630 else:
631 if self.old_state == "frozen":
632 self._unfreeze_instance()
633 if self._needs_to_apply_instance_configs():
634 self._apply_instance_configs()
635 self._stop_instance()
636
637 def _restarted(self):
638 if self.old_state == "absent":
639 self._create_instance()
640 self._start_instance()
641 else:
642 if self.old_state == "frozen":
643 self._unfreeze_instance()
644 if self._needs_to_apply_instance_configs():
645 self._apply_instance_configs()
646 self._restart_instance()
647 if self.wait_for_ipv4_addresses:
648 self._get_addresses()
649
650 def _destroyed(self):
651 if self.old_state != "absent":
652 if self.old_state == "frozen":
653 self._unfreeze_instance()
654 if self.old_state != "stopped":
655 self._stop_instance()
656 self._delete_instance()
657
658 def _frozen(self):
659 if self.old_state == "absent":
660 self._create_instance()
661 self._start_instance()
662 self._freeze_instance()
663 else:
664 if self.old_state == "stopped":
665 self._start_instance()
666 if self._needs_to_apply_instance_configs():
667 self._apply_instance_configs()
668 self._freeze_instance()
669
670 def _needs_to_change_instance_config(self, key):
671 if key not in self.config:
672 return False
673
674 if key == "config":
675 # self.old_sections is already filtered for volatile keys if necessary
676 old_configs = dict(self.old_sections.get(key, None) or {})
677 for k, v in self.config["config"].items():
678 if k not in old_configs:
679 return True
680 if old_configs[k] != v:
681 return True
682 return False
683 else:
684 old_configs = self.old_sections.get(key, {})
685 return self.config[key] != old_configs
686
687 def _needs_to_apply_instance_configs(self):
688 return any(
689 self._needs_to_change_instance_config(param) for param in set(CONFIG_PARAMS) - set(CONFIG_CREATION_PARAMS)
690 )
691
692 def _apply_instance_configs(self):
693 old_metadata = copy.deepcopy(self.old_instance_json).get("metadata", None) or {}
694 body_json = {}
695 for param in set(CONFIG_PARAMS) - set(CONFIG_CREATION_PARAMS):
696 if param in old_metadata:
697 body_json[param] = old_metadata[param]
698
699 if self._needs_to_change_instance_config(param):
700 if param == "config":
701 body_json["config"] = body_json.get("config") or {}
702 for k, v in self.config["config"].items():
703 body_json["config"][k] = v
704 else:
705 body_json[param] = self.config[param]
706 self.diff["after"]["instance"] = body_json
707 url = f"{self.api_endpoint}/{self.name}"
708 if self.project:
709 url = f"{url}?{urlencode(dict(project=self.project))}"
710 if not self.module.check_mode:
711 self.client.do("PUT", url, body_json=body_json)
712 self.actions.append("apply_instance_configs")
713
714 def run(self):
715 """Run the main method."""
716
717 def adjust_content(content):
718 return (
719 content
720 if not isinstance(content, dict)
721 else {
722 k: v for k, v in content.items() if not (self.ignore_volatile_options and k.startswith("volatile."))
723 }
724 )
725
726 try:
727 if self.trust_password is not None:
728 self.client.authenticate(self.trust_password)
729 self.ignore_volatile_options = self.module.params.get("ignore_volatile_options")
730
731 self.old_instance_json = self._get_instance_json()
732 self.old_sections = {
733 section: adjust_content(content)
734 for section, content in (self.old_instance_json.get("metadata") or {}).items()
735 if section in set(CONFIG_PARAMS) - set(CONFIG_CREATION_PARAMS)
736 }
737
738 self.diff["before"]["instance"] = self.old_sections
739 # preliminary, will be overwritten in _apply_instance_configs() if called
740 self.diff["after"]["instance"] = self.config
741
742 self.old_state = self._instance_json_to_module_state(self.old_instance_json)
743 self.diff["before"]["state"] = self.old_state
744 self.diff["after"]["state"] = self.state
745
746 action = getattr(self, LXD_ANSIBLE_STATES[self.state])
747 action()
748
749 state_changed = len(self.actions) > 0
750 result_json = {
751 "log_verbosity": self.module._verbosity,
752 "changed": state_changed,
753 "old_state": self.old_state,
754 "actions": self.actions,
755 "diff": self.diff,
756 }
757 if self.client.debug:
758 result_json["logs"] = self.client.logs
759 if self.addresses is not None:
760 result_json["addresses"] = self.addresses
761 self.module.exit_json(**result_json)
762 except LXDClientException as e:
763 state_changed = len(self.actions) > 0
764 fail_params = {
765 "msg": e.msg,
766 "changed": state_changed,
767 "actions": self.actions,
768 "diff": self.diff,
769 }
770 if self.client.debug:
771 fail_params["logs"] = e.kwargs["logs"]
772 self.module.fail_json(**fail_params)
773
774
775 def main():
776 """Ansible Main module."""
777
778 module = AnsibleModule(
779 argument_spec=dict(
780 name=dict(
781 type="str",
782 required=True,
783 ),
784 project=dict(
785 type="str",
786 ),
787 architecture=dict(
788 type="str",
789 ),
790 config=dict(
791 type="dict",
792 ),
793 ignore_volatile_options=dict(
794 type="bool",
795 default=False,
796 ),
797 devices=dict(
798 type="dict",
799 ),
800 ephemeral=dict(
801 type="bool",
802 ),
803 profiles=dict(
804 type="list",
805 elements="str",
806 ),
807 source=dict(
808 type="dict",
809 ),
810 state=dict(
811 choices=list(LXD_ANSIBLE_STATES.keys()),
812 default="started",
813 ),
814 target=dict(
815 type="str",
816 ),
817 timeout=dict(type="int", default=30),
818 type=dict(
819 type="str",
820 default="container",
821 choices=["container", "virtual-machine"],
822 ),
823 wait_for_container=dict(
824 type="bool",
825 default=False,
826 ),
827 wait_for_ipv4_addresses=dict(
828 type="bool",
829 default=False,
830 ),
831 force_stop=dict(
832 type="bool",
833 default=False,
834 ),
835 url=dict(
836 type="str",
837 default=ANSIBLE_LXD_DEFAULT_URL,
838 ),
839 snap_url=dict(
840 type="str",
841 default="unix:/var/snap/lxd/common/lxd/unix.socket",
842 ),
843 client_key=dict(
844 type="path",
845 aliases=["key_file"],
846 ),
847 client_cert=dict(
848 type="path",
849 aliases=["cert_file"],
850 ),
851 trust_password=dict(type="str", no_log=True),
852 ),
853 supports_check_mode=True,
854 )
855
856 lxd_manage = LXDContainerManagement(module=module)
857 lxd_manage.run()
858
859
860 if __name__ == "__main__":
861 main()