| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright (c) 2019, Evgeniy Krysanov <[email protected]> |
| 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: bitbucket_pipeline_known_host |
| 11 |
short_description: Manages Bitbucket pipeline known hosts |
| 12 |
description: |
| 13 |
- Manages Bitbucket pipeline known hosts under the "SSH Keys" menu. |
| 14 |
- The host fingerprint is retrieved automatically, but in case of an error, one can use O(key) field to specify it manually. |
| 15 |
author: |
| 16 |
- Evgeniy Krysanov (@catcombo) |
| 17 |
extends_documentation_fragment: |
| 18 |
- community.general._bitbucket |
| 19 |
- community.general._attributes |
| 20 |
requirements: |
| 21 |
- paramiko |
| 22 |
attributes: |
| 23 |
check_mode: |
| 24 |
support: full |
| 25 |
diff_mode: |
| 26 |
support: none |
| 27 |
options: |
| 28 |
repository: |
| 29 |
description: |
| 30 |
- The repository name. |
| 31 |
type: str |
| 32 |
required: true |
| 33 |
workspace: |
| 34 |
description: |
| 35 |
- The repository owner. |
| 36 |
- B(Note:) O(ignore:username) used to be an alias of this option. Since community.general 6.0.0 it is an alias of O(user). |
| 37 |
type: str |
| 38 |
required: true |
| 39 |
name: |
| 40 |
description: |
| 41 |
- The FQDN of the known host. |
| 42 |
type: str |
| 43 |
required: true |
| 44 |
key: |
| 45 |
description: |
| 46 |
- The public key. |
| 47 |
type: str |
| 48 |
state: |
| 49 |
description: |
| 50 |
- Indicates desired state of the record. |
| 51 |
type: str |
| 52 |
required: true |
| 53 |
choices: [absent, present] |
| 54 |
notes: |
| 55 |
- Check mode is supported. |
| 56 |
""" |
| 57 |
|
| 58 |
EXAMPLES = r""" |
| 59 |
- name: Create known hosts from the list |
| 60 |
community.general.bitbucket_pipeline_known_host: |
| 61 |
repository: 'bitbucket-repo' |
| 62 |
workspace: bitbucket_workspace |
| 63 |
name: '{{ item }}' |
| 64 |
state: present |
| 65 |
with_items: |
| 66 |
- bitbucket.org |
| 67 |
- example.com |
| 68 |
|
| 69 |
- name: Remove known host |
| 70 |
community.general.bitbucket_pipeline_known_host: |
| 71 |
repository: bitbucket-repo |
| 72 |
workspace: bitbucket_workspace |
| 73 |
name: bitbucket.org |
| 74 |
state: absent |
| 75 |
|
| 76 |
- name: Specify public key file |
| 77 |
community.general.bitbucket_pipeline_known_host: |
| 78 |
repository: bitbucket-repo |
| 79 |
workspace: bitbucket_workspace |
| 80 |
name: bitbucket.org |
| 81 |
key: '{{lookup("file", "bitbucket.pub") }}' |
| 82 |
state: absent |
| 83 |
""" |
| 84 |
|
| 85 |
RETURN = r""" # """ |
| 86 |
|
| 87 |
import socket |
| 88 |
|
| 89 |
try: |
| 90 |
import paramiko |
| 91 |
|
| 92 |
HAS_PARAMIKO = True |
| 93 |
except ImportError: |
| 94 |
HAS_PARAMIKO = False |
| 95 |
|
| 96 |
from ansible.module_utils.basic import AnsibleModule |
| 97 |
|
| 98 |
from ansible_collections.community.general.plugins.module_utils._bitbucket import BitbucketHelper |
| 99 |
|
| 100 |
error_messages = { |
| 101 |
"invalid_params": "Account or repository was not found", |
| 102 |
"unknown_key_type": "Public key type is unknown", |
| 103 |
} |
| 104 |
|
| 105 |
BITBUCKET_API_ENDPOINTS = { |
| 106 |
"known-host-list": f"{BitbucketHelper.BITBUCKET_API_URL}/2.0/repositories/{{workspace}}/{{repo_slug}}/pipelines_config/ssh/known_hosts/", |
| 107 |
"known-host-detail": ( |
| 108 |
f"{BitbucketHelper.BITBUCKET_API_URL}/2.0/repositories/{{workspace}}/{{repo_slug}}/pipelines_config/ssh/known_hosts/{{known_host_uuid}}" |
| 109 |
), |
| 110 |
} |
| 111 |
|
| 112 |
|
| 113 |
def get_existing_known_host(module, bitbucket): |
| 114 |
""" |
| 115 |
Search for a host in Bitbucket pipelines known hosts |
| 116 |
with the name specified in module param `name` |
| 117 |
|
| 118 |
:param module: instance of the :class:`AnsibleModule` |
| 119 |
:param bitbucket: instance of the :class:`BitbucketHelper` |
| 120 |
:return: existing host or None if not found |
| 121 |
:rtype: dict or None |
| 122 |
|
| 123 |
Return example:: |
| 124 |
|
| 125 |
{ |
| 126 |
'type': 'pipeline_known_host', |
| 127 |
'uuid': '{21cc0590-bebe-4fae-8baf-03722704119a7}' |
| 128 |
'hostname': 'bitbucket.org', |
| 129 |
'public_key': { |
| 130 |
'type': 'pipeline_ssh_public_key', |
| 131 |
'md5_fingerprint': 'md5:97:8c:1b:f2:6f:14:6b:4b:3b:ec:aa:46:46:74:7c:40', |
| 132 |
'sha256_fingerprint': 'SHA256:zzXQOXSFBEiUtuE8AikoYKwbHaxvSc0ojez9YXaGp1A', |
| 133 |
'key_type': 'ssh-rsa', |
| 134 |
'key': 'AAAAB3NzaC1yc2EAAAABIwAAAQEAubiN81eDcafrgMeLzaFPsw2kN...seeFVBoGqzHM9yXw==' |
| 135 |
}, |
| 136 |
} |
| 137 |
""" |
| 138 |
content = { |
| 139 |
"next": BITBUCKET_API_ENDPOINTS["known-host-list"].format( |
| 140 |
workspace=module.params["workspace"], |
| 141 |
repo_slug=module.params["repository"], |
| 142 |
) |
| 143 |
} |
| 144 |
|
| 145 |
# Look through all response pages in search of hostname we need |
| 146 |
while "next" in content: |
| 147 |
info, content = bitbucket.request( |
| 148 |
api_url=content["next"], |
| 149 |
method="GET", |
| 150 |
) |
| 151 |
|
| 152 |
if info["status"] == 404: |
| 153 |
module.fail_json(msg="Invalid `repository` or `workspace`.") |
| 154 |
|
| 155 |
if info["status"] != 200: |
| 156 |
module.fail_json(msg=f"Failed to retrieve list of known hosts: {info}") |
| 157 |
|
| 158 |
host = next((v for v in content["values"] if v["hostname"] == module.params["name"]), None) |
| 159 |
|
| 160 |
if host is not None: |
| 161 |
return host |
| 162 |
|
| 163 |
return None |
| 164 |
|
| 165 |
|
| 166 |
def get_host_key(module, hostname): |
| 167 |
""" |
| 168 |
Fetches public key for specified host |
| 169 |
|
| 170 |
:param module: instance of the :class:`AnsibleModule` |
| 171 |
:param hostname: host name |
| 172 |
:return: key type and key content |
| 173 |
:rtype: tuple |
| 174 |
|
| 175 |
Return example:: |
| 176 |
|
| 177 |
( |
| 178 |
'ssh-rsa', |
| 179 |
'AAAAB3NzaC1yc2EAAAABIwAAA...SBne8+seeFVBoGqzHM9yXw==', |
| 180 |
) |
| 181 |
""" |
| 182 |
try: |
| 183 |
sock = socket.socket() |
| 184 |
sock.connect((hostname, 22)) |
| 185 |
except OSError: |
| 186 |
module.fail_json(msg=f"Error opening socket to {hostname}") |
| 187 |
|
| 188 |
try: |
| 189 |
trans = paramiko.transport.Transport(sock) |
| 190 |
trans.start_client() |
| 191 |
host_key = trans.get_remote_server_key() |
| 192 |
except paramiko.SSHException: |
| 193 |
module.fail_json(msg=f"SSH error on retrieving {hostname} server key") |
| 194 |
|
| 195 |
trans.close() |
| 196 |
sock.close() |
| 197 |
|
| 198 |
key_type = host_key.get_name() |
| 199 |
key = host_key.get_base64() |
| 200 |
|
| 201 |
return key_type, key |
| 202 |
|
| 203 |
|
| 204 |
def create_known_host(module, bitbucket): |
| 205 |
hostname = module.params["name"] |
| 206 |
key_param = module.params["key"] |
| 207 |
|
| 208 |
if key_param is None: |
| 209 |
key_type, key = get_host_key(module, hostname) |
| 210 |
elif " " in key_param: |
| 211 |
key_type, key = key_param.split(" ", 1) |
| 212 |
else: |
| 213 |
module.fail_json(msg=error_messages["unknown_key_type"]) |
| 214 |
|
| 215 |
info, content = bitbucket.request( |
| 216 |
api_url=BITBUCKET_API_ENDPOINTS["known-host-list"].format( |
| 217 |
workspace=module.params["workspace"], |
| 218 |
repo_slug=module.params["repository"], |
| 219 |
), |
| 220 |
method="POST", |
| 221 |
data={ |
| 222 |
"hostname": hostname, |
| 223 |
"public_key": { |
| 224 |
"key_type": key_type, |
| 225 |
"key": key, |
| 226 |
}, |
| 227 |
}, |
| 228 |
) |
| 229 |
|
| 230 |
if info["status"] == 404: |
| 231 |
module.fail_json(msg=error_messages["invalid_params"]) |
| 232 |
|
| 233 |
if info["status"] != 201: |
| 234 |
module.fail_json(msg=f"Failed to create known host `{module.params['hostname']}`: {info}") |
| 235 |
|
| 236 |
|
| 237 |
def delete_known_host(module, bitbucket, known_host_uuid): |
| 238 |
info, content = bitbucket.request( |
| 239 |
api_url=BITBUCKET_API_ENDPOINTS["known-host-detail"].format( |
| 240 |
workspace=module.params["workspace"], |
| 241 |
repo_slug=module.params["repository"], |
| 242 |
known_host_uuid=known_host_uuid, |
| 243 |
), |
| 244 |
method="DELETE", |
| 245 |
) |
| 246 |
|
| 247 |
if info["status"] == 404: |
| 248 |
module.fail_json(msg=error_messages["invalid_params"]) |
| 249 |
|
| 250 |
if info["status"] != 204: |
| 251 |
module.fail_json(msg=f"Failed to delete known host `{module.params['name']}`: {info}") |
| 252 |
|
| 253 |
|
| 254 |
def main(): |
| 255 |
argument_spec = BitbucketHelper.bitbucket_argument_spec() |
| 256 |
argument_spec.update( |
| 257 |
repository=dict(type="str", required=True), |
| 258 |
workspace=dict(type="str", required=True), |
| 259 |
name=dict(type="str", required=True), |
| 260 |
key=dict(type="str", no_log=False), |
| 261 |
state=dict(type="str", choices=["present", "absent"], required=True), |
| 262 |
) |
| 263 |
module = AnsibleModule( |
| 264 |
argument_spec=argument_spec, |
| 265 |
supports_check_mode=True, |
| 266 |
required_one_of=BitbucketHelper.bitbucket_required_one_of(), |
| 267 |
required_together=BitbucketHelper.bitbucket_required_together(), |
| 268 |
) |
| 269 |
|
| 270 |
if (module.params["key"] is None) and (not HAS_PARAMIKO): |
| 271 |
module.fail_json(msg="`paramiko` package not found, please install it.") |
| 272 |
|
| 273 |
bitbucket = BitbucketHelper(module) |
| 274 |
|
| 275 |
# Retrieve access token for authorized API requests |
| 276 |
bitbucket.fetch_access_token() |
| 277 |
|
| 278 |
# Retrieve existing known host |
| 279 |
existing_host = get_existing_known_host(module, bitbucket) |
| 280 |
state = module.params["state"] |
| 281 |
changed = False |
| 282 |
|
| 283 |
# Create new host in case it doesn't exists |
| 284 |
if not existing_host and (state == "present"): |
| 285 |
if not module.check_mode: |
| 286 |
create_known_host(module, bitbucket) |
| 287 |
changed = True |
| 288 |
|
| 289 |
# Delete host |
| 290 |
elif existing_host and (state == "absent"): |
| 291 |
if not module.check_mode: |
| 292 |
delete_known_host(module, bitbucket, existing_host["uuid"]) |
| 293 |
changed = True |
| 294 |
|
| 295 |
module.exit_json(changed=changed) |
| 296 |
|
| 297 |
|
| 298 |
if __name__ == "__main__": |
| 299 |
main() |