Debian Codegraph @

ansible_collections/kubernetes/core/plugins/modules/k8s_scale.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2018, Chris Houseknecht <@chouseknecht>
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r"""
13
14 module: k8s_scale
15
16 short_description: Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
17
18 author:
19 - "Chris Houseknecht (@chouseknecht)"
20 - "Fabian von Feilitzsch (@fabianvf)"
21
22 description:
23 - Similar to the kubectl scale command. Use to set the number of replicas for a Deployment, ReplicaSet,
24 or Replication Controller, or the parallelism attribute of a Job. Supports check mode.
25 - C(wait) parameter is not supported for Jobs.
26
27 extends_documentation_fragment:
28 - kubernetes.core.k8s_name_options
29 - kubernetes.core.k8s_auth_options
30 - kubernetes.core.k8s_resource_options
31 - kubernetes.core.k8s_scale_options
32
33 options:
34 label_selectors:
35 description: List of label selectors to use to filter results.
36 type: list
37 elements: str
38 default: []
39 version_added: 2.0.0
40 continue_on_error:
41 description:
42 - Whether to continue on errors when multiple resources are defined.
43 type: bool
44 default: False
45 version_added: 2.0.0
46
47 requirements:
48 - "python >= 3.9"
49 - "kubernetes >= 24.2.0"
50 - "PyYAML >= 3.11"
51 """
52
53 EXAMPLES = r"""
54 - name: Scale deployment up, and extend timeout
55 kubernetes.core.k8s_scale:
56 api_version: v1
57 kind: Deployment
58 name: elastic
59 namespace: myproject
60 replicas: 3
61 wait_timeout: 60
62
63 - name: Scale deployment down when current replicas match
64 kubernetes.core.k8s_scale:
65 api_version: v1
66 kind: Deployment
67 name: elastic
68 namespace: myproject
69 current_replicas: 3
70 replicas: 2
71
72 - name: Increase job parallelism
73 kubernetes.core.k8s_scale:
74 api_version: batch/v1
75 kind: job
76 name: pi-with-timeout
77 namespace: testing
78 replicas: 2
79
80 # Match object using local file or inline definition
81
82 - name: Scale deployment based on a file from the local filesystem
83 kubernetes.core.k8s_scale:
84 src: /myproject/elastic_deployment.yml
85 replicas: 3
86 wait: no
87
88 - name: Scale deployment based on a template output
89 kubernetes.core.k8s_scale:
90 resource_definition: "{{ lookup('template', '/myproject/elastic_deployment.yml') | from_yaml }}"
91 replicas: 3
92 wait: no
93
94 - name: Scale deployment based on a file from the Ansible controller filesystem
95 kubernetes.core.k8s_scale:
96 resource_definition: "{{ lookup('file', '/myproject/elastic_deployment.yml') | from_yaml }}"
97 replicas: 3
98 wait: no
99
100 - name: Scale deployment using label selectors (continue operation in case error occured on one resource)
101 kubernetes.core.k8s_scale:
102 replicas: 3
103 kind: Deployment
104 namespace: test
105 label_selectors:
106 - app=test
107 continue_on_error: true
108 """
109
110 RETURN = r"""
111 result:
112 description:
113 - If a change was made, will return the patched object, otherwise returns the existing object.
114 returned: success
115 type: complex
116 contains:
117 api_version:
118 description: The versioned schema of this representation of an object.
119 returned: success
120 type: str
121 kind:
122 description: Represents the REST resource this object represents.
123 returned: success
124 type: str
125 metadata:
126 description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
127 returned: success
128 type: complex
129 spec:
130 description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
131 returned: success
132 type: complex
133 status:
134 description: Current status details for the object.
135 returned: success
136 type: complex
137 duration:
138 description: elapsed time of task in seconds
139 returned: when C(wait) is true
140 type: int
141 sample: 48
142 """
143
144 import copy
145
146 try:
147 from kubernetes.dynamic.exceptions import NotFoundError
148 except ImportError:
149 # Handled in module setup
150 pass
151
152 from ansible.module_utils.common.text.converters import to_native
153 from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
154 AnsibleModule,
155 )
156 from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
157 AUTH_ARG_SPEC,
158 NAME_ARG_SPEC,
159 RESOURCE_ARG_SPEC,
160 )
161 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
162 get_api_client,
163 )
164 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
165 AnsibleK8SModule,
166 )
167 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
168 CoreException,
169 ResourceTimeout,
170 )
171 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
172 create_definitions,
173 )
174 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.service import (
175 diff_objects,
176 )
177 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.waiter import (
178 get_waiter,
179 )
180
181 SCALE_ARG_SPEC = {
182 "replicas": {"type": "int", "required": True},
183 "current_replicas": {"type": "int"},
184 "resource_version": {},
185 "wait": {"type": "bool", "default": True},
186 "wait_timeout": {"type": "int", "default": 20},
187 "wait_sleep": {"type": "int", "default": 5},
188 }
189
190
191 def execute_module(client, module):
192 current_replicas = module.params.get("current_replicas")
193 replicas = module.params.get("replicas")
194 resource_version = module.params.get("resource_version")
195 definitions = create_definitions(module.params)
196 definition = definitions[0]
197 name = definition["metadata"].get("name")
198 namespace = definition["metadata"].get("namespace")
199 api_version = definition["apiVersion"]
200 kind = definition["kind"]
201 label_selectors = module.params.get("label_selectors")
202 if not label_selectors:
203 label_selectors = []
204 continue_on_error = module.params.get("continue_on_error")
205 wait = module.params.get("wait")
206 wait_time = module.params.get("wait_timeout")
207 wait_sleep = module.params.get("wait_sleep")
208 existing = None
209 existing_count = None
210 return_attributes = dict(result=dict())
211 if module._diff:
212 return_attributes["diff"] = dict()
213 if wait:
214 return_attributes["duration"] = 0
215
216 resource = client.resource(kind, api_version)
217 multiple_scale = False
218 try:
219 existing = resource.get(
220 name=name, namespace=namespace, label_selector=",".join(label_selectors)
221 )
222 if existing.kind.endswith("List"):
223 existing_items = existing.items
224 multiple_scale = len(existing_items) > 1
225 else:
226 existing_items = [existing]
227 except NotFoundError as e:
228 reason = e.body if hasattr(e, "body") else e
229 msg = "Failed to retrieve requested object: {0}".format(reason)
230 raise CoreException(msg) from e
231
232 if multiple_scale:
233 # when scaling multiple resource, the 'result' is changed to 'results' and is a list
234 return_attributes = {"results": []}
235 changed = False
236
237 def _continue_or_fail(error):
238 if multiple_scale and continue_on_error:
239 if "errors" not in return_attributes:
240 return_attributes["errors"] = []
241 return_attributes["errors"].append({"error": error, "failed": True})
242 else:
243 module.fail_json(msg=error, **return_attributes)
244
245 def _continue_or_exit(warn):
246 if warn:
247 module.warn(warn)
248 if multiple_scale:
249 return_attributes["results"].append({"changed": False})
250 else:
251 module.exit_json(**return_attributes)
252
253 for existing in existing_items:
254 if kind.lower() == "job":
255 existing_count = existing.spec.parallelism
256 elif hasattr(existing.spec, "replicas"):
257 existing_count = existing.spec.replicas
258
259 if existing_count is None:
260 error = "Failed to retrieve the available count for object kind={0} name={1} namespace={2}.".format(
261 existing.kind, existing.metadata.name, existing.metadata.namespace
262 )
263 _continue_or_fail(error)
264 continue
265
266 if resource_version and resource_version != existing.metadata.resourceVersion:
267 warn = "expected resource version {0} does not match with actual {1} for object kind={2} name={3} namespace={4}.".format(
268 resource_version,
269 existing.metadata.resourceVersion,
270 existing.kind,
271 existing.metadata.name,
272 existing.metadata.namespace,
273 )
274 _continue_or_exit(warn)
275 continue
276
277 if current_replicas is not None and existing_count != current_replicas:
278 warn = "current replicas {0} does not match with actual {1} for object kind={2} name={3} namespace={4}.".format(
279 current_replicas,
280 existing_count,
281 existing.kind,
282 existing.metadata.name,
283 existing.metadata.namespace,
284 )
285 _continue_or_exit(warn)
286 continue
287
288 if existing_count != replicas:
289 if kind.lower() == "job":
290 existing.spec.parallelism = replicas
291 result = {"changed": True}
292 if module.check_mode:
293 result["result"] = existing.to_dict()
294 else:
295 result["result"] = client.patch(
296 resource, existing.to_dict()
297 ).to_dict()
298 else:
299 try:
300 result = scale(
301 client,
302 module,
303 resource,
304 existing,
305 replicas,
306 wait,
307 wait_time,
308 wait_sleep,
309 )
310 except CoreException as e:
311 module.fail_json(msg=to_native(e))
312 changed = changed or result["changed"]
313 else:
314 name = existing.metadata.name
315 namespace = existing.metadata.namespace
316 existing = client.get(resource, name=name, namespace=namespace)
317 result = {"changed": False, "result": existing.to_dict()}
318 if module._diff:
319 result["diff"] = {}
320 if wait:
321 result["duration"] = 0
322 # append result to the return attribute
323 if multiple_scale:
324 return_attributes["results"].append(result)
325 else:
326 module.exit_json(**result)
327
328 module.exit_json(changed=changed, **return_attributes)
329
330
331 def argspec():
332 args = copy.deepcopy(SCALE_ARG_SPEC)
333 args.update(RESOURCE_ARG_SPEC)
334 args.update(NAME_ARG_SPEC)
335 args.update(AUTH_ARG_SPEC)
336 args.update({"label_selectors": {"type": "list", "elements": "str", "default": []}})
337 args.update(({"continue_on_error": {"type": "bool", "default": False}}))
338 return args
339
340
341 def scale(
342 client,
343 module,
344 resource,
345 existing_object,
346 replicas,
347 wait,
348 wait_time,
349 wait_sleep,
350 ):
351 name = existing_object.metadata.name
352 namespace = existing_object.metadata.namespace
353 kind = existing_object.kind
354
355 if not hasattr(resource, "scale"):
356 raise CoreException(
357 "Cannot perform scale on resource of kind {0}".format(resource.kind)
358 )
359
360 scale_obj = {
361 "kind": kind,
362 "metadata": {"name": name, "namespace": namespace},
363 "spec": {"replicas": replicas},
364 }
365
366 existing = client.get(resource, name=name, namespace=namespace)
367
368 result = dict()
369 if module.check_mode:
370 k8s_obj = copy.deepcopy(existing.to_dict())
371 k8s_obj["spec"]["replicas"] = replicas
372 if wait:
373 result["duration"] = 0
374 result["result"] = k8s_obj
375 else:
376 try:
377 resource.scale.patch(body=scale_obj)
378 except Exception as e:
379 reason = e.body if hasattr(e, "body") else e
380 msg = "Scale request failed: {0}".format(reason)
381 raise CoreException(msg) from e
382
383 k8s_obj = client.get(resource, name=name, namespace=namespace).to_dict()
384 result["result"] = k8s_obj
385 if wait:
386 waiter = get_waiter(client, resource)
387 success, result["result"], result["duration"] = waiter.wait(
388 timeout=wait_time,
389 sleep=wait_sleep,
390 name=name,
391 namespace=namespace,
392 )
393 if not success:
394 raise ResourceTimeout("Resource scaling timed out", result)
395
396 match, diffs = diff_objects(existing.to_dict(), result["result"])
397 result["changed"] = not match
398 if module._diff:
399 result["diff"] = diffs
400
401 return result
402
403
404 def main():
405 mutually_exclusive = [
406 ("resource_definition", "src"),
407 ]
408 module = AnsibleK8SModule(
409 module_class=AnsibleModule,
410 argument_spec=argspec(),
411 mutually_exclusive=mutually_exclusive,
412 supports_check_mode=True,
413 )
414
415 try:
416 client = get_api_client(module=module)
417 execute_module(client, module)
418 except CoreException as e:
419 module.fail_from_exception(e)
420
421
422 if __name__ == "__main__":
423 main()