| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright Ansible Project |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: github_key |
| 11 |
short_description: Manage GitHub access keys |
| 12 |
description: |
| 13 |
- Creates, removes, or updates GitHub access keys. |
| 14 |
- Works with both GitHub.com and GitHub Enterprise Server installations. |
| 15 |
extends_documentation_fragment: |
| 16 |
- community.general._attributes |
| 17 |
attributes: |
| 18 |
check_mode: |
| 19 |
support: full |
| 20 |
diff_mode: |
| 21 |
support: none |
| 22 |
options: |
| 23 |
token: |
| 24 |
description: |
| 25 |
- GitHub Access Token with permission to list and create public keys. |
| 26 |
required: true |
| 27 |
type: str |
| 28 |
name: |
| 29 |
description: |
| 30 |
- SSH key name. |
| 31 |
required: true |
| 32 |
type: str |
| 33 |
pubkey: |
| 34 |
description: |
| 35 |
- SSH public key value. Required when O(state=present). |
| 36 |
type: str |
| 37 |
state: |
| 38 |
description: |
| 39 |
- Whether to remove a key, ensure that it exists, or update its value. |
| 40 |
choices: ['present', 'absent'] |
| 41 |
default: 'present' |
| 42 |
type: str |
| 43 |
force: |
| 44 |
description: |
| 45 |
- The default is V(true), which replaces the existing remote key if it is different than O(pubkey). If V(false), the |
| 46 |
key is only set if no key with the given O(name) exists. |
| 47 |
type: bool |
| 48 |
default: true |
| 49 |
api_url: |
| 50 |
description: |
| 51 |
- URL to the GitHub API if not using github.com but your own GitHub Enterprise instance. |
| 52 |
type: str |
| 53 |
default: 'https://api.github.com' |
| 54 |
version_added: "11.0.0" |
| 55 |
|
| 56 |
author: Robert Estelle (@erydo) |
| 57 |
""" |
| 58 |
|
| 59 |
RETURN = r""" |
| 60 |
deleted_keys: |
| 61 |
description: An array of key objects that were deleted. Only present on state=absent. |
| 62 |
type: list |
| 63 |
returned: When state=absent |
| 64 |
sample: |
| 65 |
[ |
| 66 |
{ |
| 67 |
"id": 0, |
| 68 |
"key": "BASE64 encoded key", |
| 69 |
"url": "http://example.com/github key", |
| 70 |
"created_at": "YYYY-MM-DDTHH:MM:SZ", |
| 71 |
"read_only": false |
| 72 |
} |
| 73 |
] |
| 74 |
matching_keys: |
| 75 |
description: An array of keys matching the specified name. Only present on state=present. |
| 76 |
type: list |
| 77 |
returned: When state=present |
| 78 |
sample: |
| 79 |
[ |
| 80 |
{ |
| 81 |
"id": 0, |
| 82 |
"key": "BASE64 encoded key", |
| 83 |
"url": "http://example.com/github key", |
| 84 |
"created_at": "YYYY-MM-DDTHH:MM:SZ", |
| 85 |
"read_only": false |
| 86 |
} |
| 87 |
] |
| 88 |
key: |
| 89 |
description: Metadata about the key just created. Only present on state=present. |
| 90 |
type: dict |
| 91 |
returned: success |
| 92 |
sample: |
| 93 |
{ |
| 94 |
"id": 0, |
| 95 |
"key": "BASE64 encoded key", |
| 96 |
"url": "http://example.com/github key", |
| 97 |
"created_at": "YYYY-MM-DDTHH:MM:SZ", |
| 98 |
"read_only": false |
| 99 |
} |
| 100 |
""" |
| 101 |
|
| 102 |
EXAMPLES = r""" |
| 103 |
- name: Read SSH public key to authorize |
| 104 |
ansible.builtin.shell: cat /home/foo/.ssh/id_rsa.pub |
| 105 |
register: ssh_pub_key |
| 106 |
|
| 107 |
- name: Authorize key with GitHub |
| 108 |
local_action: |
| 109 |
module: github_key |
| 110 |
name: Access Key for Some Machine |
| 111 |
token: '{{ github_access_token }}' |
| 112 |
pubkey: '{{ ssh_pub_key.stdout }}' |
| 113 |
|
| 114 |
# Alternatively, a single task can be used reading a key from a file on the controller |
| 115 |
- name: Authorize key with GitHub |
| 116 |
community.general.github_key: |
| 117 |
name: Access Key for Some Machine |
| 118 |
token: '{{ github_access_token }}' |
| 119 |
pubkey: "{{ lookup('ansible.builtin.file', '/home/foo/.ssh/id_rsa.pub') }}" |
| 120 |
|
| 121 |
# GitHub Enterprise Server usage |
| 122 |
- name: Authorize key with GitHub Enterprise |
| 123 |
community.general.github_key: |
| 124 |
name: Access Key for Some Machine |
| 125 |
token: '{{ github_enterprise_token }}' |
| 126 |
pubkey: "{{ lookup('ansible.builtin.file', '/home/foo/.ssh/id_rsa.pub') }}" |
| 127 |
api_url: 'https://github.company.com/api/v3' |
| 128 |
""" |
| 129 |
|
| 130 |
import datetime |
| 131 |
import json |
| 132 |
import re |
| 133 |
|
| 134 |
from ansible.module_utils.basic import AnsibleModule |
| 135 |
from ansible.module_utils.urls import fetch_url |
| 136 |
|
| 137 |
from ansible_collections.community.general.plugins.module_utils._datetime import ( |
| 138 |
now, |
| 139 |
) |
| 140 |
|
| 141 |
|
| 142 |
class GitHubResponse: |
| 143 |
def __init__(self, response, info): |
| 144 |
self.content = response.read() |
| 145 |
self.info = info |
| 146 |
|
| 147 |
def json(self): |
| 148 |
return json.loads(self.content) |
| 149 |
|
| 150 |
def links(self): |
| 151 |
links = {} |
| 152 |
if "link" in self.info: |
| 153 |
link_header = self.info["link"] |
| 154 |
matches = re.findall('<([^>]+)>; rel="([^"]+)"', link_header) |
| 155 |
for url, rel in matches: |
| 156 |
links[rel] = url |
| 157 |
return links |
| 158 |
|
| 159 |
|
| 160 |
class GitHubSession: |
| 161 |
def __init__(self, module, token, api_url): |
| 162 |
self.module = module |
| 163 |
self.token = token |
| 164 |
self.api_url = api_url.rstrip("/") |
| 165 |
|
| 166 |
def request(self, method, url, data=None): |
| 167 |
headers = { |
| 168 |
"Authorization": f"token {self.token}", |
| 169 |
"Content-Type": "application/json", |
| 170 |
"Accept": "application/vnd.github.v3+json", |
| 171 |
} |
| 172 |
response, info = fetch_url(self.module, url, method=method, data=data, headers=headers) |
| 173 |
if not (200 <= info["status"] < 400): |
| 174 |
self.module.fail_json(msg=f" failed to send request {method} to {url}: {info['msg']}") |
| 175 |
return GitHubResponse(response, info) |
| 176 |
|
| 177 |
|
| 178 |
def get_all_keys(session): |
| 179 |
url = f"{session.api_url}/user/keys" |
| 180 |
result = [] |
| 181 |
while url: |
| 182 |
r = session.request("GET", url) |
| 183 |
result.extend(r.json()) |
| 184 |
url = r.links().get("next") |
| 185 |
return result |
| 186 |
|
| 187 |
|
| 188 |
def create_key(session, name, pubkey, check_mode): |
| 189 |
if check_mode: |
| 190 |
now_t = now() |
| 191 |
return { |
| 192 |
"id": 0, |
| 193 |
"key": pubkey, |
| 194 |
"title": name, |
| 195 |
"url": "http://example.com/CHECK_MODE_GITHUB_KEY", |
| 196 |
"created_at": datetime.datetime.strftime(now_t, "%Y-%m-%dT%H:%M:%SZ"), |
| 197 |
"read_only": False, |
| 198 |
"verified": False, |
| 199 |
} |
| 200 |
else: |
| 201 |
return session.request( |
| 202 |
"POST", f"{session.api_url}/user/keys", data=json.dumps({"title": name, "key": pubkey}) |
| 203 |
).json() |
| 204 |
|
| 205 |
|
| 206 |
def delete_keys(session, to_delete, check_mode): |
| 207 |
if check_mode: |
| 208 |
return |
| 209 |
|
| 210 |
for key in to_delete: |
| 211 |
session.request("DELETE", f"{session.api_url}/user/keys/{key['id']}") |
| 212 |
|
| 213 |
|
| 214 |
def ensure_key_absent(session, name, check_mode): |
| 215 |
to_delete = [key for key in get_all_keys(session) if key["title"] == name] |
| 216 |
delete_keys(session, to_delete, check_mode=check_mode) |
| 217 |
|
| 218 |
return {"changed": bool(to_delete), "deleted_keys": to_delete} |
| 219 |
|
| 220 |
|
| 221 |
def ensure_key_present(module, session, name, pubkey, force, check_mode): |
| 222 |
all_keys = get_all_keys(session) |
| 223 |
matching_keys = [k for k in all_keys if k["title"] == name] |
| 224 |
deleted_keys = [] |
| 225 |
|
| 226 |
new_signature = pubkey.split(" ")[1] |
| 227 |
for key in all_keys: |
| 228 |
existing_signature = key["key"].split(" ")[1] |
| 229 |
if new_signature == existing_signature and key["title"] != name: |
| 230 |
module.fail_json( |
| 231 |
msg=f"another key with the same content is already registered under the name |{key['title']}|" |
| 232 |
) |
| 233 |
|
| 234 |
if matching_keys and force and matching_keys[0]["key"].split(" ")[1] != new_signature: |
| 235 |
delete_keys(session, matching_keys, check_mode=check_mode) |
| 236 |
(deleted_keys, matching_keys) = (matching_keys, []) |
| 237 |
|
| 238 |
if not matching_keys: |
| 239 |
key = create_key(session, name, pubkey, check_mode=check_mode) |
| 240 |
else: |
| 241 |
key = matching_keys[0] |
| 242 |
|
| 243 |
return { |
| 244 |
"changed": bool(deleted_keys or not matching_keys), |
| 245 |
"deleted_keys": deleted_keys, |
| 246 |
"matching_keys": matching_keys, |
| 247 |
"key": key, |
| 248 |
} |
| 249 |
|
| 250 |
|
| 251 |
def main(): |
| 252 |
argument_spec = { |
| 253 |
"token": {"required": True, "no_log": True}, |
| 254 |
"name": {"required": True}, |
| 255 |
"pubkey": {}, |
| 256 |
"state": {"choices": ["present", "absent"], "default": "present"}, |
| 257 |
"force": {"default": True, "type": "bool"}, |
| 258 |
"api_url": {"default": "https://api.github.com", "type": "str"}, |
| 259 |
} |
| 260 |
module = AnsibleModule( |
| 261 |
argument_spec=argument_spec, |
| 262 |
supports_check_mode=True, |
| 263 |
) |
| 264 |
|
| 265 |
token = module.params["token"] |
| 266 |
name = module.params["name"] |
| 267 |
state = module.params["state"] |
| 268 |
force = module.params["force"] |
| 269 |
pubkey = module.params.get("pubkey") |
| 270 |
api_url = module.params.get("api_url") |
| 271 |
|
| 272 |
if pubkey: |
| 273 |
pubkey_parts = pubkey.split(" ") |
| 274 |
# Keys consist of a protocol, the key data, and an optional comment. |
| 275 |
if len(pubkey_parts) < 2: |
| 276 |
module.fail_json(msg='"pubkey" parameter has an invalid format') |
| 277 |
elif state == "present": |
| 278 |
module.fail_json(msg='"pubkey" is required when state=present') |
| 279 |
|
| 280 |
session = GitHubSession(module, token, api_url) |
| 281 |
if state == "present": |
| 282 |
result = ensure_key_present(module, session, name, pubkey, force=force, check_mode=module.check_mode) |
| 283 |
elif state == "absent": |
| 284 |
result = ensure_key_absent(session, name, check_mode=module.check_mode) |
| 285 |
|
| 286 |
module.exit_json(**result) |
| 287 |
|
| 288 |
|
| 289 |
if __name__ == "__main__": |
| 290 |
main() |