| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 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_deploy_key |
| 11 |
author: "Ali (@bincyber)" |
| 12 |
short_description: Manages deploy keys for GitHub repositories |
| 13 |
description: |
| 14 |
- Adds or removes deploy keys for GitHub repositories. Supports authentication using username and password, username and |
| 15 |
password and 2-factor authentication code (OTP), OAuth2 token, or personal access token. Admin rights on the repository |
| 16 |
are required. |
| 17 |
extends_documentation_fragment: |
| 18 |
- community.general._attributes |
| 19 |
attributes: |
| 20 |
check_mode: |
| 21 |
support: full |
| 22 |
diff_mode: |
| 23 |
support: none |
| 24 |
options: |
| 25 |
github_url: |
| 26 |
description: |
| 27 |
- The base URL of the GitHub API. |
| 28 |
type: str |
| 29 |
version_added: '0.2.0' |
| 30 |
default: https://api.github.com |
| 31 |
owner: |
| 32 |
description: |
| 33 |
- The name of the individual account or organization that owns the GitHub repository. |
| 34 |
required: true |
| 35 |
aliases: ['account', 'organization'] |
| 36 |
type: str |
| 37 |
repo: |
| 38 |
description: |
| 39 |
- The name of the GitHub repository. |
| 40 |
required: true |
| 41 |
aliases: ['repository'] |
| 42 |
type: str |
| 43 |
name: |
| 44 |
description: |
| 45 |
- The name for the deploy key. |
| 46 |
required: true |
| 47 |
aliases: ['title', 'label'] |
| 48 |
type: str |
| 49 |
key: |
| 50 |
description: |
| 51 |
- The SSH public key to add to the repository as a deploy key. |
| 52 |
required: true |
| 53 |
type: str |
| 54 |
read_only: |
| 55 |
description: |
| 56 |
- If V(true), the deploy key is only able to read repository contents. Otherwise, the deploy key is able to read and |
| 57 |
write. |
| 58 |
type: bool |
| 59 |
default: true |
| 60 |
state: |
| 61 |
description: |
| 62 |
- The state of the deploy key. |
| 63 |
default: "present" |
| 64 |
choices: ["present", "absent"] |
| 65 |
type: str |
| 66 |
force: |
| 67 |
description: |
| 68 |
- If V(true), forcefully adds the deploy key by deleting any existing deploy key with the same public key or title. |
| 69 |
type: bool |
| 70 |
default: false |
| 71 |
username: |
| 72 |
description: |
| 73 |
- The username to authenticate with. Should not be set when using personal access token. |
| 74 |
type: str |
| 75 |
password: |
| 76 |
description: |
| 77 |
- The password to authenticate with. Alternatively, a personal access token can be used instead of O(username) and O(password) |
| 78 |
combination. |
| 79 |
type: str |
| 80 |
token: |
| 81 |
description: |
| 82 |
- The OAuth2 token or personal access token to authenticate with. Mutually exclusive with O(password). |
| 83 |
type: str |
| 84 |
otp: |
| 85 |
description: |
| 86 |
- The 6 digit One Time Password for 2-Factor Authentication. Required together with O(username) and O(password). |
| 87 |
type: int |
| 88 |
notes: |
| 89 |
- "Refer to GitHub's API documentation here: https://developer.github.com/v3/repos/keys/." |
| 90 |
""" |
| 91 |
|
| 92 |
EXAMPLES = r""" |
| 93 |
- name: Add a new read-only deploy key to a GitHub repository using basic authentication |
| 94 |
community.general.github_deploy_key: |
| 95 |
owner: "johndoe" |
| 96 |
repo: "example" |
| 97 |
name: "new-deploy-key" |
| 98 |
key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDAwXxn7kIMNWzcDfou..." |
| 99 |
read_only: true |
| 100 |
username: "johndoe" |
| 101 |
password: "supersecretpassword" |
| 102 |
|
| 103 |
- name: Remove an existing deploy key from a GitHub repository |
| 104 |
community.general.github_deploy_key: |
| 105 |
owner: "johndoe" |
| 106 |
repository: "example" |
| 107 |
name: "new-deploy-key" |
| 108 |
key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDAwXxn7kIMNWzcDfou..." |
| 109 |
force: true |
| 110 |
username: "johndoe" |
| 111 |
password: "supersecretpassword" |
| 112 |
state: absent |
| 113 |
|
| 114 |
- name: Add a new deploy key to a GitHub repository, replace an existing key, use an OAuth2 token to authenticate |
| 115 |
community.general.github_deploy_key: |
| 116 |
owner: "johndoe" |
| 117 |
repository: "example" |
| 118 |
name: "new-deploy-key" |
| 119 |
key: "{{ lookup('file', '~/.ssh/github.pub') }}" |
| 120 |
force: true |
| 121 |
token: "ABAQDAwXxn7kIMNWzcDfo..." |
| 122 |
|
| 123 |
- name: Re-add a deploy key to a GitHub repository but with a different name |
| 124 |
community.general.github_deploy_key: |
| 125 |
owner: "johndoe" |
| 126 |
repository: "example" |
| 127 |
name: "replace-deploy-key" |
| 128 |
key: "{{ lookup('file', '~/.ssh/github.pub') }}" |
| 129 |
username: "johndoe" |
| 130 |
password: "supersecretpassword" |
| 131 |
|
| 132 |
- name: Add a new deploy key to a GitHub repository using 2FA |
| 133 |
community.general.github_deploy_key: |
| 134 |
owner: "johndoe" |
| 135 |
repo: "example" |
| 136 |
name: "new-deploy-key-2" |
| 137 |
key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDAwXxn7kIMNWzcDfou..." |
| 138 |
username: "johndoe" |
| 139 |
password: "supersecretpassword" |
| 140 |
otp: 123456 |
| 141 |
|
| 142 |
- name: Add a read-only deploy key to a repository hosted on GitHub Enterprise |
| 143 |
community.general.github_deploy_key: |
| 144 |
github_url: "https://api.example.com" |
| 145 |
owner: "janedoe" |
| 146 |
repo: "example" |
| 147 |
name: "new-deploy-key" |
| 148 |
key: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDAwXxn7kIMNWzcDfou..." |
| 149 |
read_only: true |
| 150 |
username: "janedoe" |
| 151 |
password: "supersecretpassword" |
| 152 |
""" |
| 153 |
|
| 154 |
RETURN = r""" |
| 155 |
msg: |
| 156 |
description: The status message describing what occurred. |
| 157 |
returned: always |
| 158 |
type: str |
| 159 |
sample: "Deploy key added successfully" |
| 160 |
|
| 161 |
http_status_code: |
| 162 |
description: The HTTP status code returned by the GitHub API. |
| 163 |
returned: failed |
| 164 |
type: int |
| 165 |
sample: 400 |
| 166 |
|
| 167 |
error: |
| 168 |
description: The error message returned by the GitHub API. |
| 169 |
returned: failed |
| 170 |
type: str |
| 171 |
sample: "key is already in use" |
| 172 |
|
| 173 |
id: |
| 174 |
description: The key identifier assigned by GitHub for the deploy key. |
| 175 |
returned: changed |
| 176 |
type: int |
| 177 |
sample: 24381901 |
| 178 |
""" |
| 179 |
|
| 180 |
from re import findall |
| 181 |
|
| 182 |
from ansible.module_utils.basic import AnsibleModule |
| 183 |
from ansible.module_utils.urls import fetch_url |
| 184 |
|
| 185 |
|
| 186 |
class GithubDeployKey: |
| 187 |
def __init__(self, module): |
| 188 |
self.module = module |
| 189 |
|
| 190 |
self.github_url = self.module.params["github_url"] |
| 191 |
self.name = module.params["name"] |
| 192 |
self.key = module.params["key"] |
| 193 |
self.state = module.params["state"] |
| 194 |
self.read_only = module.params.get("read_only", True) |
| 195 |
self.force = module.params.get("force", False) |
| 196 |
self.username = module.params.get("username", None) |
| 197 |
self.password = module.params.get("password", None) |
| 198 |
self.token = module.params.get("token", None) |
| 199 |
self.otp = module.params.get("otp", None) |
| 200 |
|
| 201 |
@property |
| 202 |
def url(self): |
| 203 |
owner = self.module.params["owner"] |
| 204 |
repo = self.module.params["repo"] |
| 205 |
return f"{self.github_url}/repos/{owner}/{repo}/keys" |
| 206 |
|
| 207 |
@property |
| 208 |
def headers(self): |
| 209 |
if self.username is not None and self.password is not None: |
| 210 |
self.module.params["url_username"] = self.username |
| 211 |
self.module.params["url_password"] = self.password |
| 212 |
self.module.params["force_basic_auth"] = True |
| 213 |
if self.otp is not None: |
| 214 |
return {"X-GitHub-OTP": self.otp} |
| 215 |
elif self.token is not None: |
| 216 |
return {"Authorization": f"token {self.token}"} |
| 217 |
else: |
| 218 |
return None |
| 219 |
|
| 220 |
def paginate(self, url): |
| 221 |
while url: |
| 222 |
resp, info = fetch_url(self.module, url, headers=self.headers, method="GET") |
| 223 |
|
| 224 |
if info["status"] == 200: |
| 225 |
yield self.module.from_json(resp.read()) |
| 226 |
|
| 227 |
links = {} |
| 228 |
for x, y in findall(r'<([^>]+)>;\s*rel="(\w+)"', info.get("link", "")): |
| 229 |
links[y] = x |
| 230 |
|
| 231 |
url = links.get("next") |
| 232 |
else: |
| 233 |
self.handle_error(method="GET", info=info) |
| 234 |
|
| 235 |
def get_existing_key(self): |
| 236 |
for keys in self.paginate(self.url): |
| 237 |
if keys: |
| 238 |
for i in keys: |
| 239 |
existing_key_id = str(i["id"]) |
| 240 |
if i["key"].split() == self.key.split()[:2]: |
| 241 |
return existing_key_id |
| 242 |
elif i["title"] == self.name and self.force: |
| 243 |
return existing_key_id |
| 244 |
else: |
| 245 |
return None |
| 246 |
|
| 247 |
def add_new_key(self): |
| 248 |
request_body = {"title": self.name, "key": self.key, "read_only": self.read_only} |
| 249 |
|
| 250 |
resp, info = fetch_url( |
| 251 |
self.module, |
| 252 |
self.url, |
| 253 |
data=self.module.jsonify(request_body), |
| 254 |
headers=self.headers, |
| 255 |
method="POST", |
| 256 |
timeout=30, |
| 257 |
) |
| 258 |
|
| 259 |
status_code = info["status"] |
| 260 |
|
| 261 |
if status_code == 201: |
| 262 |
response_body = self.module.from_json(resp.read()) |
| 263 |
key_id = response_body["id"] |
| 264 |
self.module.exit_json(changed=True, msg="Deploy key successfully added", id=key_id) |
| 265 |
elif status_code == 422: |
| 266 |
# there might be multiple reasons for a 422 |
| 267 |
# so we must check if the reason is that the key already exists |
| 268 |
if self.get_existing_key(): |
| 269 |
self.module.exit_json(changed=False, msg="Deploy key already exists") |
| 270 |
else: |
| 271 |
self.handle_error(method="POST", info=info) |
| 272 |
else: |
| 273 |
self.handle_error(method="POST", info=info) |
| 274 |
|
| 275 |
def remove_existing_key(self, key_id): |
| 276 |
resp, info = fetch_url(self.module, f"{self.url}/{key_id}", headers=self.headers, method="DELETE") |
| 277 |
|
| 278 |
status_code = info["status"] |
| 279 |
|
| 280 |
if status_code == 204: |
| 281 |
if self.state == "absent": |
| 282 |
self.module.exit_json(changed=True, msg="Deploy key successfully deleted", id=key_id) |
| 283 |
else: |
| 284 |
self.handle_error(method="DELETE", info=info, key_id=key_id) |
| 285 |
|
| 286 |
def handle_error(self, method, info, key_id=None): |
| 287 |
status_code = info["status"] |
| 288 |
body = info.get("body") |
| 289 |
if body: |
| 290 |
err = self.module.from_json(body)["message"] |
| 291 |
else: |
| 292 |
err = None |
| 293 |
|
| 294 |
if status_code == 401: |
| 295 |
self.module.fail_json( |
| 296 |
msg=f"Failed to connect to {self.github_url} due to invalid credentials", |
| 297 |
http_status_code=status_code, |
| 298 |
error=err, |
| 299 |
) |
| 300 |
elif status_code == 404: |
| 301 |
self.module.fail_json(msg="GitHub repository does not exist", http_status_code=status_code, error=err) |
| 302 |
else: |
| 303 |
if method == "GET": |
| 304 |
self.module.fail_json( |
| 305 |
msg="Failed to retrieve existing deploy keys", http_status_code=status_code, error=err |
| 306 |
) |
| 307 |
elif method == "POST": |
| 308 |
self.module.fail_json(msg="Failed to add deploy key", http_status_code=status_code, error=err) |
| 309 |
elif method == "DELETE": |
| 310 |
self.module.fail_json( |
| 311 |
msg="Failed to delete existing deploy key", id=key_id, http_status_code=status_code, error=err |
| 312 |
) |
| 313 |
|
| 314 |
|
| 315 |
def main(): |
| 316 |
module = AnsibleModule( |
| 317 |
argument_spec=dict( |
| 318 |
github_url=dict(type="str", default="https://api.github.com"), |
| 319 |
owner=dict(required=True, type="str", aliases=["account", "organization"]), |
| 320 |
repo=dict(required=True, type="str", aliases=["repository"]), |
| 321 |
name=dict(required=True, type="str", aliases=["title", "label"]), |
| 322 |
key=dict(required=True, type="str", no_log=False), |
| 323 |
read_only=dict(type="bool", default=True), |
| 324 |
state=dict(default="present", choices=["present", "absent"]), |
| 325 |
force=dict(type="bool", default=False), |
| 326 |
username=dict(type="str"), |
| 327 |
password=dict(type="str", no_log=True), |
| 328 |
otp=dict(type="int", no_log=True), |
| 329 |
token=dict(type="str", no_log=True), |
| 330 |
), |
| 331 |
mutually_exclusive=[["password", "token"]], |
| 332 |
required_together=[["username", "password"], ["otp", "username", "password"]], |
| 333 |
required_one_of=[["username", "token"]], |
| 334 |
supports_check_mode=True, |
| 335 |
) |
| 336 |
|
| 337 |
deploy_key = GithubDeployKey(module) |
| 338 |
|
| 339 |
if module.check_mode: |
| 340 |
key_id = deploy_key.get_existing_key() |
| 341 |
if deploy_key.state == "present" and key_id is None: |
| 342 |
module.exit_json(changed=True) |
| 343 |
elif deploy_key.state == "present" and key_id is not None: |
| 344 |
module.exit_json(changed=False) |
| 345 |
|
| 346 |
# to forcefully modify an existing key, the existing key must be deleted first |
| 347 |
if deploy_key.state == "absent" or deploy_key.force: |
| 348 |
key_id = deploy_key.get_existing_key() |
| 349 |
|
| 350 |
if key_id is not None: |
| 351 |
deploy_key.remove_existing_key(key_id) |
| 352 |
elif deploy_key.state == "absent": |
| 353 |
module.exit_json(changed=False, msg="Deploy key does not exist") |
| 354 |
|
| 355 |
if deploy_key.state == "present": |
| 356 |
deploy_key.add_new_key() |
| 357 |
|
| 358 |
|
| 359 |
if __name__ == "__main__": |
| 360 |
main() |