Debian Codegraph @

ansible_collections/community/general/plugins/modules/bitbucket_access_key.py

raw
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_access_key
11 short_description: Manages Bitbucket repository access keys
12 description:
13 - Manages Bitbucket repository access keys (also called deploy keys).
14 author:
15 - Evgeniy Krysanov (@catcombo)
16 extends_documentation_fragment:
17 - community.general._bitbucket
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: none
24 options:
25 repository:
26 description:
27 - The repository name.
28 type: str
29 required: true
30 workspace:
31 description:
32 - The repository owner.
33 - 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).
34 type: str
35 required: true
36 key:
37 description:
38 - The SSH public key.
39 type: str
40 label:
41 description:
42 - The key label.
43 type: str
44 required: true
45 state:
46 description:
47 - Indicates desired state of the access key.
48 type: str
49 required: true
50 choices: [absent, present]
51 notes:
52 - Bitbucket OAuth consumer or App password should have permissions to read and administrate account repositories.
53 - Check mode is supported.
54 """
55
56 EXAMPLES = r"""
57 - name: Create access key
58 community.general.bitbucket_access_key:
59 repository: 'bitbucket-repo'
60 workspace: bitbucket_workspace
61 key: '{{lookup("file", "bitbucket.pub") }}'
62 label: 'Bitbucket'
63 state: present
64
65 - name: Delete access key
66 community.general.bitbucket_access_key:
67 repository: bitbucket-repo
68 workspace: bitbucket_workspace
69 label: Bitbucket
70 state: absent
71 """
72
73 RETURN = r""" # """
74
75 from ansible.module_utils.basic import AnsibleModule
76
77 from ansible_collections.community.general.plugins.module_utils._bitbucket import BitbucketHelper
78
79 error_messages = {
80 "required_key": "`key` is required when the `state` is `present`",
81 "required_permission": "OAuth consumer `client_id` should have permissions to read and administrate the repository",
82 "invalid_workspace_or_repo": "Invalid `repository` or `workspace`",
83 "invalid_key": "Invalid SSH key or key is already in use",
84 }
85
86 BITBUCKET_API_ENDPOINTS = {
87 "deploy-key-list": f"{BitbucketHelper.BITBUCKET_API_URL}/2.0/repositories/{{workspace}}/{{repo_slug}}/deploy-keys/",
88 "deploy-key-detail": f"{BitbucketHelper.BITBUCKET_API_URL}/2.0/repositories/{{workspace}}/{{repo_slug}}/deploy-keys/{{key_id}}",
89 }
90
91
92 def get_existing_deploy_key(module, bitbucket):
93 """
94 Search for an existing deploy key on Bitbucket
95 with the label specified in module param `label`
96
97 :param module: instance of the :class:`AnsibleModule`
98 :param bitbucket: instance of the :class:`BitbucketHelper`
99 :return: existing deploy key or None if not found
100 :rtype: dict or None
101
102 Return example::
103
104 {
105 "id": 123,
106 "label": "mykey",
107 "created_on": "2019-03-23T10:15:21.517377+00:00",
108 "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADA...AdkTg7HGqL3rlaDrEcWfL7Lu6TnhBdq5",
109 "type": "deploy_key",
110 "comment": "",
111 "last_used": None,
112 "repository": {
113 "links": {
114 "self": {
115 "href": "https://api.bitbucket.org/2.0/repositories/mleu/test"
116 },
117 "html": {
118 "href": "https://bitbucket.org/mleu/test"
119 },
120 "avatar": {
121 "href": "..."
122 }
123 },
124 "type": "repository",
125 "name": "test",
126 "full_name": "mleu/test",
127 "uuid": "{85d08b4e-571d-44e9-a507-fa476535aa98}"
128 },
129 "links": {
130 "self": {
131 "href": "https://api.bitbucket.org/2.0/repositories/mleu/test/deploy-keys/123"
132 }
133 },
134 }
135 """
136 content = {
137 "next": BITBUCKET_API_ENDPOINTS["deploy-key-list"].format(
138 workspace=module.params["workspace"],
139 repo_slug=module.params["repository"],
140 )
141 }
142
143 # Look through the all response pages in search of deploy key we need
144 while "next" in content:
145 info, content = bitbucket.request(
146 api_url=content["next"],
147 method="GET",
148 )
149
150 if info["status"] == 404:
151 module.fail_json(msg=error_messages["invalid_workspace_or_repo"])
152
153 if info["status"] == 403:
154 module.fail_json(msg=error_messages["required_permission"])
155
156 if info["status"] != 200:
157 module.fail_json(msg=f"Failed to retrieve the list of deploy keys: {info}")
158
159 res = next((v for v in content["values"] if v["label"] == module.params["label"]), None)
160
161 if res is not None:
162 return res
163
164 return None
165
166
167 def create_deploy_key(module, bitbucket):
168 info, content = bitbucket.request(
169 api_url=BITBUCKET_API_ENDPOINTS["deploy-key-list"].format(
170 workspace=module.params["workspace"],
171 repo_slug=module.params["repository"],
172 ),
173 method="POST",
174 data={
175 "key": module.params["key"],
176 "label": module.params["label"],
177 },
178 )
179
180 if info["status"] == 404:
181 module.fail_json(msg=error_messages["invalid_workspace_or_repo"])
182
183 if info["status"] == 403:
184 module.fail_json(msg=error_messages["required_permission"])
185
186 if info["status"] == 400:
187 module.fail_json(msg=error_messages["invalid_key"])
188
189 if info["status"] != 200:
190 module.fail_json(msg=f"Failed to create deploy key `{module.params['label']}`: {info}")
191
192
193 def delete_deploy_key(module, bitbucket, key_id):
194 info, content = bitbucket.request(
195 api_url=BITBUCKET_API_ENDPOINTS["deploy-key-detail"].format(
196 workspace=module.params["workspace"],
197 repo_slug=module.params["repository"],
198 key_id=key_id,
199 ),
200 method="DELETE",
201 )
202
203 if info["status"] == 404:
204 module.fail_json(msg=error_messages["invalid_workspace_or_repo"])
205
206 if info["status"] == 403:
207 module.fail_json(msg=error_messages["required_permission"])
208
209 if info["status"] != 204:
210 module.fail_json(msg=f"Failed to delete deploy key `{module.params['label']}`: {info}")
211
212
213 def main():
214 argument_spec = BitbucketHelper.bitbucket_argument_spec()
215 argument_spec.update(
216 repository=dict(type="str", required=True),
217 workspace=dict(
218 type="str",
219 required=True,
220 ),
221 key=dict(type="str", no_log=False),
222 label=dict(type="str", required=True),
223 state=dict(type="str", choices=["present", "absent"], required=True),
224 )
225 module = AnsibleModule(
226 argument_spec=argument_spec,
227 supports_check_mode=True,
228 required_one_of=BitbucketHelper.bitbucket_required_one_of(),
229 required_together=BitbucketHelper.bitbucket_required_together(),
230 )
231
232 bitbucket = BitbucketHelper(module)
233
234 key = module.params["key"]
235 state = module.params["state"]
236
237 # Check parameters
238 if (key is None) and (state == "present"):
239 module.fail_json(msg=error_messages["required_key"])
240
241 # Retrieve access token for authorized API requests
242 bitbucket.fetch_access_token()
243
244 # Retrieve existing deploy key (if any)
245 existing_deploy_key = get_existing_deploy_key(module, bitbucket)
246 changed = False
247
248 # Create new deploy key in case it doesn't exists
249 if not existing_deploy_key and (state == "present"):
250 if not module.check_mode:
251 create_deploy_key(module, bitbucket)
252 changed = True
253
254 # Update deploy key if the old value does not match the new one
255 elif existing_deploy_key and (state == "present"):
256 if not key.startswith(existing_deploy_key.get("key")):
257 if not module.check_mode:
258 # Bitbucket doesn't support update key for the same label,
259 # so we need to delete the old one first
260 delete_deploy_key(module, bitbucket, existing_deploy_key["id"])
261 create_deploy_key(module, bitbucket)
262 changed = True
263
264 # Delete deploy key
265 elif existing_deploy_key and (state == "absent"):
266 if not module.check_mode:
267 delete_deploy_key(module, bitbucket, existing_deploy_key["id"])
268 changed = True
269
270 module.exit_json(changed=changed)
271
272
273 if __name__ == "__main__":
274 main()