Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Scaleway Serverless function namespace management module
4 #
5 # Copyright (c) 2022, Guillaume MARTINEZ <[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
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: scaleway_function_namespace
13 short_description: Scaleway Function namespace management
14 version_added: 6.0.0
15 author: Guillaume MARTINEZ (@Lunik)
16 description:
17 - This module manages function namespaces on Scaleway account.
18 extends_documentation_fragment:
19 - community.general._scaleway
20 - community.general._scaleway_waitable_resource
21 - community.general._attributes
22 - community.general._scaleway.actiongroup_scaleway
23 requirements:
24 - passlib[argon2] >= 1.7.4
25
26 attributes:
27 check_mode:
28 support: full
29 diff_mode:
30 support: none
31 action_group:
32 version_added: 11.3.0
33
34 options:
35 state:
36 type: str
37 description:
38 - Indicate desired state of the function namespace.
39 default: present
40 choices:
41 - present
42 - absent
43
44 project_id:
45 type: str
46 description:
47 - Project identifier.
48 required: true
49
50 region:
51 type: str
52 description:
53 - Scaleway region to use (for example V(fr-par)).
54 required: true
55 choices:
56 - fr-par
57 - nl-ams
58 - pl-waw
59
60 name:
61 type: str
62 description:
63 - Name of the function namespace.
64 required: true
65
66 description:
67 description:
68 - Description of the function namespace.
69 type: str
70 default: ''
71
72 environment_variables:
73 description:
74 - Environment variables of the function namespace.
75 - Injected in functions at runtime.
76 type: dict
77 default: {}
78
79 secret_environment_variables:
80 description:
81 - Secret environment variables of the function namespace.
82 - Updating those values does not output a RV(ignore:changed) state in Ansible.
83 - Injected in functions at runtime.
84 type: dict
85 default: {}
86 """
87
88 EXAMPLES = r"""
89 - name: Create a function namespace
90 community.general.scaleway_function_namespace:
91 project_id: '{{ scw_project }}'
92 state: present
93 region: fr-par
94 name: my-awesome-function-namespace
95 environment_variables:
96 MY_VAR: my_value
97 secret_environment_variables:
98 MY_SECRET_VAR: my_secret_value
99 register: function_namespace_creation_task
100
101 - name: Make sure function namespace is deleted
102 community.general.scaleway_function_namespace:
103 project_id: '{{ scw_project }}'
104 state: absent
105 region: fr-par
106 name: my-awesome-function-namespace
107 """
108
109 RETURN = r"""
110 function_namespace:
111 description: The function namespace information.
112 returned: when O(state=present)
113 type: dict
114 sample:
115 description: ""
116 environment_variables:
117 MY_VAR: my_value
118 error_message:
119 id: 531a1fd7-98d2-4a74-ad77-d398324304b8
120 name: my-awesome-function-namespace
121 organization_id: e04e3bdc-015c-4514-afde-9389e9be24b0
122 project_id: d44cea58-dcb7-4c95-bff1-1105acb60a98
123 region: fr-par
124 registry_endpoint: ""
125 registry_namespace_id: ""
126 secret_environment_variables:
127 - key: MY_SECRET_VAR
128 value: $argon2id$v=19$m=65536,t=1,p=2$tb6UwSPWx/rH5Vyxt9Ujfw$5ZlvaIjWwNDPxD9Rdght3NarJz4IETKjpvAU3mMSmFg
129 status: pending
130 """
131
132 from copy import deepcopy
133
134 from ansible.module_utils.basic import AnsibleModule
135
136 from ansible_collections.community.general.plugins.module_utils._scaleway import (
137 SCALEWAY_REGIONS,
138 Scaleway,
139 SecretVariables,
140 resource_attributes_should_be_changed,
141 scaleway_argument_spec,
142 scaleway_waitable_resource_argument_spec,
143 )
144
145 STABLE_STATES = ("ready", "absent")
146
147 MUTABLE_ATTRIBUTES = (
148 "description",
149 "environment_variables",
150 "secret_environment_variables",
151 )
152
153
154 def payload_from_wished_fn(wished_fn):
155 payload = {
156 "project_id": wished_fn["project_id"],
157 "name": wished_fn["name"],
158 "description": wished_fn["description"],
159 "environment_variables": wished_fn["environment_variables"],
160 "secret_environment_variables": SecretVariables.dict_to_list(wished_fn["secret_environment_variables"]),
161 }
162
163 return payload
164
165
166 def absent_strategy(api, wished_fn):
167 changed = False
168
169 fn_list = api.fetch_all_resources("namespaces")
170 fn_lookup = {fn["name"]: fn for fn in fn_list}
171
172 if wished_fn["name"] not in fn_lookup:
173 return changed, {}
174
175 target_fn = fn_lookup[wished_fn["name"]]
176 changed = True
177 if api.module.check_mode:
178 return changed, {"status": "Function namespace would be destroyed"}
179
180 api.wait_to_complete_state_transition(resource=target_fn, stable_states=STABLE_STATES, force_wait=True)
181 response = api.delete(path=f"{api.api_path}/{target_fn['id']}")
182 if not response.ok:
183 api.module.fail_json(msg=f"Error deleting function namespace [{response.status_code}: {response.json}]")
184
185 api.wait_to_complete_state_transition(resource=target_fn, stable_states=STABLE_STATES)
186 return changed, response.json
187
188
189 def present_strategy(api, wished_fn):
190 changed = False
191
192 fn_list = api.fetch_all_resources("namespaces")
193 fn_lookup = {fn["name"]: fn for fn in fn_list}
194
195 payload_fn = payload_from_wished_fn(wished_fn)
196
197 if wished_fn["name"] not in fn_lookup:
198 changed = True
199 if api.module.check_mode:
200 return changed, {"status": "A function namespace would be created."}
201
202 # Create function namespace
203 api.warn(payload_fn)
204 creation_response = api.post(path=api.api_path, data=payload_fn)
205
206 if not creation_response.ok:
207 msg = f"Error during function namespace creation: {creation_response.info['msg']}: '{creation_response.json['message']}' ({creation_response.json})"
208 api.module.fail_json(msg=msg)
209
210 api.wait_to_complete_state_transition(resource=creation_response.json, stable_states=STABLE_STATES)
211 response = api.get(path=f"{api.api_path}/{creation_response.json['id']}")
212 return changed, response.json
213
214 target_fn = fn_lookup[wished_fn["name"]]
215 decoded_target_fn = deepcopy(target_fn)
216 decoded_target_fn["secret_environment_variables"] = SecretVariables.decode(
217 decoded_target_fn["secret_environment_variables"], payload_fn["secret_environment_variables"]
218 )
219
220 patch_payload = resource_attributes_should_be_changed(
221 target=decoded_target_fn,
222 wished=payload_fn,
223 verifiable_mutable_attributes=MUTABLE_ATTRIBUTES,
224 mutable_attributes=MUTABLE_ATTRIBUTES,
225 )
226
227 if not patch_payload:
228 return changed, target_fn
229
230 changed = True
231 if api.module.check_mode:
232 return changed, {"status": "Function namespace attributes would be changed."}
233
234 fn_patch_response = api.patch(path=f"{api.api_path}/{target_fn['id']}", data=patch_payload)
235
236 if not fn_patch_response.ok:
237 api.module.fail_json(
238 msg=f"Error during function namespace attributes update: [{fn_patch_response.status_code}: {fn_patch_response.json['message']}]"
239 )
240
241 api.wait_to_complete_state_transition(resource=target_fn, stable_states=STABLE_STATES)
242 response = api.get(path=f"{api.api_path}/{target_fn['id']}")
243 return changed, response.json
244
245
246 state_strategy = {"present": present_strategy, "absent": absent_strategy}
247
248
249 def core(module):
250 SecretVariables.ensure_scaleway_secret_package(module)
251
252 region = module.params["region"]
253 wished_function_namespace = {
254 "state": module.params["state"],
255 "project_id": module.params["project_id"],
256 "name": module.params["name"],
257 "description": module.params["description"],
258 "environment_variables": module.params["environment_variables"],
259 "secret_environment_variables": module.params["secret_environment_variables"],
260 }
261
262 api = Scaleway(module=module)
263 api.api_path = f"functions/v1beta1/regions/{region}/namespaces"
264
265 changed, summary = state_strategy[wished_function_namespace["state"]](api=api, wished_fn=wished_function_namespace)
266
267 module.exit_json(changed=changed, function_namespace=summary)
268
269
270 def main():
271 argument_spec = scaleway_argument_spec()
272 argument_spec.update(scaleway_waitable_resource_argument_spec())
273 argument_spec.update(
274 dict(
275 state=dict(type="str", default="present", choices=["absent", "present"]),
276 project_id=dict(type="str", required=True),
277 region=dict(type="str", required=True, choices=SCALEWAY_REGIONS),
278 name=dict(type="str", required=True),
279 description=dict(type="str", default=""),
280 environment_variables=dict(type="dict", default={}),
281 secret_environment_variables=dict(type="dict", default={}, no_log=True),
282 )
283 )
284 module = AnsibleModule(
285 argument_spec=argument_spec,
286 supports_check_mode=True,
287 )
288
289 core(module)
290
291
292 if __name__ == "__main__":
293 main()