| 1 |
#!/usr/bin/python |
| 2 |
# Copyright 2016 Tomas Karasek <[email protected]> |
| 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: packet_sshkey |
| 10 |
short_description: Create/delete an SSH key in Packet host |
| 11 |
description: |
| 12 |
- Create/delete an SSH key in Packet host. |
| 13 |
- API is documented at U(https://www.packet.net/help/api/#page:ssh-keys,header:ssh-keys-ssh-keys-post). |
| 14 |
author: "Tomas Karasek (@t0mk) <[email protected]>" |
| 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 |
state: |
| 24 |
description: |
| 25 |
- Indicate desired state of the target. |
| 26 |
default: present |
| 27 |
choices: ['present', 'absent'] |
| 28 |
type: str |
| 29 |
auth_token: |
| 30 |
description: |
| 31 |
- Packet API token. You can also supply it in environment variable E(PACKET_API_TOKEN). |
| 32 |
type: str |
| 33 |
label: |
| 34 |
description: |
| 35 |
- Label for the key. If you keep it empty, it is read from key string. |
| 36 |
type: str |
| 37 |
aliases: [name] |
| 38 |
id: |
| 39 |
description: |
| 40 |
- UUID of the key which you want to remove. |
| 41 |
type: str |
| 42 |
fingerprint: |
| 43 |
description: |
| 44 |
- Fingerprint of the key which you want to remove. |
| 45 |
type: str |
| 46 |
key: |
| 47 |
description: |
| 48 |
- Public Key string (V({type} {base64 encoded key} {description})). |
| 49 |
type: str |
| 50 |
key_file: |
| 51 |
description: |
| 52 |
- File with the public key. |
| 53 |
type: path |
| 54 |
|
| 55 |
requirements: |
| 56 |
- packet-python |
| 57 |
""" |
| 58 |
|
| 59 |
EXAMPLES = r""" |
| 60 |
# All the examples assume that you have your Packet API token in env var PACKET_API_TOKEN. |
| 61 |
# You can also pass the api token in module param auth_token. |
| 62 |
|
| 63 |
- name: Create sshkey from string |
| 64 |
hosts: localhost |
| 65 |
tasks: |
| 66 |
- community.general.packet_sshkey: |
| 67 |
key: "{{ lookup('file', 'my_packet_sshkey.pub') }}" |
| 68 |
|
| 69 |
- name: Create sshkey from file |
| 70 |
hosts: localhost |
| 71 |
tasks: |
| 72 |
- community.general.packet_sshkey: |
| 73 |
label: key from file |
| 74 |
key_file: ~/ff.pub |
| 75 |
|
| 76 |
- name: Remove sshkey by id |
| 77 |
hosts: localhost |
| 78 |
tasks: |
| 79 |
- community.general.packet_sshkey: |
| 80 |
state: absent |
| 81 |
id: eef49903-7a09-4ca1-af67-4087c29ab5b6 |
| 82 |
""" |
| 83 |
|
| 84 |
RETURN = r""" |
| 85 |
sshkeys: |
| 86 |
description: Information about sshkeys that were created/removed. |
| 87 |
type: list |
| 88 |
sample: |
| 89 |
[ |
| 90 |
{ |
| 91 |
"fingerprint": "5c:93:74:7c:ed:07:17:62:28:75:79:23:d6:08:93:46", |
| 92 |
"id": "41d61bd8-3342-428b-a09c-e67bdd18a9b7", |
| 93 |
"key": "ssh-dss AAAAB3NzaC1kc3MAAACBA ... MdDxfmcsCslJKgoRKSmQpCwXQtN2g== user@server", |
| 94 |
"label": "mynewkey33" |
| 95 |
} |
| 96 |
] |
| 97 |
returned: always |
| 98 |
""" |
| 99 |
|
| 100 |
import os |
| 101 |
import uuid |
| 102 |
|
| 103 |
from ansible.module_utils.basic import AnsibleModule |
| 104 |
|
| 105 |
HAS_PACKET_SDK = True |
| 106 |
try: |
| 107 |
import packet |
| 108 |
except ImportError: |
| 109 |
HAS_PACKET_SDK = False |
| 110 |
|
| 111 |
|
| 112 |
PACKET_API_TOKEN_ENV_VAR = "PACKET_API_TOKEN" |
| 113 |
|
| 114 |
|
| 115 |
def serialize_sshkey(sshkey): |
| 116 |
sshkey_data = {} |
| 117 |
copy_keys = ["id", "key", "label", "fingerprint"] |
| 118 |
for name in copy_keys: |
| 119 |
sshkey_data[name] = getattr(sshkey, name) |
| 120 |
return sshkey_data |
| 121 |
|
| 122 |
|
| 123 |
def is_valid_uuid(myuuid): |
| 124 |
try: |
| 125 |
val = uuid.UUID(myuuid, version=4) |
| 126 |
except ValueError: |
| 127 |
return False |
| 128 |
return str(val) == myuuid |
| 129 |
|
| 130 |
|
| 131 |
def load_key_string(key_str): |
| 132 |
ret_dict = {} |
| 133 |
key_str = key_str.strip() |
| 134 |
ret_dict["key"] = key_str |
| 135 |
cut_key = key_str.split() |
| 136 |
if len(cut_key) in [2, 3]: |
| 137 |
if len(cut_key) == 3: |
| 138 |
ret_dict["label"] = cut_key[2] |
| 139 |
else: |
| 140 |
raise Exception(f"Public key {key_str} is in wrong format") |
| 141 |
return ret_dict |
| 142 |
|
| 143 |
|
| 144 |
def get_sshkey_selector(module): |
| 145 |
key_id = module.params.get("id") |
| 146 |
if key_id: |
| 147 |
if not is_valid_uuid(key_id): |
| 148 |
raise Exception(f"sshkey ID {key_id} is not valid UUID") |
| 149 |
selecting_fields = ["label", "fingerprint", "id", "key"] |
| 150 |
select_dict = {} |
| 151 |
for f in selecting_fields: |
| 152 |
if module.params.get(f) is not None: |
| 153 |
select_dict[f] = module.params.get(f) |
| 154 |
|
| 155 |
if module.params.get("key_file"): |
| 156 |
with open(module.params.get("key_file")) as _file: |
| 157 |
loaded_key = load_key_string(_file.read()) |
| 158 |
select_dict["key"] = loaded_key["key"] |
| 159 |
if module.params.get("label") is None: |
| 160 |
if loaded_key.get("label"): |
| 161 |
select_dict["label"] = loaded_key["label"] |
| 162 |
|
| 163 |
def selector(k): |
| 164 |
if "key" in select_dict: |
| 165 |
# if key string is specified, compare only the key strings |
| 166 |
return k.key == select_dict["key"] |
| 167 |
else: |
| 168 |
# if key string not specified, all the fields must match |
| 169 |
return all(select_dict[f] == getattr(k, f) for f in select_dict) |
| 170 |
|
| 171 |
return selector |
| 172 |
|
| 173 |
|
| 174 |
def act_on_sshkeys(target_state, module, packet_conn): |
| 175 |
selector = get_sshkey_selector(module) |
| 176 |
existing_sshkeys = packet_conn.list_ssh_keys() |
| 177 |
matching_sshkeys = list(filter(selector, existing_sshkeys)) |
| 178 |
changed = False |
| 179 |
if target_state == "present": |
| 180 |
if matching_sshkeys == []: |
| 181 |
# there is no key matching the fields from module call |
| 182 |
# => create the key, label and |
| 183 |
newkey = {} |
| 184 |
if module.params.get("key_file"): |
| 185 |
with open(module.params.get("key_file")) as f: |
| 186 |
newkey = load_key_string(f.read()) |
| 187 |
if module.params.get("key"): |
| 188 |
newkey = load_key_string(module.params.get("key")) |
| 189 |
if module.params.get("label"): |
| 190 |
newkey["label"] = module.params.get("label") |
| 191 |
for param in ("label", "key"): |
| 192 |
if param not in newkey: |
| 193 |
_msg = ( |
| 194 |
"If you want to ensure a key is present, you must " |
| 195 |
"supply both a label and a key string, either in " |
| 196 |
f"module params, or in a key file. {param} is missing" |
| 197 |
) |
| 198 |
raise Exception(_msg) |
| 199 |
matching_sshkeys = [] |
| 200 |
new_key_response = packet_conn.create_ssh_key(newkey["label"], newkey["key"]) |
| 201 |
changed = True |
| 202 |
|
| 203 |
matching_sshkeys.append(new_key_response) |
| 204 |
else: |
| 205 |
# state is 'absent' => delete matching keys |
| 206 |
for k in matching_sshkeys: |
| 207 |
try: |
| 208 |
k.delete() |
| 209 |
changed = True |
| 210 |
except Exception as e: |
| 211 |
_msg = f"while trying to remove sshkey {k.label}, id {k.id} {target_state}, got error: {e}" |
| 212 |
raise Exception(_msg) from e |
| 213 |
|
| 214 |
return {"changed": changed, "sshkeys": [serialize_sshkey(k) for k in matching_sshkeys]} |
| 215 |
|
| 216 |
|
| 217 |
def main(): |
| 218 |
module = AnsibleModule( |
| 219 |
argument_spec=dict( |
| 220 |
state=dict(choices=["present", "absent"], default="present"), |
| 221 |
auth_token=dict(default=os.environ.get(PACKET_API_TOKEN_ENV_VAR), no_log=True), |
| 222 |
label=dict(type="str", aliases=["name"]), |
| 223 |
id=dict(type="str"), |
| 224 |
fingerprint=dict(type="str"), |
| 225 |
key=dict(type="str", no_log=True), |
| 226 |
key_file=dict(type="path"), |
| 227 |
), |
| 228 |
mutually_exclusive=[ |
| 229 |
("label", "id"), |
| 230 |
("label", "fingerprint"), |
| 231 |
("id", "fingerprint"), |
| 232 |
("key", "fingerprint"), |
| 233 |
("key", "id"), |
| 234 |
("key_file", "key"), |
| 235 |
], |
| 236 |
) |
| 237 |
|
| 238 |
if not HAS_PACKET_SDK: |
| 239 |
module.fail_json(msg="packet required for this module") |
| 240 |
|
| 241 |
if not module.params.get("auth_token"): |
| 242 |
_fail_msg = f"if Packet API token is not in environment variable {PACKET_API_TOKEN_ENV_VAR}, the auth_token parameter is required" |
| 243 |
module.fail_json(msg=_fail_msg) |
| 244 |
|
| 245 |
auth_token = module.params.get("auth_token") |
| 246 |
|
| 247 |
packet_conn = packet.Manager(auth_token=auth_token) |
| 248 |
|
| 249 |
state = module.params.get("state") |
| 250 |
|
| 251 |
if state in ["present", "absent"]: |
| 252 |
try: |
| 253 |
module.exit_json(**act_on_sshkeys(state, module, packet_conn)) |
| 254 |
except Exception as e: |
| 255 |
module.fail_json(msg=f"failed to set sshkey state: {e}") |
| 256 |
else: |
| 257 |
module.fail_json(msg=f"{state} is not a valid state for this module") |
| 258 |
|
| 259 |
|
| 260 |
if __name__ == "__main__": |
| 261 |
main() |