Debian Codegraph @

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

raw
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_secrets
11 short_description: Manage GitHub repository or organization secrets
12 description:
13 - Create, update, or delete secrets in a GitHub repository or organization.
14 author:
15 - Thomas Sjögren (@konstruktoid)
16 version_added: '12.5.0'
17 requirements:
18 - pynacl
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 organization:
28 description:
29 - The GitHub username or organization name.
30 type: str
31 required: true
32 aliases: ["org", "username"]
33 repository:
34 description:
35 - The name of the repository.
36 - If not provided, the secret will be managed at the organization level.
37 type: str
38 aliases: ["repo"]
39 key:
40 description:
41 - The name of the secret.
42 type: str
43 value:
44 description:
45 - The value of the secret. Required when O(state=present).
46 type: str
47 visibility:
48 description:
49 - The visibility of the secret when set at the organization level.
50 - Required when O(state=present) and O(repository) is not set.
51 type: str
52 choices: ["all", "private", "selected"]
53 state:
54 description:
55 - The desired state of the secret.
56 type: str
57 choices: ["present", "absent"]
58 default: "present"
59 api_url:
60 description:
61 - The base URL for the GitHub API.
62 type: str
63 default: "https://api.github.com"
64 token:
65 description:
66 - The GitHub token used for authentication.
67 type: str
68 required: true
69 """
70
71 EXAMPLES = r"""
72 - name: Add Github secret
73 community.general.github_secrets:
74 token: "{{ lookup('ansible.builtin.env', 'GITHUB_TOKEN') }}"
75 repository: "ansible"
76 organization: "ansible"
77 key: "TEST_SECRET"
78 value: "bob"
79 state: "present"
80
81 - name: Delete Github secret
82 community.general.github_secrets:
83 token: "{{ lookup('ansible.builtin.env', 'GITHUB_TOKEN') }}"
84 repository: "ansible"
85 organization: "ansible"
86 key: "TEST_SECRET"
87 state: "absent"
88 """
89
90 RETURN = r"""
91 result:
92 description: The result of the module.
93 type: dict
94 returned: always
95 sample: {
96 "msg": "OK (2 bytes)",
97 "response": "Secret created",
98 "status": 201
99 }
100 """
101
102 import json
103 import typing as t
104 from http import HTTPStatus
105
106 from ansible.module_utils.basic import AnsibleModule
107 from ansible.module_utils.urls import fetch_url
108
109 from ansible_collections.community.general.plugins.module_utils import _deps as deps
110
111 with deps.declare(
112 "pynacl",
113 reason="pynacl is a required dependency",
114 url="https://pypi.org/project/PyNaCl/",
115 ):
116 from nacl import encoding, public
117
118
119 def get_public_key(
120 module: AnsibleModule,
121 api_url: str,
122 headers: dict[str, str],
123 organization: str,
124 repository: str,
125 ) -> tuple[str, str]:
126 """Retrieve the GitHub Actions public key used to encrypt secrets."""
127 if repository:
128 url = f"{api_url}/repos/{organization}/{repository}/actions/secrets/public-key"
129 else:
130 url = f"{api_url}/orgs/{organization}/actions/secrets/public-key"
131
132 resp, info = fetch_url(module, url, headers=headers)
133
134 if info["status"] != HTTPStatus.OK:
135 module.fail_json(msg=f"Failed to get public key: {info}")
136
137 data = json.loads(resp.read())
138 return data["key_id"], data["key"]
139
140
141 def encrypt_secret(public_key: str, secret_value: str) -> str:
142 """Encrypt a secret value using GitHub's public key."""
143 key = public.PublicKey(
144 public_key.encode("utf-8"),
145 encoding.Base64Encoder(), # type: ignore [arg-type]
146 )
147 sealed_box = public.SealedBox(key)
148 encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
149 return encoding.Base64Encoder.encode(encrypted).decode("utf-8")
150
151
152 def check_secret(
153 module: AnsibleModule,
154 api_url: str,
155 headers: dict[str, str],
156 organization: str,
157 repository: str,
158 key: str,
159 ) -> dict[str, int]:
160 url = (
161 f"{api_url}/repos/{organization}/{repository}/actions/secrets/{key}"
162 if repository
163 else f"{api_url}/orgs/{organization}/actions/secrets/{key}"
164 )
165
166 resp, info = fetch_url(module, url, headers=headers)
167
168 if info["status"] in (HTTPStatus.OK, HTTPStatus.NOT_FOUND):
169 return {"status": info["status"]}
170 else:
171 module.fail_json(msg=f"Failed to check secret: {info}")
172
173
174 def upsert_secret(
175 module: AnsibleModule,
176 api_url: str,
177 headers: dict[str, str],
178 organization: str,
179 repository: str,
180 key: str,
181 encrypted_value: str,
182 key_id: str,
183 ) -> dict[str, t.Any]:
184 """Create or update a GitHub Actions secret."""
185 url = (
186 f"{api_url}/repos/{organization}/{repository}/actions/secrets/{key}"
187 if repository
188 else f"{api_url}/orgs/{organization}/actions/secrets/{key}"
189 )
190
191 payload = {
192 "encrypted_value": encrypted_value,
193 "key_id": key_id,
194 }
195
196 if not repository and module.params.get("visibility"):
197 payload["visibility"] = module.params["visibility"]
198
199 if module.check_mode:
200 secret_present = check_secret(module, api_url, headers, organization, repository, key)
201 if secret_present["status"] == HTTPStatus.NOT_FOUND:
202 check_mode_msg = "OK (2 bytes)"
203 check_mode_status = HTTPStatus.CREATED.value
204
205 info = {
206 "msg": check_mode_msg,
207 "status": check_mode_status,
208 }
209 else:
210 check_mode_msg = "OK (unknown bytes)"
211 check_mode_status = HTTPStatus.NO_CONTENT
212
213 info = {
214 "msg": check_mode_msg,
215 "status": check_mode_status,
216 }
217 else:
218 resp, info = fetch_url(
219 module,
220 url,
221 headers=headers,
222 data=json.dumps(payload).encode("utf-8"),
223 method="PUT",
224 )
225
226 if info["status"] not in (HTTPStatus.CREATED, HTTPStatus.NO_CONTENT):
227 module.fail_json(msg=f"Failed to upsert secret: {info}")
228
229 return info
230
231
232 def delete_secret(
233 module: AnsibleModule,
234 api_url: str,
235 headers: dict[str, str],
236 organization: str,
237 repository: str,
238 key: str,
239 ) -> dict[str, t.Any]:
240 """Delete a GitHub Actions secret."""
241 url = (
242 f"{api_url}/repos/{organization}/{repository}/actions/secrets/{key}"
243 if repository
244 else f"{api_url}/orgs/{organization}/actions/secrets/{key}"
245 )
246
247 if module.check_mode:
248 secret_present = check_secret(module, api_url, headers, organization, repository, key)
249 info = {
250 "msg": (
251 "HTTP Error 404: Not Found"
252 if secret_present["status"] == HTTPStatus.NOT_FOUND
253 else "OK (unknown bytes)"
254 ),
255 "status": (
256 HTTPStatus.NO_CONTENT if secret_present["status"] == HTTPStatus.OK else secret_present["status"]
257 ),
258 }
259 else:
260 resp, info = fetch_url(
261 module,
262 url,
263 headers=headers,
264 method="DELETE",
265 )
266
267 if info["status"] not in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_FOUND):
268 module.fail_json(msg=f"Failed to delete secret: {info}")
269
270 return info
271
272
273 def main() -> None:
274 """Ansible module entry point."""
275 argument_spec = {
276 "organization": {
277 "type": "str",
278 "aliases": ["org", "username"],
279 "required": True,
280 },
281 "repository": {"type": "str", "aliases": ["repo"]},
282 "key": {"type": "str", "no_log": False},
283 "value": {"type": "str", "no_log": True},
284 "visibility": {"type": "str", "choices": ["all", "private", "selected"]},
285 "state": {
286 "type": "str",
287 "choices": ["present", "absent"],
288 "default": "present",
289 },
290 "api_url": {"type": "str", "default": "https://api.github.com"},
291 "token": {"type": "str", "required": True, "no_log": True},
292 }
293
294 module = AnsibleModule(
295 argument_spec=argument_spec,
296 required_if=[("state", "present", ["value"])],
297 required_by={"value": "key"},
298 supports_check_mode=True,
299 )
300
301 deps.validate(module)
302
303 organization: str = module.params["organization"]
304 repository: str = module.params["repository"]
305 key: str = module.params["key"]
306 value: str = module.params["value"]
307 visibility: str = module.params.get("visibility")
308 state: str = module.params["state"]
309 api_url: str = module.params["api_url"]
310 token: str = module.params["token"]
311
312 if state == "present" and value is None:
313 module.fail_json(
314 msg="Invalid parameters",
315 details="The 'value' parameter cannot be empty",
316 params=module.params,
317 )
318
319 if state == "present" and not repository and not visibility:
320 module.fail_json(
321 msg="Invalid parameters",
322 details="When 'state' is 'present' and 'repository' is not set, 'visibility' must be provided",
323 params=module.params,
324 )
325
326 result: dict[str, t.Any] = {}
327
328 headers = {
329 "Accept": "application/vnd.github+json",
330 "Authorization": f"Bearer {token}",
331 "Content-Type": "application/json",
332 }
333
334 if state == "present":
335 key_id, public_key = get_public_key(
336 module,
337 api_url,
338 headers,
339 organization,
340 repository,
341 )
342
343 encrypted_value = encrypt_secret(public_key, value)
344
345 upsert = upsert_secret(
346 module,
347 api_url,
348 headers,
349 organization,
350 repository,
351 key,
352 encrypted_value,
353 key_id,
354 )
355
356 response_msg = "Secret created" if upsert["status"] == HTTPStatus.CREATED else "Secret updated"
357
358 result["changed"] = True
359 result.update(
360 result={
361 "status": upsert["status"],
362 "msg": upsert.get("msg"),
363 "response": response_msg,
364 },
365 )
366
367 if state == "absent":
368 delete = delete_secret(
369 module,
370 api_url,
371 headers,
372 organization,
373 repository,
374 key,
375 )
376
377 if delete["status"] == HTTPStatus.NO_CONTENT:
378 result["changed"] = True
379 result.update(
380 result={
381 "status": delete["status"],
382 "msg": delete.get("msg"),
383 "response": "Secret deleted",
384 },
385 )
386
387 if delete["status"] == HTTPStatus.NOT_FOUND:
388 result["changed"] = False
389 result.update(
390 result={
391 "status": delete["status"],
392 "msg": delete.get("msg"),
393 "response": "Secret not found",
394 },
395 )
396
397 module.exit_json(**result)
398
399
400 if __name__ == "__main__":
401 main()