1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +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

@ -115,7 +115,7 @@ PACKET_API_TOKEN_ENV_VAR = "PACKET_API_TOKEN"
def serialize_sshkey(sshkey):
sshkey_data = {}
copy_keys = ['id', 'key', 'label', 'fingerprint']
copy_keys = ["id", "key", "label", "fingerprint"]
for name in copy_keys:
sshkey_data[name] = getattr(sshkey, name)
return sshkey_data
@ -132,42 +132,43 @@ def is_valid_uuid(myuuid):
def load_key_string(key_str):
ret_dict = {}
key_str = key_str.strip()
ret_dict['key'] = key_str
ret_dict["key"] = key_str
cut_key = key_str.split()
if len(cut_key) in [2, 3]:
if len(cut_key) == 3:
ret_dict['label'] = cut_key[2]
ret_dict["label"] = cut_key[2]
else:
raise Exception(f"Public key {key_str} is in wrong format")
return ret_dict
def get_sshkey_selector(module):
key_id = module.params.get('id')
key_id = module.params.get("id")
if key_id:
if not is_valid_uuid(key_id):
raise Exception(f"sshkey ID {key_id} is not valid UUID")
selecting_fields = ['label', 'fingerprint', 'id', 'key']
selecting_fields = ["label", "fingerprint", "id", "key"]
select_dict = {}
for f in selecting_fields:
if module.params.get(f) is not None:
select_dict[f] = module.params.get(f)
if module.params.get('key_file'):
with open(module.params.get('key_file')) as _file:
if module.params.get("key_file"):
with open(module.params.get("key_file")) as _file:
loaded_key = load_key_string(_file.read())
select_dict['key'] = loaded_key['key']
if module.params.get('label') is None:
if loaded_key.get('label'):
select_dict['label'] = loaded_key['label']
select_dict["key"] = loaded_key["key"]
if module.params.get("label") is None:
if loaded_key.get("label"):
select_dict["label"] = loaded_key["label"]
def selector(k):
if 'key' in select_dict:
if "key" in select_dict:
# if key string is specified, compare only the key strings
return k.key == select_dict['key']
return k.key == select_dict["key"]
else:
# if key string not specified, all the fields must match
return all(select_dict[f] == getattr(k, f) for f in select_dict)
return selector
@ -176,27 +177,28 @@ def act_on_sshkeys(target_state, module, packet_conn):
existing_sshkeys = packet_conn.list_ssh_keys()
matching_sshkeys = list(filter(selector, existing_sshkeys))
changed = False
if target_state == 'present':
if target_state == "present":
if matching_sshkeys == []:
# there is no key matching the fields from module call
# => create the key, label and
newkey = {}
if module.params.get('key_file'):
with open(module.params.get('key_file')) as f:
if module.params.get("key_file"):
with open(module.params.get("key_file")) as f:
newkey = load_key_string(f.read())
if module.params.get('key'):
newkey = load_key_string(module.params.get('key'))
if module.params.get('label'):
newkey['label'] = module.params.get('label')
for param in ('label', 'key'):
if module.params.get("key"):
newkey = load_key_string(module.params.get("key"))
if module.params.get("label"):
newkey["label"] = module.params.get("label")
for param in ("label", "key"):
if param not in newkey:
_msg = ("If you want to ensure a key is present, you must "
"supply both a label and a key string, either in "
f"module params, or in a key file. {param} is missing")
_msg = (
"If you want to ensure a key is present, you must "
"supply both a label and a key string, either in "
f"module params, or in a key file. {param} is missing"
)
raise Exception(_msg)
matching_sshkeys = []
new_key_response = packet_conn.create_ssh_key(
newkey['label'], newkey['key'])
new_key_response = packet_conn.create_ssh_key(newkey["label"], newkey["key"])
changed = True
matching_sshkeys.append(new_key_response)
@ -210,55 +212,51 @@ def act_on_sshkeys(target_state, module, packet_conn):
_msg = f"while trying to remove sshkey {k.label}, id {k.id} {target_state}, got error: {e}"
raise Exception(_msg)
return {
'changed': changed,
'sshkeys': [serialize_sshkey(k) for k in matching_sshkeys]
}
return {"changed": changed, "sshkeys": [serialize_sshkey(k) for k in matching_sshkeys]}
def main():
module = AnsibleModule(
argument_spec=dict(
state=dict(choices=['present', 'absent'], default='present'),
auth_token=dict(default=os.environ.get(PACKET_API_TOKEN_ENV_VAR),
no_log=True),
label=dict(type='str', aliases=['name']),
id=dict(type='str'),
fingerprint=dict(type='str'),
key=dict(type='str', no_log=True),
key_file=dict(type='path'),
state=dict(choices=["present", "absent"], default="present"),
auth_token=dict(default=os.environ.get(PACKET_API_TOKEN_ENV_VAR), no_log=True),
label=dict(type="str", aliases=["name"]),
id=dict(type="str"),
fingerprint=dict(type="str"),
key=dict(type="str", no_log=True),
key_file=dict(type="path"),
),
mutually_exclusive=[
('label', 'id'),
('label', 'fingerprint'),
('id', 'fingerprint'),
('key', 'fingerprint'),
('key', 'id'),
('key_file', 'key'),
]
("label", "id"),
("label", "fingerprint"),
("id", "fingerprint"),
("key", "fingerprint"),
("key", "id"),
("key_file", "key"),
],
)
if not HAS_PACKET_SDK:
module.fail_json(msg='packet required for this module')
module.fail_json(msg="packet required for this module")
if not module.params.get('auth_token'):
if not module.params.get("auth_token"):
_fail_msg = f"if Packet API token is not in environment variable {PACKET_API_TOKEN_ENV_VAR}, the auth_token parameter is required"
module.fail_json(msg=_fail_msg)
auth_token = module.params.get('auth_token')
auth_token = module.params.get("auth_token")
packet_conn = packet.Manager(auth_token=auth_token)
state = module.params.get('state')
state = module.params.get("state")
if state in ['present', 'absent']:
if state in ["present", "absent"]:
try:
module.exit_json(**act_on_sshkeys(state, module, packet_conn))
except Exception as e:
module.fail_json(msg=f'failed to set sshkey state: {e}')
module.fail_json(msg=f"failed to set sshkey state: {e}")
else:
module.fail_json(msg=f'{state} is not a valid state for this module')
module.fail_json(msg=f"{state} is not a valid state for this module")
if __name__ == '__main__':
if __name__ == "__main__":
main()