| 1 |
#!/usr/bin/python |
| 2 |
# Copyright (c) Ansible project |
| 3 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 4 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 5 |
|
| 6 |
from __future__ import annotations |
| 7 |
|
| 8 |
DOCUMENTATION = r""" |
| 9 |
module: lxd_project |
| 10 |
short_description: Manage LXD projects |
| 11 |
version_added: 4.8.0 |
| 12 |
description: |
| 13 |
- Management of LXD projects. |
| 14 |
author: "Raymond Chang (@we10710aa)" |
| 15 |
extends_documentation_fragment: |
| 16 |
- community.general._attributes |
| 17 |
attributes: |
| 18 |
check_mode: |
| 19 |
support: none |
| 20 |
diff_mode: |
| 21 |
support: none |
| 22 |
options: |
| 23 |
name: |
| 24 |
description: |
| 25 |
- Name of the project. |
| 26 |
required: true |
| 27 |
type: str |
| 28 |
description: |
| 29 |
description: |
| 30 |
- Description of the project. |
| 31 |
type: str |
| 32 |
config: |
| 33 |
description: |
| 34 |
- 'The config for the project (for example V({"features.profiles": "true"})).' |
| 35 |
- See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/projects/project_get). |
| 36 |
- If the project already exists and its "config" value in metadata obtained from C(GET /1.0/projects/<name>) |
| 37 |
U(https://documentation.ubuntu.com/lxd/en/latest/api/#/projects/project_get) |
| 38 |
are different, then this module tries to apply the configurations U(https://documentation.ubuntu.com/lxd/en/latest/api/#/projects/project_put). |
| 39 |
type: dict |
| 40 |
new_name: |
| 41 |
description: |
| 42 |
- A new name of a project. |
| 43 |
- If this parameter is specified a project is renamed to this name. |
| 44 |
- See U(https://documentation.ubuntu.com/lxd/en/latest/api/#/projects/project_post). |
| 45 |
type: str |
| 46 |
merge_project: |
| 47 |
description: |
| 48 |
- Merge the configuration of the present project with the new desired configuration, instead of replacing it. If configuration |
| 49 |
is the same after merged, no change is made. |
| 50 |
default: false |
| 51 |
type: bool |
| 52 |
state: |
| 53 |
choices: |
| 54 |
- present |
| 55 |
- absent |
| 56 |
description: |
| 57 |
- Define the state of a project. |
| 58 |
default: present |
| 59 |
type: str |
| 60 |
url: |
| 61 |
description: |
| 62 |
- The Unix domain socket path or the https URL for the LXD server. |
| 63 |
default: unix:/var/lib/lxd/unix.socket |
| 64 |
type: str |
| 65 |
snap_url: |
| 66 |
description: |
| 67 |
- The Unix domain socket path when LXD is installed by snap package manager. |
| 68 |
default: unix:/var/snap/lxd/common/lxd/unix.socket |
| 69 |
type: str |
| 70 |
client_key: |
| 71 |
description: |
| 72 |
- The client certificate key file path. |
| 73 |
- If not specified, it defaults to C($HOME/.config/lxc/client.key). |
| 74 |
aliases: [key_file] |
| 75 |
type: path |
| 76 |
client_cert: |
| 77 |
description: |
| 78 |
- The client certificate file path. |
| 79 |
- If not specified, it defaults to C($HOME/.config/lxc/client.crt). |
| 80 |
aliases: [cert_file] |
| 81 |
type: path |
| 82 |
trust_password: |
| 83 |
description: |
| 84 |
- The client trusted password. |
| 85 |
- 'You need to set this password on the LXD server before running this module using the following command: C(lxc config |
| 86 |
set core.trust_password <some random password>) See U(https://www.stgraber.org/2016/04/18/lxd-api-direct-interaction/).' |
| 87 |
- If O(trust_password) is set, this module send a request for authentication before sending any requests. |
| 88 |
type: str |
| 89 |
notes: |
| 90 |
- Projects must have a unique name. If you attempt to create a project with a name that already existed in the users namespace |
| 91 |
the module simply returns as "unchanged". |
| 92 |
""" |
| 93 |
|
| 94 |
EXAMPLES = r""" |
| 95 |
# An example for creating a project |
| 96 |
- hosts: localhost |
| 97 |
connection: local |
| 98 |
tasks: |
| 99 |
- name: Create a project |
| 100 |
community.general.lxd_project: |
| 101 |
name: ansible-test-project |
| 102 |
state: present |
| 103 |
config: {} |
| 104 |
description: my new project |
| 105 |
|
| 106 |
# An example for renaming a project |
| 107 |
- hosts: localhost |
| 108 |
connection: local |
| 109 |
tasks: |
| 110 |
- name: Rename ansible-test-project to ansible-test-project-new-name |
| 111 |
community.general.lxd_project: |
| 112 |
name: ansible-test-project |
| 113 |
new_name: ansible-test-project-new-name |
| 114 |
state: present |
| 115 |
config: {} |
| 116 |
description: my new project |
| 117 |
""" |
| 118 |
|
| 119 |
RETURN = r""" |
| 120 |
old_state: |
| 121 |
description: The old state of the project. |
| 122 |
returned: success |
| 123 |
type: str |
| 124 |
sample: "absent" |
| 125 |
logs: |
| 126 |
description: The logs of requests and responses. |
| 127 |
returned: when ansible-playbook is invoked with -vvvv. |
| 128 |
type: list |
| 129 |
elements: dict |
| 130 |
contains: |
| 131 |
type: |
| 132 |
description: Type of actions performed, currently only V(sent request). |
| 133 |
type: str |
| 134 |
sample: "sent request" |
| 135 |
request: |
| 136 |
description: HTTP request sent to LXD server. |
| 137 |
type: dict |
| 138 |
contains: |
| 139 |
method: |
| 140 |
description: Method of HTTP request. |
| 141 |
type: str |
| 142 |
sample: "GET" |
| 143 |
url: |
| 144 |
description: URL path of HTTP request. |
| 145 |
type: str |
| 146 |
sample: "/1.0/projects/test-project" |
| 147 |
json: |
| 148 |
description: JSON body of HTTP request. |
| 149 |
type: str |
| 150 |
sample: "(too long to be placed here)" |
| 151 |
timeout: |
| 152 |
description: Timeout of HTTP request, V(null) if unset. |
| 153 |
type: int |
| 154 |
sample: null |
| 155 |
response: |
| 156 |
description: HTTP response received from LXD server. |
| 157 |
type: dict |
| 158 |
contains: |
| 159 |
json: |
| 160 |
description: JSON of HTTP response. |
| 161 |
type: str |
| 162 |
sample: "(too long to be placed here)" |
| 163 |
actions: |
| 164 |
description: List of actions performed for the project. |
| 165 |
returned: success |
| 166 |
type: list |
| 167 |
elements: str |
| 168 |
sample: ["create"] |
| 169 |
""" |
| 170 |
|
| 171 |
import os |
| 172 |
|
| 173 |
from ansible.module_utils.basic import AnsibleModule |
| 174 |
|
| 175 |
from ansible_collections.community.general.plugins.module_utils._lxd import ( |
| 176 |
LXDClient, |
| 177 |
LXDClientException, |
| 178 |
default_cert_file, |
| 179 |
default_key_file, |
| 180 |
) |
| 181 |
|
| 182 |
# ANSIBLE_LXD_DEFAULT_URL is a default value of the lxd endpoint |
| 183 |
ANSIBLE_LXD_DEFAULT_URL = "unix:/var/lib/lxd/unix.socket" |
| 184 |
|
| 185 |
# PROJECTS_STATES is a list for states supported |
| 186 |
PROJECTS_STATES = ["present", "absent"] |
| 187 |
|
| 188 |
# CONFIG_PARAMS is a list of config attribute names. |
| 189 |
CONFIG_PARAMS = ["config", "description"] |
| 190 |
|
| 191 |
|
| 192 |
class LXDProjectManagement: |
| 193 |
def __init__(self, module): |
| 194 |
"""Management of LXC projects via Ansible. |
| 195 |
|
| 196 |
:param module: Processed Ansible Module. |
| 197 |
:type module: ``object`` |
| 198 |
""" |
| 199 |
self.module = module |
| 200 |
self.name = self.module.params["name"] |
| 201 |
self._build_config() |
| 202 |
self.state = self.module.params["state"] |
| 203 |
self.new_name = self.module.params.get("new_name", None) |
| 204 |
|
| 205 |
self.key_file = self.module.params.get("client_key") |
| 206 |
if self.key_file is None: |
| 207 |
self.key_file = default_key_file() |
| 208 |
self.cert_file = self.module.params.get("client_cert") |
| 209 |
if self.cert_file is None: |
| 210 |
self.cert_file = default_cert_file() |
| 211 |
self.debug = self.module._verbosity >= 4 |
| 212 |
|
| 213 |
try: |
| 214 |
if self.module.params["url"] != ANSIBLE_LXD_DEFAULT_URL: |
| 215 |
self.url = self.module.params["url"] |
| 216 |
elif os.path.exists(self.module.params["snap_url"].replace("unix:", "")): |
| 217 |
self.url = self.module.params["snap_url"] |
| 218 |
else: |
| 219 |
self.url = self.module.params["url"] |
| 220 |
except Exception as e: |
| 221 |
self.module.fail_json(msg=e.msg) |
| 222 |
|
| 223 |
try: |
| 224 |
self.client = LXDClient(self.url, key_file=self.key_file, cert_file=self.cert_file, debug=self.debug) |
| 225 |
except LXDClientException as e: |
| 226 |
self.module.fail_json(msg=e.msg) |
| 227 |
self.trust_password = self.module.params.get("trust_password", None) |
| 228 |
self.actions = [] |
| 229 |
|
| 230 |
def _build_config(self): |
| 231 |
self.config = {} |
| 232 |
for attr in CONFIG_PARAMS: |
| 233 |
param_val = self.module.params.get(attr, None) |
| 234 |
if param_val is not None: |
| 235 |
self.config[attr] = param_val |
| 236 |
|
| 237 |
def _get_project_json(self): |
| 238 |
return self.client.do("GET", f"/1.0/projects/{self.name}", ok_error_codes=[404]) |
| 239 |
|
| 240 |
@staticmethod |
| 241 |
def _project_json_to_module_state(resp_json): |
| 242 |
if resp_json["type"] == "error": |
| 243 |
return "absent" |
| 244 |
return "present" |
| 245 |
|
| 246 |
def _update_project(self): |
| 247 |
if self.state == "present": |
| 248 |
if self.old_state == "absent": |
| 249 |
if self.new_name is None: |
| 250 |
self._create_project() |
| 251 |
else: |
| 252 |
self.module.fail_json( |
| 253 |
msg="new_name must not be set when the project does not exist and the state is present", |
| 254 |
changed=False, |
| 255 |
) |
| 256 |
else: |
| 257 |
if self.new_name is not None and self.new_name != self.name: |
| 258 |
self._rename_project() |
| 259 |
if self._needs_to_apply_project_configs(): |
| 260 |
self._apply_project_configs() |
| 261 |
elif self.state == "absent": |
| 262 |
if self.old_state == "present": |
| 263 |
if self.new_name is None: |
| 264 |
self._delete_project() |
| 265 |
else: |
| 266 |
self.module.fail_json( |
| 267 |
msg="new_name must not be set when the project exists and the specified state is absent", |
| 268 |
changed=False, |
| 269 |
) |
| 270 |
|
| 271 |
def _create_project(self): |
| 272 |
config = self.config.copy() |
| 273 |
config["name"] = self.name |
| 274 |
self.client.do("POST", "/1.0/projects", config) |
| 275 |
self.actions.append("create") |
| 276 |
|
| 277 |
def _rename_project(self): |
| 278 |
config = {"name": self.new_name} |
| 279 |
self.client.do("POST", f"/1.0/projects/{self.name}", config) |
| 280 |
self.actions.append("rename") |
| 281 |
self.name = self.new_name |
| 282 |
|
| 283 |
def _needs_to_change_project_config(self, key): |
| 284 |
if key not in self.config: |
| 285 |
return False |
| 286 |
old_configs = self.old_project_json["metadata"].get(key, None) |
| 287 |
return self.config[key] != old_configs |
| 288 |
|
| 289 |
def _needs_to_apply_project_configs(self): |
| 290 |
return self._needs_to_change_project_config("config") or self._needs_to_change_project_config("description") |
| 291 |
|
| 292 |
def _merge_dicts(self, source, destination): |
| 293 |
"""Return a new dict that merge two dict, |
| 294 |
with values in source dict overwrite destination dict |
| 295 |
|
| 296 |
Args: |
| 297 |
dict(source): source dict |
| 298 |
dict(destination): destination dict |
| 299 |
Kwargs: |
| 300 |
None |
| 301 |
Raises: |
| 302 |
None |
| 303 |
Returns: |
| 304 |
dict(destination): merged dict""" |
| 305 |
result = destination.copy() |
| 306 |
for key, value in source.items(): |
| 307 |
if isinstance(value, dict): |
| 308 |
# get node or create one |
| 309 |
node = result.setdefault(key, {}) |
| 310 |
self._merge_dicts(value, node) |
| 311 |
else: |
| 312 |
result[key] = value |
| 313 |
return result |
| 314 |
|
| 315 |
def _apply_project_configs(self): |
| 316 |
"""Selection of the procedure: rebuild or merge |
| 317 |
|
| 318 |
The standard behavior is that all information not contained |
| 319 |
in the play is discarded. |
| 320 |
|
| 321 |
If "merge_project" is provides in the play and "True", then existing |
| 322 |
configurations from the project and new ones defined are merged. |
| 323 |
|
| 324 |
Args: |
| 325 |
None |
| 326 |
Kwargs: |
| 327 |
None |
| 328 |
Raises: |
| 329 |
None |
| 330 |
Returns: |
| 331 |
None""" |
| 332 |
old_config = dict() |
| 333 |
old_metadata = self.old_project_json["metadata"].copy() |
| 334 |
for attr in CONFIG_PARAMS: |
| 335 |
old_config[attr] = old_metadata[attr] |
| 336 |
|
| 337 |
if self.module.params["merge_project"]: |
| 338 |
config = self._merge_dicts(self.config, old_config) |
| 339 |
if config == old_config: |
| 340 |
# no need to call api if merged config is the same |
| 341 |
# as old config |
| 342 |
return |
| 343 |
else: |
| 344 |
config = self.config.copy() |
| 345 |
# upload config to lxd |
| 346 |
self.client.do("PUT", f"/1.0/projects/{self.name}", config) |
| 347 |
self.actions.append("apply_projects_configs") |
| 348 |
|
| 349 |
def _delete_project(self): |
| 350 |
self.client.do("DELETE", f"/1.0/projects/{self.name}") |
| 351 |
self.actions.append("delete") |
| 352 |
|
| 353 |
def run(self): |
| 354 |
"""Run the main method.""" |
| 355 |
|
| 356 |
try: |
| 357 |
if self.trust_password is not None: |
| 358 |
self.client.authenticate(self.trust_password) |
| 359 |
|
| 360 |
self.old_project_json = self._get_project_json() |
| 361 |
self.old_state = self._project_json_to_module_state(self.old_project_json) |
| 362 |
self._update_project() |
| 363 |
|
| 364 |
state_changed = len(self.actions) > 0 |
| 365 |
result_json = {"changed": state_changed, "old_state": self.old_state, "actions": self.actions} |
| 366 |
if self.client.debug: |
| 367 |
result_json["logs"] = self.client.logs |
| 368 |
self.module.exit_json(**result_json) |
| 369 |
except LXDClientException as e: |
| 370 |
state_changed = len(self.actions) > 0 |
| 371 |
fail_params = {"msg": e.msg, "changed": state_changed, "actions": self.actions} |
| 372 |
if self.client.debug: |
| 373 |
fail_params["logs"] = e.kwargs["logs"] |
| 374 |
self.module.fail_json(**fail_params) |
| 375 |
|
| 376 |
|
| 377 |
def main(): |
| 378 |
"""Ansible Main module.""" |
| 379 |
|
| 380 |
module = AnsibleModule( |
| 381 |
argument_spec=dict( |
| 382 |
name=dict(type="str", required=True), |
| 383 |
new_name=dict( |
| 384 |
type="str", |
| 385 |
), |
| 386 |
config=dict( |
| 387 |
type="dict", |
| 388 |
), |
| 389 |
description=dict( |
| 390 |
type="str", |
| 391 |
), |
| 392 |
merge_project=dict(type="bool", default=False), |
| 393 |
state=dict(choices=PROJECTS_STATES, default="present"), |
| 394 |
url=dict(type="str", default=ANSIBLE_LXD_DEFAULT_URL), |
| 395 |
snap_url=dict(type="str", default="unix:/var/snap/lxd/common/lxd/unix.socket"), |
| 396 |
client_key=dict(type="path", aliases=["key_file"]), |
| 397 |
client_cert=dict(type="path", aliases=["cert_file"]), |
| 398 |
trust_password=dict(type="str", no_log=True), |
| 399 |
), |
| 400 |
supports_check_mode=False, |
| 401 |
) |
| 402 |
|
| 403 |
lxd_manage = LXDProjectManagement(module=module) |
| 404 |
lxd_manage.run() |
| 405 |
|
| 406 |
|
| 407 |
if __name__ == "__main__": |
| 408 |
main() |