Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2020, Florent Madiot ([email protected])
4 # Based on code:
5 # Copyright (c) 2019, Markus Bergholz ([email protected])
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: gitlab_group_variable
12 short_description: Creates, updates, or deletes GitLab groups variables
13 version_added: 1.2.0
14 description:
15 - Creates a group variable if it does not exist.
16 - When a group variable does exist and is not hidden, its value is updated when the values are different.
17 When a group variable does exist and is hidden, its value is updated. In this case, the module is B(not idempotent).
18 - Variables which are untouched in the playbook, but are not untouched in the GitLab group, they stay untouched (O(purge=false))
19 or are deleted (O(purge=true)).
20 author:
21 - Florent Madiot (@scodeman)
22 requirements:
23 - python-gitlab python module
24 extends_documentation_fragment:
25 - community.general._auth_basic
26 - community.general._gitlab
27 - community.general._attributes
28
29 attributes:
30 check_mode:
31 support: full
32 diff_mode:
33 support: none
34
35 options:
36 state:
37 description:
38 - Create or delete group variable.
39 default: present
40 type: str
41 choices: ["present", "absent"]
42 group:
43 description:
44 - The path and name of the group.
45 required: true
46 type: str
47 purge:
48 description:
49 - When set to V(true), delete all variables which are not untouched in the task.
50 default: false
51 type: bool
52 vars:
53 description:
54 - When the list element is a simple key-value pair, C(masked), C(hidden), C(raw), and C(protected) are set to V(false).
55 - When the list element is a dict with the keys C(value), C(masked), C(hidden), C(raw), and C(protected), the user can have full
56 control about whether a value should be masked, hidden, raw, protected, or a combination.
57 - Support for group variables requires GitLab >= 9.5.
58 - Support for environment_scope requires GitLab Premium >= 13.11.
59 - Support for protected values requires GitLab >= 9.3.
60 - Support for masked values requires GitLab >= 11.10.
61 - Support for hidden values requires GitLab >= 17.4, and was added in community.general 11.3.0.
62 - Support for raw values requires GitLab >= 15.7.
63 - A C(value) must be a string or a number.
64 - Field C(variable_type) must be a string with either V(env_var), which is the default, or V(file).
65 - When a value is masked, it must be in Base64 and have a length of at least 8 characters. See GitLab documentation
66 on acceptable values for a masked variable (U(https://docs.gitlab.com/ce/ci/variables/#masked-variables)).
67 default: {}
68 type: dict
69 variables:
70 version_added: 4.5.0
71 description:
72 - A list of dictionaries that represents CI/CD variables.
73 - This modules works internal with this structure, even if the older O(vars) parameter is used.
74 default: []
75 type: list
76 elements: dict
77 suboptions:
78 name:
79 description:
80 - The name of the variable.
81 type: str
82 required: true
83 value:
84 description:
85 - The variable value.
86 - Required when O(state=present).
87 type: str
88 description:
89 description:
90 - A description for the variable.
91 - Support for descriptions requires GitLab >= 16.2.
92 type: str
93 version_added: '11.4.0'
94 masked:
95 description:
96 - Whether variable value is masked or not.
97 type: bool
98 default: false
99 hidden:
100 description:
101 - Whether variable value is hidden or not.
102 - Implies C(masked).
103 - Support for hidden values requires GitLab >= 17.4.
104 type: bool
105 default: false
106 version_added: '11.3.0'
107 protected:
108 description:
109 - Whether variable value is protected or not.
110 type: bool
111 default: false
112 raw:
113 description:
114 - Whether variable value is raw or not.
115 - Support for raw values requires GitLab >= 15.7.
116 type: bool
117 default: false
118 version_added: '7.4.0'
119 variable_type:
120 description:
121 - Whether a variable is an environment variable (V(env_var)) or a file (V(file)).
122 type: str
123 choices: ["env_var", "file"]
124 default: env_var
125 environment_scope:
126 description:
127 - The scope for the variable.
128 type: str
129 default: '*'
130 """
131
132
133 EXAMPLES = r"""
134 - name: Set or update some CI/CD variables
135 community.general.gitlab_group_variable:
136 api_url: https://gitlab.com
137 api_token: secret_access_token
138 group: scodeman/testgroup/
139 purge: false
140 variables:
141 - name: ACCESS_KEY_ID
142 value: abc123
143 - name: SECRET_ACCESS_KEY
144 value: 3214cbad
145 masked: true
146 protected: true
147 variable_type: env_var
148 environment_scope: production
149
150 - name: Set or update some CI/CD variables with raw value
151 community.general.gitlab_group_variable:
152 api_url: https://gitlab.com
153 api_token: secret_access_token
154 group: scodeman/testgroup/
155 purge: false
156 vars:
157 ACCESS_KEY_ID: abc123
158 SECRET_ACCESS_KEY:
159 value: 3214cbad
160 masked: true
161 protected: true
162 raw: true
163 variable_type: env_var
164 environment_scope: '*'
165
166 - name: Set or update some CI/CD variables with expandable value
167 community.general.gitlab_group_variable:
168 api_url: https://gitlab.com
169 api_token: secret_access_token
170 group: scodeman/testgroup/
171 purge: false
172 vars:
173 ACCESS_KEY_ID: abc123
174 SECRET_ACCESS_KEY:
175 value: '$MY_OTHER_VARIABLE'
176 masked: true
177 protected: true
178 raw: false
179 variable_type: env_var
180 environment_scope: '*'
181
182 - name: Delete one variable
183 community.general.gitlab_group_variable:
184 api_url: https://gitlab.com
185 api_token: secret_access_token
186 group: scodeman/testgroup/
187 state: absent
188 vars:
189 ACCESS_KEY_ID: abc123
190 """
191
192 RETURN = r"""
193 group_variable:
194 description: Four lists of the variablenames which were added, updated, removed or exist.
195 returned: always
196 type: dict
197 contains:
198 added:
199 description: A list of variables which were created.
200 returned: always
201 type: list
202 sample: ["ACCESS_KEY_ID", "SECRET_ACCESS_KEY"]
203 untouched:
204 description: A list of variables which exist.
205 returned: always
206 type: list
207 sample: ["ACCESS_KEY_ID", "SECRET_ACCESS_KEY"]
208 removed:
209 description: A list of variables which were deleted.
210 returned: always
211 type: list
212 sample: ["ACCESS_KEY_ID", "SECRET_ACCESS_KEY"]
213 updated:
214 description: A list of variables whose values were changed.
215 returned: always
216 type: list
217 sample: ["ACCESS_KEY_ID", "SECRET_ACCESS_KEY"]
218 """
219
220 from ansible.module_utils.api import basic_auth_argument_spec
221 from ansible.module_utils.basic import AnsibleModule
222
223 from ansible_collections.community.general.plugins.module_utils._gitlab import (
224 auth_argument_spec,
225 filter_returned_variables,
226 gitlab_authentication,
227 list_all_kwargs,
228 vars_to_variables,
229 )
230
231
232 class GitlabGroupVariables:
233 def __init__(self, module, gitlab_instance):
234 self.repo = gitlab_instance
235 self.group = self.get_group(module.params["group"])
236 self._module = module
237
238 def get_group(self, group_name):
239 return self.repo.groups.get(group_name)
240
241 def list_all_group_variables(self):
242 return list(self.group.variables.list(**list_all_kwargs))
243
244 def create_variable(self, var_obj):
245 if self._module.check_mode:
246 return True
247 var = {
248 "key": var_obj.get("key"),
249 "value": var_obj.get("value"),
250 "description": var_obj.get("description"),
251 "masked": var_obj.get("masked"),
252 "masked_and_hidden": var_obj.get("hidden"),
253 "protected": var_obj.get("protected"),
254 "raw": var_obj.get("raw"),
255 "variable_type": var_obj.get("variable_type"),
256 }
257 if var_obj.get("environment_scope") is not None:
258 var["environment_scope"] = var_obj.get("environment_scope")
259
260 self.group.variables.create(var)
261 return True
262
263 def update_variable(self, var_obj):
264 if self._module.check_mode:
265 return True
266 self.delete_variable(var_obj)
267 self.create_variable(var_obj)
268 return True
269
270 def delete_variable(self, var_obj):
271 if self._module.check_mode:
272 return True
273 self.group.variables.delete(var_obj.get("key"), filter={"environment_scope": var_obj.get("environment_scope")})
274 return True
275
276
277 def compare(requested_variables, existing_variables, state):
278 # we need to do this, because it was determined in a previous version - more or less buggy
279 # basically it is not necessary and might results in more/other bugs!
280 # but it is required and only relevant for check mode!!
281 # logic represents state 'present' when not purge. all other can be derived from that
282 # untouched => equal in both
283 # updated => name and scope are equal
284 # added => name and scope does not exist
285 untouched = list()
286 updated = list()
287 added = list()
288
289 if state == "present":
290 existing_key_scope_vars = list()
291 for item in existing_variables:
292 existing_key_scope_vars.append({"key": item.get("key"), "environment_scope": item.get("environment_scope")})
293
294 for var in requested_variables:
295 if var in existing_variables:
296 untouched.append(var)
297 else:
298 compare_item = {"key": var.get("name"), "environment_scope": var.get("environment_scope")}
299 if compare_item in existing_key_scope_vars:
300 updated.append(var)
301 else:
302 added.append(var)
303
304 return untouched, updated, added
305
306
307 def native_python_main(this_gitlab, purge, requested_variables, state, module):
308 change = False
309 return_value = dict(added=list(), updated=list(), removed=list(), untouched=list())
310
311 gitlab_keys = this_gitlab.list_all_group_variables()
312 before = [x.attributes for x in gitlab_keys]
313
314 gitlab_keys = this_gitlab.list_all_group_variables()
315 existing_variables = filter_returned_variables(gitlab_keys)
316
317 for item in requested_variables:
318 item["key"] = item.pop("name")
319 item["value"] = str(item.get("value"))
320 if item.get("protected") is None:
321 item["protected"] = False
322 if item.get("raw") is None:
323 item["raw"] = False
324 if item.get("masked") is None:
325 item["masked"] = False
326 if item.get("hidden") is None:
327 item["hidden"] = False
328 if item.get("environment_scope") is None:
329 item["environment_scope"] = "*"
330 if item.get("variable_type") is None:
331 item["variable_type"] = "env_var"
332
333 if module.check_mode:
334 untouched, updated, added = compare(requested_variables, existing_variables, state)
335
336 if state == "present":
337 add_or_update = [x for x in requested_variables if x not in existing_variables]
338 for item in add_or_update:
339 try:
340 if this_gitlab.create_variable(item):
341 return_value["added"].append(item)
342
343 except Exception:
344 if this_gitlab.update_variable(item):
345 return_value["updated"].append(item)
346
347 if purge:
348 # refetch and filter
349 gitlab_keys = this_gitlab.list_all_group_variables()
350 existing_variables = filter_returned_variables(gitlab_keys)
351
352 remove = [x for x in existing_variables if x not in requested_variables]
353 for item in remove:
354 if this_gitlab.delete_variable(item):
355 return_value["removed"].append(item)
356
357 elif state == "absent":
358 # value, type, and description do not matter on removing variables.
359 keys_ignored_on_deletion = ["value", "variable_type", "description"]
360 for key in keys_ignored_on_deletion:
361 for item in existing_variables:
362 item.pop(key)
363 for item in requested_variables:
364 item.pop(key)
365
366 if not purge:
367 remove_requested = [x for x in requested_variables if x in existing_variables]
368 for item in remove_requested:
369 if this_gitlab.delete_variable(item):
370 return_value["removed"].append(item)
371
372 else:
373 for item in existing_variables:
374 if this_gitlab.delete_variable(item):
375 return_value["removed"].append(item)
376
377 if module.check_mode:
378 return_value = dict(added=added, updated=updated, removed=return_value["removed"], untouched=untouched)
379
380 if len(return_value["added"] + return_value["removed"] + return_value["updated"]) > 0:
381 change = True
382
383 gitlab_keys = this_gitlab.list_all_group_variables()
384 after = [x.attributes for x in gitlab_keys]
385
386 return change, return_value, before, after
387
388
389 def main():
390 argument_spec = basic_auth_argument_spec()
391 argument_spec.update(auth_argument_spec())
392 argument_spec.update(
393 group=dict(type="str", required=True),
394 purge=dict(type="bool", default=False),
395 vars=dict(type="dict", default=dict(), no_log=True),
396 # please mind whenever changing the variables dict to also change module_utils/gitlab.py's
397 # KNOWN dict in filter_returned_variables or bad evil will happen
398 variables=dict(
399 type="list",
400 elements="dict",
401 default=list(),
402 options=dict(
403 name=dict(type="str", required=True),
404 value=dict(type="str", no_log=True),
405 description=dict(type="str"),
406 masked=dict(type="bool", default=False),
407 hidden=dict(type="bool", default=False),
408 protected=dict(type="bool", default=False),
409 raw=dict(type="bool", default=False),
410 environment_scope=dict(type="str", default="*"),
411 variable_type=dict(type="str", default="env_var", choices=["env_var", "file"]),
412 ),
413 ),
414 state=dict(type="str", default="present", choices=["absent", "present"]),
415 )
416
417 module = AnsibleModule(
418 argument_spec=argument_spec,
419 mutually_exclusive=[
420 ["api_username", "api_token"],
421 ["api_username", "api_oauth_token"],
422 ["api_username", "api_job_token"],
423 ["api_token", "api_oauth_token"],
424 ["api_token", "api_job_token"],
425 ["vars", "variables"],
426 ],
427 required_together=[
428 ["api_username", "api_password"],
429 ],
430 required_one_of=[["api_username", "api_token", "api_oauth_token", "api_job_token"]],
431 supports_check_mode=True,
432 )
433
434 # check prerequisites and connect to gitlab server
435 gitlab_instance = gitlab_authentication(module)
436
437 purge = module.params["purge"]
438 var_list = module.params["vars"]
439 state = module.params["state"]
440
441 if var_list:
442 variables = vars_to_variables(var_list, module)
443 else:
444 variables = module.params["variables"]
445
446 if state == "present":
447 if any(x["value"] is None for x in variables):
448 module.fail_json(msg="value parameter is required in state present")
449
450 this_gitlab = GitlabGroupVariables(module=module, gitlab_instance=gitlab_instance)
451
452 changed, raw_return_value, before, after = native_python_main(this_gitlab, purge, variables, state, module)
453
454 # postprocessing
455 for item in after:
456 item.pop("group_id")
457 item["name"] = item.pop("key")
458 for item in before:
459 item.pop("group_id")
460 item["name"] = item.pop("key")
461
462 untouched_key_name = "key"
463 if not module.check_mode:
464 untouched_key_name = "name"
465 raw_return_value["untouched"] = [x for x in before if x in after]
466
467 added = [x.get("key") for x in raw_return_value["added"]]
468 updated = [x.get("key") for x in raw_return_value["updated"]]
469 removed = [x.get("key") for x in raw_return_value["removed"]]
470 untouched = [x.get(untouched_key_name) for x in raw_return_value["untouched"]]
471 return_value = dict(added=added, updated=updated, removed=removed, untouched=untouched)
472
473 module.exit_json(changed=changed, group_variable=return_value)
474
475
476 if __name__ == "__main__":
477 main()