Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2016, Hiroaki Nakamura <[email protected]>
4 # Copyright (c) 2020, Frank Dornheim <[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 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: lxd_profile
12 short_description: Manage LXD profiles
13 description:
14 - Management of LXD profiles.
15 author: "Hiroaki Nakamura (@hnakamur)"
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: none
21 diff_mode:
22 support: none
23 options:
24 name:
25 description:
26 - Name of a profile.
27 required: true
28 type: str
29 project:
30 description:
31 - Project of a profile. See U(https://documentation.ubuntu.com/lxd/en/latest/projects/).
32 type: str
33 version_added: 4.8.0
34 description:
35 description:
36 - Description of the profile.
37 type: str
38 config:
39 description:
40 - 'The config for the instance (for example V({"limits.memory": "4GB"})).'
41 - See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/profiles/profile_get).
42 - If the profile already exists and its C(config) value in metadata obtained from GET /1.0/profiles/<name>
43 U(https://documentation.ubuntu.com/lxd/en/latest/api/#/profiles/profile_get)
44 are different, then this module tries to apply the configurations U(https://documentation.ubuntu.com/lxd/en/latest/api/#/profiles/profile_put).
45 - Not all config values are supported to apply the existing profile. Maybe you need to delete and recreate a profile.
46 type: dict
47 devices:
48 description:
49 - 'The devices for the profile (for example V({"rootfs": {"path": "/dev/kvm", "type": "unix-char"})).'
50 - See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/profiles/profile_get).
51 type: dict
52 new_name:
53 description:
54 - A new name of a profile.
55 - If this parameter is specified a profile is renamed to this name.
56 - See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/profiles/profile_post).
57 type: str
58 merge_profile:
59 description:
60 - Merge the configuration of the present profile with the new desired configuration, instead of replacing it.
61 default: false
62 type: bool
63 version_added: 2.1.0
64 state:
65 choices:
66 - present
67 - absent
68 description:
69 - Define the state of a profile.
70 default: present
71 type: str
72 url:
73 description:
74 - The unix domain socket path or the https URL for the LXD server.
75 default: unix:/var/lib/lxd/unix.socket
76 type: str
77 snap_url:
78 description:
79 - The unix domain socket path when LXD is installed by snap package manager.
80 default: unix:/var/snap/lxd/common/lxd/unix.socket
81 type: str
82 client_key:
83 description:
84 - The client certificate key file path.
85 - If not specified, it defaults to C($HOME/.config/lxc/client.key).
86 aliases: [key_file]
87 type: path
88 client_cert:
89 description:
90 - The client certificate file path.
91 - If not specified, it defaults to C($HOME/.config/lxc/client.crt).
92 aliases: [cert_file]
93 type: path
94 trust_password:
95 description:
96 - The client trusted password.
97 - 'You need to set this password on the LXD server before running this module using the following command: C(lxc config
98 set core.trust_password <some random password>). See U(https://www.stgraber.org/2016/04/18/lxd-api-direct-interaction/).'
99 - If O(trust_password) is set, this module send a request for authentication before sending any requests.
100 type: str
101 notes:
102 - Profiles must have a unique name. If you attempt to create a profile with a name that already existed in the users namespace
103 the module simply returns as "unchanged".
104 """
105
106 EXAMPLES = r"""
107 # An example for creating a profile
108 - hosts: localhost
109 connection: local
110 tasks:
111 - name: Create a profile
112 community.general.lxd_profile:
113 name: macvlan
114 state: present
115 config: {}
116 description: my macvlan profile
117 devices:
118 eth0:
119 nictype: macvlan
120 parent: br0
121 type: nic
122
123 # An example for creating a profile in project mytestproject
124 - hosts: localhost
125 connection: local
126 tasks:
127 - name: Create a profile
128 community.general.lxd_profile:
129 name: testprofile
130 project: mytestproject
131 state: present
132 config: {}
133 description: test profile in project mytestproject
134 devices: {}
135
136 # An example for creating a profile via http connection
137 - hosts: localhost
138 connection: local
139 tasks:
140 - name: Create macvlan profile
141 community.general.lxd_profile:
142 url: https://127.0.0.1:8443
143 # These client_cert and client_key values are equal to the default values.
144 # client_cert: "{{ lookup('env', 'HOME') }}/.config/lxc/client.crt"
145 # client_key: "{{ lookup('env', 'HOME') }}/.config/lxc/client.key"
146 trust_password: mypassword
147 name: macvlan
148 state: present
149 config: {}
150 description: my macvlan profile
151 devices:
152 eth0:
153 nictype: macvlan
154 parent: br0
155 type: nic
156
157 # An example for modify/merge a profile
158 - hosts: localhost
159 connection: local
160 tasks:
161 - name: Merge a profile
162 community.general.lxd_profile:
163 merge_profile: true
164 name: macvlan
165 state: present
166 config: {}
167 description: my macvlan profile
168 devices:
169 eth0:
170 nictype: macvlan
171 parent: br0
172 type: nic
173
174 # An example for deleting a profile
175 - hosts: localhost
176 connection: local
177 tasks:
178 - name: Delete a profile
179 community.general.lxd_profile:
180 name: macvlan
181 state: absent
182
183 # An example for renaming a profile
184 - hosts: localhost
185 connection: local
186 tasks:
187 - name: Rename a profile
188 community.general.lxd_profile:
189 name: macvlan
190 new_name: macvlan2
191 state: present
192 """
193
194 RETURN = r"""
195 old_state:
196 description: The old state of the profile.
197 returned: success
198 type: str
199 sample: "absent"
200 logs:
201 description: The logs of requests and responses.
202 returned: when ansible-playbook is invoked with -vvvv.
203 type: list
204 sample: "(too long to be placed here)"
205 actions:
206 description: List of actions performed for the profile.
207 returned: success
208 type: list
209 sample: ["create"]
210 """
211
212 import os
213 from urllib.parse import urlencode
214
215 from ansible.module_utils.basic import AnsibleModule
216
217 from ansible_collections.community.general.plugins.module_utils._lxd import LXDClient, LXDClientException
218
219 # ANSIBLE_LXD_DEFAULT_URL is a default value of the lxd endpoint
220 ANSIBLE_LXD_DEFAULT_URL = "unix:/var/lib/lxd/unix.socket"
221
222 # PROFILE_STATES is a list for states supported
223 PROFILES_STATES = ["present", "absent"]
224
225 # CONFIG_PARAMS is a list of config attribute names.
226 CONFIG_PARAMS = ["config", "description", "devices"]
227
228
229 class LXDProfileManagement:
230 def __init__(self, module):
231 """Management of LXC profiles via Ansible.
232
233 :param module: Processed Ansible Module.
234 :type module: ``object``
235 """
236 self.module = module
237 self.name = self.module.params["name"]
238 self.project = self.module.params["project"]
239 self._build_config()
240 self.state = self.module.params["state"]
241 self.new_name = self.module.params.get("new_name", None)
242
243 self.key_file = self.module.params.get("client_key")
244 if self.key_file is None:
245 self.key_file = f"{os.environ['HOME']}/.config/lxc/client.key"
246 self.cert_file = self.module.params.get("client_cert")
247 if self.cert_file is None:
248 self.cert_file = f"{os.environ['HOME']}/.config/lxc/client.crt"
249 self.debug = self.module._verbosity >= 4
250
251 try:
252 if self.module.params["url"] != ANSIBLE_LXD_DEFAULT_URL:
253 self.url = self.module.params["url"]
254 elif os.path.exists(self.module.params["snap_url"].replace("unix:", "")):
255 self.url = self.module.params["snap_url"]
256 else:
257 self.url = self.module.params["url"]
258 except Exception as e:
259 self.module.fail_json(msg=e.msg)
260
261 try:
262 self.client = LXDClient(self.url, key_file=self.key_file, cert_file=self.cert_file, debug=self.debug)
263 except LXDClientException as e:
264 self.module.fail_json(msg=e.msg)
265 self.trust_password = self.module.params.get("trust_password", None)
266 self.actions = []
267
268 def _build_config(self):
269 self.config = {}
270 for attr in CONFIG_PARAMS:
271 param_val = self.module.params.get(attr, None)
272 if param_val is not None:
273 self.config[attr] = param_val
274
275 def _get_profile_json(self):
276 url = f"/1.0/profiles/{self.name}"
277 if self.project:
278 url = f"{url}?{urlencode(dict(project=self.project))}"
279 return self.client.do("GET", url, ok_error_codes=[404])
280
281 @staticmethod
282 def _profile_json_to_module_state(resp_json):
283 if resp_json["type"] == "error":
284 return "absent"
285 return "present"
286
287 def _update_profile(self):
288 if self.state == "present":
289 if self.old_state == "absent":
290 if self.new_name is None:
291 self._create_profile()
292 else:
293 self.module.fail_json(
294 msg="new_name must not be set when the profile does not exist and the state is present",
295 changed=False,
296 )
297 else:
298 if self.new_name is not None and self.new_name != self.name:
299 self._rename_profile()
300 if self._needs_to_apply_profile_configs():
301 self._apply_profile_configs()
302 elif self.state == "absent":
303 if self.old_state == "present":
304 if self.new_name is None:
305 self._delete_profile()
306 else:
307 self.module.fail_json(
308 msg="new_name must not be set when the profile exists and the specified state is absent",
309 changed=False,
310 )
311
312 def _create_profile(self):
313 url = "/1.0/profiles"
314 if self.project:
315 url = f"{url}?{urlencode(dict(project=self.project))}"
316 config = self.config.copy()
317 config["name"] = self.name
318 self.client.do("POST", url, config)
319 self.actions.append("create")
320
321 def _rename_profile(self):
322 url = f"/1.0/profiles/{self.name}"
323 if self.project:
324 url = f"{url}?{urlencode(dict(project=self.project))}"
325 config = {"name": self.new_name}
326 self.client.do("POST", url, config)
327 self.actions.append("rename")
328 self.name = self.new_name
329
330 def _needs_to_change_profile_config(self, key):
331 if key not in self.config:
332 return False
333 old_configs = self.old_profile_json["metadata"].get(key, None)
334 return self.config[key] != old_configs
335
336 def _needs_to_apply_profile_configs(self):
337 return (
338 self._needs_to_change_profile_config("config")
339 or self._needs_to_change_profile_config("description")
340 or self._needs_to_change_profile_config("devices")
341 )
342
343 def _merge_dicts(self, source, destination):
344 """Merge Dictionaries
345
346 Get a list of filehandle numbers from logger to be handed to
347 DaemonContext.files_preserve
348
349 Args:
350 dict(source): source dict
351 dict(destination): destination dict
352 Kwargs:
353 None
354 Raises:
355 None
356 Returns:
357 dict(destination): merged dict"""
358 for key, value in source.items():
359 if isinstance(value, dict):
360 # get node or create one
361 node = destination.setdefault(key, {})
362 self._merge_dicts(value, node)
363 else:
364 destination[key] = value
365 return destination
366
367 def _merge_config(self, config):
368 """merge profile
369
370 Merge Configuration of the present profile and the new desired configitems
371
372 Args:
373 dict(config): Dict with the old config in 'metadata' and new config in 'config'
374 Kwargs:
375 None
376 Raises:
377 None
378 Returns:
379 dict(config): new config"""
380 # merge or copy the sections from the existing profile to 'config'
381 for item in ["config", "description", "devices", "name", "used_by"]:
382 if item in config:
383 config[item] = self._merge_dicts(config["metadata"][item], config[item])
384 else:
385 config[item] = config["metadata"][item]
386 # merge or copy the sections from the ansible-task to 'config'
387 return self._merge_dicts(self.config, config)
388
389 def _generate_new_config(self, config):
390 """rebuild profile
391
392 Rebuild the Profile by the configuration provided in the play.
393 Existing configurations are discarded.
394
395 This is the default behavior.
396
397 Args:
398 dict(config): Dict with the old config in 'metadata' and new config in 'config'
399 Kwargs:
400 None
401 Raises:
402 None
403 Returns:
404 dict(config): new config"""
405 for k, v in self.config.items():
406 config[k] = v
407 return config
408
409 def _apply_profile_configs(self):
410 """Selection of the procedure: rebuild or merge
411
412 The standard behavior is that all information not contained
413 in the play is discarded.
414
415 If "merge_profile" is provides in the play and "True", then existing
416 configurations from the profile and new ones defined are merged.
417
418 Args:
419 None
420 Kwargs:
421 None
422 Raises:
423 None
424 Returns:
425 None"""
426 config = self.old_profile_json.copy()
427 if self.module.params["merge_profile"]:
428 config = self._merge_config(config)
429 else:
430 config = self._generate_new_config(config)
431
432 # upload config to lxd
433 url = f"/1.0/profiles/{self.name}"
434 if self.project:
435 url = f"{url}?{urlencode(dict(project=self.project))}"
436 self.client.do("PUT", url, config)
437 self.actions.append("apply_profile_configs")
438
439 def _delete_profile(self):
440 url = f"/1.0/profiles/{self.name}"
441 if self.project:
442 url = f"{url}?{urlencode(dict(project=self.project))}"
443 self.client.do("DELETE", url)
444 self.actions.append("delete")
445
446 def run(self):
447 """Run the main method."""
448
449 try:
450 if self.trust_password is not None:
451 self.client.authenticate(self.trust_password)
452
453 self.old_profile_json = self._get_profile_json()
454 self.old_state = self._profile_json_to_module_state(self.old_profile_json)
455 self._update_profile()
456
457 state_changed = len(self.actions) > 0
458 result_json = {"changed": state_changed, "old_state": self.old_state, "actions": self.actions}
459 if self.client.debug:
460 result_json["logs"] = self.client.logs
461 self.module.exit_json(**result_json)
462 except LXDClientException as e:
463 state_changed = len(self.actions) > 0
464 fail_params = {"msg": e.msg, "changed": state_changed, "actions": self.actions}
465 if self.client.debug:
466 fail_params["logs"] = e.kwargs["logs"]
467 self.module.fail_json(**fail_params)
468
469
470 def main():
471 """Ansible Main module."""
472
473 module = AnsibleModule(
474 argument_spec=dict(
475 name=dict(type="str", required=True),
476 project=dict(
477 type="str",
478 ),
479 new_name=dict(
480 type="str",
481 ),
482 config=dict(
483 type="dict",
484 ),
485 description=dict(
486 type="str",
487 ),
488 devices=dict(
489 type="dict",
490 ),
491 merge_profile=dict(type="bool", default=False),
492 state=dict(choices=PROFILES_STATES, default="present"),
493 url=dict(type="str", default=ANSIBLE_LXD_DEFAULT_URL),
494 snap_url=dict(type="str", default="unix:/var/snap/lxd/common/lxd/unix.socket"),
495 client_key=dict(type="path", aliases=["key_file"]),
496 client_cert=dict(type="path", aliases=["cert_file"]),
497 trust_password=dict(type="str", no_log=True),
498 ),
499 supports_check_mode=False,
500 )
501
502 lxd_manage = LXDProfileManagement(module=module)
503 lxd_manage.run()
504
505
506 if __name__ == "__main__":
507 main()