1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-04-19 10:21:30 +00:00

Reformat everything.

This commit is contained in:
Felix Fontein 2025-11-01 12:08:41 +01:00
parent 3f2213791a
commit 340ff8586d
1008 changed files with 61301 additions and 58309 deletions

View file

@ -177,23 +177,22 @@ actions:
"""
from ansible_collections.community.general.plugins.module_utils.lxd import (
LXDClient, LXDClientException, default_key_file, default_cert_file
LXDClient,
LXDClientException,
default_key_file,
default_cert_file,
)
from ansible.module_utils.basic import AnsibleModule
import os
# ANSIBLE_LXD_DEFAULT_URL is a default value of the lxd endpoint
ANSIBLE_LXD_DEFAULT_URL = 'unix:/var/lib/lxd/unix.socket'
ANSIBLE_LXD_DEFAULT_URL = "unix:/var/lib/lxd/unix.socket"
# PROJECTS_STATES is a list for states supported
PROJECTS_STATES = [
'present', 'absent'
]
PROJECTS_STATES = ["present", "absent"]
# CONFIG_PARAMS is a list of config attribute names.
CONFIG_PARAMS = [
'config', 'description'
]
CONFIG_PARAMS = ["config", "description"]
class LXDProjectManagement:
@ -204,37 +203,34 @@ class LXDProjectManagement:
:type module: ``object``
"""
self.module = module
self.name = self.module.params['name']
self.name = self.module.params["name"]
self._build_config()
self.state = self.module.params['state']
self.new_name = self.module.params.get('new_name', None)
self.state = self.module.params["state"]
self.new_name = self.module.params.get("new_name", None)
self.key_file = self.module.params.get('client_key')
self.key_file = self.module.params.get("client_key")
if self.key_file is None:
self.key_file = default_key_file()
self.cert_file = self.module.params.get('client_cert')
self.cert_file = self.module.params.get("client_cert")
if self.cert_file is None:
self.cert_file = default_cert_file()
self.debug = self.module._verbosity >= 4
try:
if self.module.params['url'] != ANSIBLE_LXD_DEFAULT_URL:
self.url = self.module.params['url']
elif os.path.exists(self.module.params['snap_url'].replace('unix:', '')):
self.url = self.module.params['snap_url']
if self.module.params["url"] != ANSIBLE_LXD_DEFAULT_URL:
self.url = self.module.params["url"]
elif os.path.exists(self.module.params["snap_url"].replace("unix:", "")):
self.url = self.module.params["snap_url"]
else:
self.url = self.module.params['url']
self.url = self.module.params["url"]
except Exception as e:
self.module.fail_json(msg=e.msg)
try:
self.client = LXDClient(
self.url, key_file=self.key_file, cert_file=self.cert_file,
debug=self.debug
)
self.client = LXDClient(self.url, key_file=self.key_file, cert_file=self.cert_file, debug=self.debug)
except LXDClientException as e:
self.module.fail_json(msg=e.msg)
self.trust_password = self.module.params.get('trust_password', None)
self.trust_password = self.module.params.get("trust_password", None)
self.actions = []
def _build_config(self):
@ -245,66 +241,62 @@ class LXDProjectManagement:
self.config[attr] = param_val
def _get_project_json(self):
return self.client.do(
'GET', f'/1.0/projects/{self.name}',
ok_error_codes=[404]
)
return self.client.do("GET", f"/1.0/projects/{self.name}", ok_error_codes=[404])
@staticmethod
def _project_json_to_module_state(resp_json):
if resp_json['type'] == 'error':
return 'absent'
return 'present'
if resp_json["type"] == "error":
return "absent"
return "present"
def _update_project(self):
if self.state == 'present':
if self.old_state == 'absent':
if self.state == "present":
if self.old_state == "absent":
if self.new_name is None:
self._create_project()
else:
self.module.fail_json(
msg='new_name must not be set when the project does not exist and the state is present',
changed=False)
msg="new_name must not be set when the project does not exist and the state is present",
changed=False,
)
else:
if self.new_name is not None and self.new_name != self.name:
self._rename_project()
if self._needs_to_apply_project_configs():
self._apply_project_configs()
elif self.state == 'absent':
if self.old_state == 'present':
elif self.state == "absent":
if self.old_state == "present":
if self.new_name is None:
self._delete_project()
else:
self.module.fail_json(
msg='new_name must not be set when the project exists and the specified state is absent',
changed=False)
msg="new_name must not be set when the project exists and the specified state is absent",
changed=False,
)
def _create_project(self):
config = self.config.copy()
config['name'] = self.name
self.client.do('POST', '/1.0/projects', config)
self.actions.append('create')
config["name"] = self.name
self.client.do("POST", "/1.0/projects", config)
self.actions.append("create")
def _rename_project(self):
config = {'name': self.new_name}
self.client.do('POST', f'/1.0/projects/{self.name}', config)
self.actions.append('rename')
config = {"name": self.new_name}
self.client.do("POST", f"/1.0/projects/{self.name}", config)
self.actions.append("rename")
self.name = self.new_name
def _needs_to_change_project_config(self, key):
if key not in self.config:
return False
old_configs = self.old_project_json['metadata'].get(key, None)
old_configs = self.old_project_json["metadata"].get(key, None)
return self.config[key] != old_configs
def _needs_to_apply_project_configs(self):
return (
self._needs_to_change_project_config('config') or
self._needs_to_change_project_config('description')
)
return self._needs_to_change_project_config("config") or self._needs_to_change_project_config("description")
def _merge_dicts(self, source, destination):
""" Return a new dict that merge two dict,
"""Return a new dict that merge two dict,
with values in source dict overwrite destination dict
Args:
@ -327,7 +319,7 @@ class LXDProjectManagement:
return result
def _apply_project_configs(self):
""" Selection of the procedure: rebuild or merge
"""Selection of the procedure: rebuild or merge
The standard behavior is that all information not contained
in the play is discarded.
@ -344,11 +336,11 @@ class LXDProjectManagement:
Returns:
None"""
old_config = dict()
old_metadata = self.old_project_json['metadata'].copy()
old_metadata = self.old_project_json["metadata"].copy()
for attr in CONFIG_PARAMS:
old_config[attr] = old_metadata[attr]
if self.module.params['merge_project']:
if self.module.params["merge_project"]:
config = self._merge_dicts(self.config, old_config)
if config == old_config:
# no need to call api if merged config is the same
@ -357,12 +349,12 @@ class LXDProjectManagement:
else:
config = self.config.copy()
# upload config to lxd
self.client.do('PUT', f'/1.0/projects/{self.name}', config)
self.actions.append('apply_projects_configs')
self.client.do("PUT", f"/1.0/projects/{self.name}", config)
self.actions.append("apply_projects_configs")
def _delete_project(self):
self.client.do('DELETE', f'/1.0/projects/{self.name}')
self.actions.append('delete')
self.client.do("DELETE", f"/1.0/projects/{self.name}")
self.actions.append("delete")
def run(self):
"""Run the main method."""
@ -372,28 +364,19 @@ class LXDProjectManagement:
self.client.authenticate(self.trust_password)
self.old_project_json = self._get_project_json()
self.old_state = self._project_json_to_module_state(
self.old_project_json)
self.old_state = self._project_json_to_module_state(self.old_project_json)
self._update_project()
state_changed = len(self.actions) > 0
result_json = {
'changed': state_changed,
'old_state': self.old_state,
'actions': self.actions
}
result_json = {"changed": state_changed, "old_state": self.old_state, "actions": self.actions}
if self.client.debug:
result_json['logs'] = self.client.logs
result_json["logs"] = self.client.logs
self.module.exit_json(**result_json)
except LXDClientException as e:
state_changed = len(self.actions) > 0
fail_params = {
'msg': e.msg,
'changed': state_changed,
'actions': self.actions
}
fail_params = {"msg": e.msg, "changed": state_changed, "actions": self.actions}
if self.client.debug:
fail_params['logs'] = e.kwargs['logs']
fail_params["logs"] = e.kwargs["logs"]
self.module.fail_json(**fail_params)
@ -402,44 +385,23 @@ def main():
module = AnsibleModule(
argument_spec=dict(
name=dict(
type='str',
required=True
),
name=dict(type="str", required=True),
new_name=dict(
type='str',
type="str",
),
config=dict(
type='dict',
type="dict",
),
description=dict(
type='str',
type="str",
),
merge_project=dict(
type='bool',
default=False
),
state=dict(
choices=PROJECTS_STATES,
default='present'
),
url=dict(
type='str',
default=ANSIBLE_LXD_DEFAULT_URL
),
snap_url=dict(
type='str',
default='unix:/var/snap/lxd/common/lxd/unix.socket'
),
client_key=dict(
type='path',
aliases=['key_file']
),
client_cert=dict(
type='path',
aliases=['cert_file']
),
trust_password=dict(type='str', no_log=True)
merge_project=dict(type="bool", default=False),
state=dict(choices=PROJECTS_STATES, default="present"),
url=dict(type="str", default=ANSIBLE_LXD_DEFAULT_URL),
snap_url=dict(type="str", default="unix:/var/snap/lxd/common/lxd/unix.socket"),
client_key=dict(type="path", aliases=["key_file"]),
client_cert=dict(type="path", aliases=["cert_file"]),
trust_password=dict(type="str", no_log=True),
),
supports_check_mode=False,
)
@ -448,5 +410,5 @@ def main():
lxd_manage.run()
if __name__ == '__main__':
if __name__ == "__main__":
main()