Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2023, Benedikt Braunger ([email protected])
4 # Based on code:
5 # Copyright (c) 2020, Florent Madiot ([email protected])
6 # Copyright (c) 2019, Markus Bergholz ([email protected])
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: gitlab_instance_variable
13 short_description: Creates, updates, or deletes GitLab instance variables
14 version_added: 7.1.0
15 description:
16 - Creates a instance variable if it does not exist.
17 - When a instance variable does exist, its value is updated if the values are different.
18 - Support for instance variables requires GitLab >= 13.0.
19 - Variables which are not mentioned in the modules options, but are present on the GitLab instance, either stay (O(purge=false))
20 or are deleted (O(purge=true)).
21 author:
22 - Benedikt Braunger (@benibr)
23 requirements:
24 - python-gitlab python module
25 extends_documentation_fragment:
26 - community.general._auth_basic
27 - community.general._gitlab
28 - community.general._attributes
29
30 attributes:
31 check_mode:
32 support: full
33 diff_mode:
34 support: none
35
36 options:
37 state:
38 description:
39 - Create or delete instance variable.
40 default: present
41 type: str
42 choices: ["present", "absent"]
43 purge:
44 description:
45 - When set to V(true), delete all variables which are not mentioned in the task.
46 default: false
47 type: bool
48 variables:
49 description:
50 - A list of dictionaries that represents CI/CD variables.
51 default: []
52 type: list
53 elements: dict
54 suboptions:
55 name:
56 description:
57 - The name of the variable.
58 type: str
59 required: true
60 value:
61 description:
62 - The variable value.
63 - Required when O(state=present).
64 type: str
65 description:
66 description:
67 - A description for the variable.
68 - Support for descriptions requires GitLab >= 16.8.
69 type: str
70 version_added: '11.4.0'
71 masked:
72 description:
73 - Whether variable value is masked or not.
74 type: bool
75 default: false
76 protected:
77 description:
78 - Whether variable value is protected or not.
79 type: bool
80 default: false
81 raw:
82 description:
83 - Whether variable value is raw or not.
84 - Support for raw values requires GitLab >= 15.7.
85 type: bool
86 default: false
87 version_added: 10.2.0
88 variable_type:
89 description:
90 - Whether a variable is an environment variable (V(env_var)) or a file (V(file)).
91 type: str
92 choices: ["env_var", "file"]
93 default: env_var
94 """
95
96
97 EXAMPLES = r"""
98 - name: Set or update some CI/CD variables
99 community.general.gitlab_instance_variable:
100 api_url: https://gitlab.com
101 api_token: secret_access_token
102 purge: false
103 variables:
104 - name: ACCESS_KEY_ID
105 value: abc1312cba
106 - name: SECRET_ACCESS_KEY
107 value: 1337
108 masked: true
109 protected: true
110 variable_type: env_var
111
112 - name: Delete one variable
113 community.general.gitlab_instance_variable:
114 api_url: https://gitlab.com
115 api_token: secret_access_token
116 state: absent
117 variables:
118 - name: ACCESS_KEY_ID
119 """
120
121 RETURN = r"""
122 instance_variable:
123 description: Four lists of the variablenames which were added, updated, removed or exist.
124 returned: always
125 type: dict
126 contains:
127 added:
128 description: A list of variables which were created.
129 returned: always
130 type: list
131 sample: ["ACCESS_KEY_ID", "SECRET_ACCESS_KEY"]
132 untouched:
133 description: A list of variables which exist.
134 returned: always
135 type: list
136 sample: ["ACCESS_KEY_ID", "SECRET_ACCESS_KEY"]
137 removed:
138 description: A list of variables which were deleted.
139 returned: always
140 type: list
141 sample: ["ACCESS_KEY_ID", "SECRET_ACCESS_KEY"]
142 updated:
143 description: A list pre-existing variables whose values have been set.
144 returned: always
145 type: list
146 sample: ["ACCESS_KEY_ID", "SECRET_ACCESS_KEY"]
147 """
148
149 from ansible.module_utils.api import basic_auth_argument_spec
150 from ansible.module_utils.basic import AnsibleModule
151
152 from ansible_collections.community.general.plugins.module_utils._gitlab import (
153 auth_argument_spec,
154 filter_returned_variables,
155 gitlab_authentication,
156 list_all_kwargs,
157 )
158
159
160 class GitlabInstanceVariables:
161 def __init__(self, module, gitlab_instance):
162 self.instance = gitlab_instance
163 self._module = module
164
165 def list_all_instance_variables(self):
166 return list(self.instance.variables.list(**list_all_kwargs))
167
168 def create_variable(self, var_obj):
169 if self._module.check_mode:
170 return True
171 var = {
172 "key": var_obj.get("key"),
173 "value": var_obj.get("value"),
174 "description": var_obj.get("description"),
175 "masked": var_obj.get("masked"),
176 "protected": var_obj.get("protected"),
177 "raw": var_obj.get("raw"),
178 "variable_type": var_obj.get("variable_type"),
179 }
180
181 self.instance.variables.create(var)
182 return True
183
184 def update_variable(self, var_obj):
185 if self._module.check_mode:
186 return True
187 self.delete_variable(var_obj)
188 self.create_variable(var_obj)
189 return True
190
191 def delete_variable(self, var_obj):
192 if self._module.check_mode:
193 return True
194 self.instance.variables.delete(var_obj.get("key"))
195 return True
196
197
198 def compare(requested_variables, existing_variables, state):
199 # we need to do this, because it was determined in a previous version - more or less buggy
200 # basically it is not necessary and might results in more/other bugs!
201 # but it is required and only relevant for check mode!!
202 # logic represents state 'present' when not purge. all other can be derived from that
203 # untouched => equal in both
204 # updated => name and scope are equal
205 # added => name and scope does not exist
206 untouched = list()
207 updated = list()
208 added = list()
209
210 if state == "present":
211 existing_key_scope_vars = list()
212 for item in existing_variables:
213 existing_key_scope_vars.append({"key": item.get("key")})
214
215 for var in requested_variables:
216 if var in existing_variables:
217 untouched.append(var)
218 else:
219 compare_item = {"key": var.get("name")}
220 if compare_item in existing_key_scope_vars:
221 updated.append(var)
222 else:
223 added.append(var)
224
225 return untouched, updated, added
226
227
228 def native_python_main(this_gitlab, purge, requested_variables, state, module):
229 change = False
230 return_value = dict(added=list(), updated=list(), removed=list(), untouched=list())
231
232 gitlab_keys = this_gitlab.list_all_instance_variables()
233 before = [x.attributes for x in gitlab_keys]
234
235 existing_variables = filter_returned_variables(gitlab_keys)
236
237 for item in requested_variables:
238 item["key"] = item.pop("name")
239 item["value"] = str(item.get("value"))
240 if item.get("protected") is None:
241 item["protected"] = False
242 if item.get("masked") is None:
243 item["masked"] = False
244 if item.get("raw") is None:
245 item["raw"] = False
246 if item.get("variable_type") is None:
247 item["variable_type"] = "env_var"
248
249 if module.check_mode:
250 untouched, updated, added = compare(requested_variables, existing_variables, state)
251
252 if state == "present":
253 add_or_update = [x for x in requested_variables if x not in existing_variables]
254 for item in add_or_update:
255 try:
256 if this_gitlab.create_variable(item):
257 return_value["added"].append(item)
258
259 except Exception:
260 if this_gitlab.update_variable(item):
261 return_value["updated"].append(item)
262
263 if purge:
264 # refetch and filter
265 gitlab_keys = this_gitlab.list_all_instance_variables()
266 existing_variables = filter_returned_variables(gitlab_keys)
267
268 remove = [x for x in existing_variables if x not in requested_variables]
269 for item in remove:
270 if this_gitlab.delete_variable(item):
271 return_value["removed"].append(item)
272
273 elif state == "absent":
274 # value, type, and description do not matter on removing variables.
275 keys_ignored_on_deletion = ["value", "variable_type", "description"]
276 for key in keys_ignored_on_deletion:
277 for item in existing_variables:
278 item.pop(key)
279 for item in requested_variables:
280 item.pop(key)
281
282 if not purge:
283 remove_requested = [x for x in requested_variables if x in existing_variables]
284 for item in remove_requested:
285 if this_gitlab.delete_variable(item):
286 return_value["removed"].append(item)
287
288 else:
289 for item in existing_variables:
290 if this_gitlab.delete_variable(item):
291 return_value["removed"].append(item)
292
293 if module.check_mode:
294 return_value = dict(added=added, updated=updated, removed=return_value["removed"], untouched=untouched)
295
296 if len(return_value["added"] + return_value["removed"] + return_value["updated"]) > 0:
297 change = True
298
299 gitlab_keys = this_gitlab.list_all_instance_variables()
300 after = [x.attributes for x in gitlab_keys]
301
302 return change, return_value, before, after
303
304
305 def main():
306 argument_spec = basic_auth_argument_spec()
307 argument_spec.update(auth_argument_spec())
308 argument_spec.update(
309 purge=dict(type="bool", default=False),
310 variables=dict(
311 type="list",
312 elements="dict",
313 default=list(),
314 options=dict(
315 name=dict(type="str", required=True),
316 value=dict(type="str", no_log=True),
317 description=dict(type="str"),
318 masked=dict(type="bool", default=False),
319 protected=dict(type="bool", default=False),
320 raw=dict(type="bool", default=False),
321 variable_type=dict(type="str", default="env_var", choices=["env_var", "file"]),
322 ),
323 ),
324 state=dict(type="str", default="present", choices=["absent", "present"]),
325 )
326
327 module = AnsibleModule(
328 argument_spec=argument_spec,
329 mutually_exclusive=[
330 ["api_username", "api_token"],
331 ["api_username", "api_oauth_token"],
332 ["api_username", "api_job_token"],
333 ["api_token", "api_oauth_token"],
334 ["api_token", "api_job_token"],
335 ],
336 required_together=[
337 ["api_username", "api_password"],
338 ],
339 required_one_of=[["api_username", "api_token", "api_oauth_token", "api_job_token"]],
340 supports_check_mode=True,
341 )
342
343 # check prerequisites and connect to gitlab server
344 gitlab_instance = gitlab_authentication(module)
345
346 purge = module.params["purge"]
347 state = module.params["state"]
348
349 variables = module.params["variables"]
350
351 if state == "present":
352 if any(x["value"] is None for x in variables):
353 module.fail_json(msg="value parameter is required in state present")
354
355 this_gitlab = GitlabInstanceVariables(module=module, gitlab_instance=gitlab_instance)
356
357 changed, raw_return_value, before, after = native_python_main(this_gitlab, purge, variables, state, module)
358
359 # postprocessing
360 for item in after:
361 item["name"] = item.pop("key")
362 for item in before:
363 item["name"] = item.pop("key")
364
365 untouched_key_name = "key"
366 if not module.check_mode:
367 untouched_key_name = "name"
368 raw_return_value["untouched"] = [x for x in before if x in after]
369
370 added = [x.get("key") for x in raw_return_value["added"]]
371 updated = [x.get("key") for x in raw_return_value["updated"]]
372 removed = [x.get("key") for x in raw_return_value["removed"]]
373 untouched = [x.get(untouched_key_name) for x in raw_return_value["untouched"]]
374 return_value = dict(added=added, updated=updated, removed=removed, untouched=untouched)
375
376 module.exit_json(changed=changed, instance_variable=return_value)
377
378
379 if __name__ == "__main__":
380 main()