Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Scaleway Serverless container 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_container
13 short_description: Scaleway Container management
14 version_added: 6.0.0
15 author: Guillaume MARTINEZ (@Lunik)
16 description:
17 - This module manages container 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 container.
39 default: present
40 choices:
41 - present
42 - absent
43
44 namespace_id:
45 type: str
46 description:
47 - Container namespace 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 container namespace.
64 required: true
65
66 description:
67 description:
68 - Description of the container namespace.
69 type: str
70 default: ''
71
72 min_scale:
73 description:
74 - Minimum number of replicas for the container.
75 type: int
76
77 max_scale:
78 description:
79 - Maximum number of replicas for the container.
80 type: int
81
82 environment_variables:
83 description:
84 - Environment variables of the container namespace.
85 - Injected in container at runtime.
86 type: dict
87 default: {}
88
89 secret_environment_variables:
90 description:
91 - Secret environment variables of the container namespace.
92 - Updating those values does not output a RV(ignore:changed) state in Ansible.
93 - Injected in container at runtime.
94 type: dict
95 default: {}
96
97 cpu_limit:
98 description:
99 - Resources define performance characteristics of your container.
100 - They are allocated to your container at runtime.
101 - Unit is 1/1000 of a VCPU.
102 type: int
103 version_added: 11.3.0
104
105 memory_limit:
106 description:
107 - Resources define performance characteristics of your container.
108 - They are allocated to your container at runtime.
109 - Unit is MB of memory.
110 type: int
111
112 container_timeout:
113 description:
114 - The length of time your handler can spend processing a request before being stopped.
115 type: str
116
117 privacy:
118 description:
119 - Privacy policies define whether a container can be executed anonymously.
120 - Choose V(public) to enable anonymous execution, or V(private) to protect your container with an authentication mechanism
121 provided by the Scaleway API.
122 type: str
123 default: public
124 choices:
125 - public
126 - private
127
128 registry_image:
129 description:
130 - The name of image used for the container.
131 type: str
132 required: true
133
134 max_concurrency:
135 description:
136 - Maximum number of connections per container.
137 - This parameter is used to trigger autoscaling.
138 type: int
139
140 protocol:
141 description:
142 - Communication protocol of the container.
143 type: str
144 default: http1
145 choices:
146 - http1
147 - h2c
148
149 port:
150 description:
151 - Listen port used to expose the container.
152 type: int
153
154 redeploy:
155 description:
156 - Redeploy the container if update is required.
157 type: bool
158 default: false
159 """
160
161 EXAMPLES = r"""
162 - name: Create a container
163 community.general.scaleway_container:
164 namespace_id: '{{ scw_container_namespace }}'
165 state: present
166 region: fr-par
167 name: my-awesome-container
168 registry_image: rg.fr-par.scw.cloud/funcscwtestrgy2f9zw/nginx:latest
169 environment_variables:
170 MY_VAR: my_value
171 secret_environment_variables:
172 MY_SECRET_VAR: my_secret_value
173 register: container_creation_task
174
175 - name: Make sure container is deleted
176 community.general.scaleway_container:
177 namespace_id: '{{ scw_container_namespace }}'
178 state: absent
179 region: fr-par
180 name: my-awesome-container
181 """
182
183 RETURN = r"""
184 container:
185 description: The container information.
186 returned: when O(state=present)
187 type: dict
188 sample:
189 cpu_limit: 140
190 description: Container used for testing scaleway_container ansible module
191 domain_name: cnansibletestgfogtjod-cn-ansible-test.functions.fnc.fr-par.scw.cloud
192 environment_variables:
193 MY_VAR: my_value
194 error_message: null
195 http_option: ""
196 id: c9070eb0-d7a4-48dd-9af3-4fb139890721
197 max_concurrency: 50
198 max_scale: 5
199 memory_limit: 256
200 min_scale: 0
201 name: cn-ansible-test
202 namespace_id: 75e299f1-d1e5-4e6b-bc6e-4fb51cfe1e69
203 port: 80
204 privacy: public
205 protocol: http1
206 region: fr-par
207 registry_image: rg.fr-par.scw.cloud/namespace-ansible-ci/nginx:latest
208 secret_environment_variables:
209 - key: MY_SECRET_VAR
210 value: $argon2id$v=19$m=65536,t=1,p=2$tb6UwSPWx/rH5Vyxt9Ujfw$5ZlvaIjWwNDPxD9Rdght3NarJz4IETKjpvAU3mMSmFg
211 status: created
212 timeout: 300s
213 """
214
215 from copy import deepcopy
216
217 from ansible.module_utils.basic import AnsibleModule
218
219 from ansible_collections.community.general.plugins.module_utils._scaleway import (
220 SCALEWAY_REGIONS,
221 Scaleway,
222 SecretVariables,
223 resource_attributes_should_be_changed,
224 scaleway_argument_spec,
225 scaleway_waitable_resource_argument_spec,
226 )
227
228 STABLE_STATES = ("ready", "created", "absent")
229
230 MUTABLE_ATTRIBUTES = (
231 "description",
232 "min_scale",
233 "max_scale",
234 "environment_variables",
235 "cpu_limit",
236 "memory_limit",
237 "timeout",
238 "privacy",
239 "registry_image",
240 "max_concurrency",
241 "protocol",
242 "port",
243 "secret_environment_variables",
244 )
245
246
247 def payload_from_wished_cn(wished_cn):
248 payload = {
249 "namespace_id": wished_cn["namespace_id"],
250 "name": wished_cn["name"],
251 "description": wished_cn["description"],
252 "min_scale": wished_cn["min_scale"],
253 "max_scale": wished_cn["max_scale"],
254 "environment_variables": wished_cn["environment_variables"],
255 "secret_environment_variables": SecretVariables.dict_to_list(wished_cn["secret_environment_variables"]),
256 "cpu_limit": wished_cn["cpu_limit"],
257 "memory_limit": wished_cn["memory_limit"],
258 "timeout": wished_cn["timeout"],
259 "privacy": wished_cn["privacy"],
260 "registry_image": wished_cn["registry_image"],
261 "max_concurrency": wished_cn["max_concurrency"],
262 "protocol": wished_cn["protocol"],
263 "port": wished_cn["port"],
264 "redeploy": wished_cn["redeploy"],
265 }
266
267 return payload
268
269
270 def absent_strategy(api, wished_cn):
271 changed = False
272
273 cn_list = api.fetch_all_resources("containers")
274 cn_lookup = {cn["name"]: cn for cn in cn_list}
275
276 if wished_cn["name"] not in cn_lookup:
277 return changed, {}
278
279 target_cn = cn_lookup[wished_cn["name"]]
280 changed = True
281 if api.module.check_mode:
282 return changed, {"status": "Container would be destroyed"}
283
284 api.wait_to_complete_state_transition(resource=target_cn, stable_states=STABLE_STATES, force_wait=True)
285 response = api.delete(path=f"{api.api_path}/{target_cn['id']}")
286 if not response.ok:
287 api.module.fail_json(msg=f"Error deleting container [{response.status_code}: {response.json}]")
288
289 api.wait_to_complete_state_transition(resource=target_cn, stable_states=STABLE_STATES)
290 return changed, response.json
291
292
293 def present_strategy(api, wished_cn):
294 changed = False
295
296 cn_list = api.fetch_all_resources("containers")
297 cn_lookup = {cn["name"]: cn for cn in cn_list}
298
299 payload_cn = payload_from_wished_cn(wished_cn)
300
301 if wished_cn["name"] not in cn_lookup:
302 changed = True
303 if api.module.check_mode:
304 return changed, {"status": "A container would be created."}
305
306 # Creation doesn't support `redeploy` parameter
307 del payload_cn["redeploy"]
308
309 # Create container
310 api.warn(payload_cn)
311 creation_response = api.post(path=api.api_path, data=payload_cn)
312
313 if not creation_response.ok:
314 msg = f"Error during container creation: {creation_response.info['msg']}: '{creation_response.json['message']}' ({creation_response.json})"
315 api.module.fail_json(msg=msg)
316
317 api.wait_to_complete_state_transition(resource=creation_response.json, stable_states=STABLE_STATES)
318 response = api.get(path=f"{api.api_path}/{creation_response.json['id']}")
319 return changed, response.json
320
321 target_cn = cn_lookup[wished_cn["name"]]
322 decoded_target_cn = deepcopy(target_cn)
323 decoded_target_cn["secret_environment_variables"] = SecretVariables.decode(
324 decoded_target_cn["secret_environment_variables"], payload_cn["secret_environment_variables"]
325 )
326 patch_payload = resource_attributes_should_be_changed(
327 target=decoded_target_cn,
328 wished=payload_cn,
329 verifiable_mutable_attributes=MUTABLE_ATTRIBUTES,
330 mutable_attributes=MUTABLE_ATTRIBUTES,
331 )
332
333 if not patch_payload:
334 return changed, target_cn
335
336 changed = True
337 if api.module.check_mode:
338 return changed, {"status": "Container attributes would be changed."}
339
340 cn_patch_response = api.patch(path=f"{api.api_path}/{target_cn['id']}", data=patch_payload)
341
342 if not cn_patch_response.ok:
343 api.module.fail_json(
344 msg=f"Error during container attributes update: [{cn_patch_response.status_code}: {cn_patch_response.json['message']}]"
345 )
346
347 api.wait_to_complete_state_transition(resource=target_cn, stable_states=STABLE_STATES)
348 response = api.get(path=f"{api.api_path}/{target_cn['id']}")
349 return changed, response.json
350
351
352 state_strategy = {"present": present_strategy, "absent": absent_strategy}
353
354
355 def core(module):
356 SecretVariables.ensure_scaleway_secret_package(module)
357
358 region = module.params["region"]
359 wished_container = {
360 "state": module.params["state"],
361 "namespace_id": module.params["namespace_id"],
362 "name": module.params["name"],
363 "description": module.params["description"],
364 "min_scale": module.params["min_scale"],
365 "max_scale": module.params["max_scale"],
366 "environment_variables": module.params["environment_variables"],
367 "secret_environment_variables": module.params["secret_environment_variables"],
368 "cpu_limit": module.params["cpu_limit"],
369 "memory_limit": module.params["memory_limit"],
370 "timeout": module.params["container_timeout"],
371 "privacy": module.params["privacy"],
372 "registry_image": module.params["registry_image"],
373 "max_concurrency": module.params["max_concurrency"],
374 "protocol": module.params["protocol"],
375 "port": module.params["port"],
376 "redeploy": module.params["redeploy"],
377 }
378
379 api = Scaleway(module=module)
380 api.api_path = f"containers/v1beta1/regions/{region}/containers"
381
382 changed, summary = state_strategy[wished_container["state"]](api=api, wished_cn=wished_container)
383
384 module.exit_json(changed=changed, container=summary)
385
386
387 def main():
388 argument_spec = scaleway_argument_spec()
389 argument_spec.update(scaleway_waitable_resource_argument_spec())
390 argument_spec.update(
391 dict(
392 state=dict(type="str", default="present", choices=["absent", "present"]),
393 namespace_id=dict(type="str", required=True),
394 region=dict(type="str", required=True, choices=SCALEWAY_REGIONS),
395 name=dict(type="str", required=True),
396 description=dict(type="str", default=""),
397 min_scale=dict(type="int"),
398 max_scale=dict(type="int"),
399 cpu_limit=dict(type="int"),
400 memory_limit=dict(type="int"),
401 container_timeout=dict(type="str"),
402 privacy=dict(type="str", default="public", choices=["public", "private"]),
403 registry_image=dict(type="str", required=True),
404 max_concurrency=dict(type="int"),
405 protocol=dict(type="str", default="http1", choices=["http1", "h2c"]),
406 port=dict(type="int"),
407 redeploy=dict(type="bool", default=False),
408 environment_variables=dict(type="dict", default={}),
409 secret_environment_variables=dict(type="dict", default={}, no_log=True),
410 )
411 )
412 module = AnsibleModule(
413 argument_spec=argument_spec,
414 supports_check_mode=True,
415 )
416
417 core(module)
418
419
420 if __name__ == "__main__":
421 main()