Debian Codegraph @

ansible_collections/community/general/plugins/modules/bitbucket_pipeline_variable.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_pipeline_variable
11 short_description: Manages Bitbucket pipeline variables
12 description:
13 - Manages Bitbucket pipeline variables.
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 name:
37 description:
38 - The pipeline variable name.
39 type: str
40 required: true
41 value:
42 description:
43 - The pipeline variable value.
44 type: str
45 secured:
46 description:
47 - Whether to encrypt the variable value.
48 type: bool
49 default: false
50 state:
51 description:
52 - Indicates desired state of the variable.
53 type: str
54 required: true
55 choices: [absent, present]
56 notes:
57 - Check mode is supported.
58 - For secured values return parameter RV(ignore:changed) is always V(true).
59 """
60
61 EXAMPLES = r"""
62 - name: Create or update pipeline variables from the list
63 community.general.bitbucket_pipeline_variable:
64 repository: 'bitbucket-repo'
65 workspace: bitbucket_workspace
66 name: '{{ item.name }}'
67 value: '{{ item.value }}'
68 secured: '{{ item.secured }}'
69 state: present
70 with_items:
71 - {name: AWS_ACCESS_KEY, value: ABCD1234, secured: false}
72 - {name: AWS_SECRET, value: qwe789poi123vbn0, secured: true}
73
74 - name: Remove pipeline variable
75 community.general.bitbucket_pipeline_variable:
76 repository: bitbucket-repo
77 workspace: bitbucket_workspace
78 name: AWS_ACCESS_KEY
79 state: absent
80 """
81
82 RETURN = r""" # """
83
84 from ansible.module_utils.basic import AnsibleModule, _load_params
85
86 from ansible_collections.community.general.plugins.module_utils._bitbucket import BitbucketHelper
87
88 error_messages = {
89 "required_value": "`value` is required when the `state` is `present`",
90 }
91
92 BITBUCKET_API_ENDPOINTS = {
93 "pipeline-variable-list": f"{BitbucketHelper.BITBUCKET_API_URL}/2.0/repositories/{{workspace}}/{{repo_slug}}/pipelines_config/variables/",
94 "pipeline-variable-detail": (
95 f"{BitbucketHelper.BITBUCKET_API_URL}/2.0/repositories/{{workspace}}/{{repo_slug}}/pipelines_config/variables/{{variable_uuid}}"
96 ),
97 }
98
99
100 def get_existing_pipeline_variable(module, bitbucket):
101 """
102 Search for a pipeline variable
103
104 :param module: instance of the :class:`AnsibleModule`
105 :param bitbucket: instance of the :class:`BitbucketHelper`
106 :return: existing variable or None if not found
107 :rtype: dict or None
108
109 Return example::
110
111 {
112 'name': 'AWS_ACCESS_OBKEY_ID',
113 'value': 'x7HU80-a2',
114 'type': 'pipeline_variable',
115 'secured': False,
116 'uuid': '{9ddb0507-439a-495a-99f3-5464f15128127}'
117 }
118
119 The `value` key in dict is absent in case of secured variable.
120 """
121 variables_base_url = BITBUCKET_API_ENDPOINTS["pipeline-variable-list"].format(
122 workspace=module.params["workspace"],
123 repo_slug=module.params["repository"],
124 )
125 # Look through the all response pages in search of variable we need
126 page = 1
127 while True:
128 next_url = f"{variables_base_url}?page={page}"
129 info, content = bitbucket.request(
130 api_url=next_url,
131 method="GET",
132 )
133
134 if info["status"] == 404:
135 module.fail_json(msg="Invalid `repository` or `workspace`.")
136
137 if info["status"] != 200:
138 module.fail_json(msg=f"Failed to retrieve the list of pipeline variables: {info}")
139
140 # We are at the end of list
141 if "pagelen" in content and content["pagelen"] == 0:
142 return None
143
144 page += 1
145 var = next((v for v in content["values"] if v["key"] == module.params["name"]), None)
146
147 if var is not None:
148 var["name"] = var.pop("key")
149 return var
150
151
152 def create_pipeline_variable(module, bitbucket):
153 info, content = bitbucket.request(
154 api_url=BITBUCKET_API_ENDPOINTS["pipeline-variable-list"].format(
155 workspace=module.params["workspace"],
156 repo_slug=module.params["repository"],
157 ),
158 method="POST",
159 data={
160 "key": module.params["name"],
161 "value": module.params["value"],
162 "secured": module.params["secured"],
163 },
164 )
165
166 if info["status"] != 201:
167 module.fail_json(msg=f"Failed to create pipeline variable `{module.params['name']}`: {info}")
168
169
170 def update_pipeline_variable(module, bitbucket, variable_uuid):
171 info, content = bitbucket.request(
172 api_url=BITBUCKET_API_ENDPOINTS["pipeline-variable-detail"].format(
173 workspace=module.params["workspace"],
174 repo_slug=module.params["repository"],
175 variable_uuid=variable_uuid,
176 ),
177 method="PUT",
178 data={
179 "value": module.params["value"],
180 "secured": module.params["secured"],
181 },
182 )
183
184 if info["status"] != 200:
185 module.fail_json(msg=f"Failed to update pipeline variable `{module.params['name']}`: {info}")
186
187
188 def delete_pipeline_variable(module, bitbucket, variable_uuid):
189 info, content = bitbucket.request(
190 api_url=BITBUCKET_API_ENDPOINTS["pipeline-variable-detail"].format(
191 workspace=module.params["workspace"],
192 repo_slug=module.params["repository"],
193 variable_uuid=variable_uuid,
194 ),
195 method="DELETE",
196 )
197
198 if info["status"] != 204:
199 module.fail_json(msg=f"Failed to delete pipeline variable `{module.params['name']}`: {info}")
200
201
202 class BitBucketPipelineVariable(AnsibleModule):
203 def __init__(self, *args, **kwargs):
204 params = _load_params() or {}
205 if params.get("secured"):
206 kwargs["argument_spec"]["value"].update({"no_log": True})
207 super().__init__(*args, **kwargs)
208
209
210 def main():
211 argument_spec = BitbucketHelper.bitbucket_argument_spec()
212 argument_spec.update(
213 repository=dict(type="str", required=True),
214 workspace=dict(type="str", required=True),
215 name=dict(type="str", required=True),
216 value=dict(type="str"),
217 secured=dict(type="bool", default=False),
218 state=dict(type="str", choices=["present", "absent"], required=True),
219 )
220 module = BitBucketPipelineVariable(
221 argument_spec=argument_spec,
222 supports_check_mode=True,
223 required_one_of=BitbucketHelper.bitbucket_required_one_of(),
224 required_together=BitbucketHelper.bitbucket_required_together(),
225 )
226
227 bitbucket = BitbucketHelper(module)
228
229 value = module.params["value"]
230 state = module.params["state"]
231 secured = module.params["secured"]
232
233 # Check parameters
234 if (value is None) and (state == "present"):
235 module.fail_json(msg=error_messages["required_value"])
236
237 # Retrieve access token for authorized API requests
238 bitbucket.fetch_access_token()
239
240 # Retrieve existing pipeline variable (if any)
241 existing_variable = get_existing_pipeline_variable(module, bitbucket)
242 changed = False
243
244 # Create new variable in case it doesn't exists
245 if not existing_variable and (state == "present"):
246 if not module.check_mode:
247 create_pipeline_variable(module, bitbucket)
248 changed = True
249
250 # Update variable if it is secured or the old value does not match the new one
251 elif existing_variable and (state == "present"):
252 if (existing_variable["secured"] != secured) or (existing_variable.get("value") != value):
253 if not module.check_mode:
254 update_pipeline_variable(module, bitbucket, existing_variable["uuid"])
255 changed = True
256
257 # Delete variable
258 elif existing_variable and (state == "absent"):
259 if not module.check_mode:
260 delete_pipeline_variable(module, bitbucket, existing_variable["uuid"])
261 changed = True
262
263 module.exit_json(changed=changed)
264
265
266 if __name__ == "__main__":
267 main()