Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # (c) 2018, Chris Houseknecht <@chouseknecht>
5 # (c) 2021, Aubin Bikouo <@abikouo>
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12
13 DOCUMENTATION = r"""
14
15 module: k8s
16
17 short_description: Manage Kubernetes (K8s) objects
18
19 author:
20 - "Chris Houseknecht (@chouseknecht)"
21 - "Fabian von Feilitzsch (@fabianvf)"
22
23 description:
24 - Use the Kubernetes Python client to perform CRUD operations on K8s objects.
25 - Pass the object definition from a source file or inline. See examples for reading
26 files and using Jinja templates or vault-encrypted files.
27 - Access to the full range of K8s APIs.
28 - Use the M(kubernetes.core.k8s_info) module to obtain a list of items about an object of type C(kind)
29 - Authenticate using either a config file, certificates, password or token.
30 - Supports check mode.
31
32 extends_documentation_fragment:
33 - kubernetes.core.k8s_name_options
34 - kubernetes.core.k8s_resource_options
35 - kubernetes.core.k8s_auth_options
36 - kubernetes.core.k8s_wait_options
37 - kubernetes.core.k8s_delete_options
38
39 options:
40 state:
41 description:
42 - Determines if an object should be created, patched, or deleted. When set to C(present), an object will be
43 created, if it does not already exist. If set to C(absent), an existing object will be deleted. If set to
44 C(present), an existing object will be patched, if its attributes differ from those specified using
45 I(resource_definition) or I(src).
46 - C(patched) state is an existing resource that has a given patch applied. If the resource doesn't exist, silently skip it (do not raise an error).
47 type: str
48 default: present
49 choices: [ absent, present, patched ]
50 force:
51 description:
52 - If set to C(yes), and I(state) is C(present), an existing object will be replaced.
53 type: bool
54 default: no
55 merge_type:
56 description:
57 - Whether to override the default patch merge approach with a specific type. By default, the strategic
58 merge will typically be used.
59 - For example, Custom Resource Definitions typically aren't updatable by the usual strategic merge. You may
60 want to use C(merge) if you see "strategic merge patch format is not supported".
61 - See U(https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment)
62 - If more than one C(merge_type) is given, the merge_types will be tried in order. This defaults to
63 C(['strategic-merge', 'merge']), which is ideal for using the same parameters on resource kinds that
64 combine Custom Resources and built-in resources.
65 - Mutually exclusive with C(apply).
66 - I(merge_type=json) has been removed in version 4.0.0. Please use M(kubernetes.core.k8s_json_patch) instead.
67 choices:
68 - merge
69 - strategic-merge
70 type: list
71 elements: str
72 validate:
73 description:
74 - how (if at all) to validate the resource definition against the kubernetes schema.
75 Requires the kubernetes-validate python module.
76 suboptions:
77 fail_on_error:
78 description: whether to fail on validation errors.
79 type: bool
80 version:
81 description: version of Kubernetes to validate against. defaults to Kubernetes server version
82 type: str
83 strict:
84 description: whether to fail when passing unexpected properties
85 default: True
86 type: bool
87 type: dict
88 append_hash:
89 description:
90 - Whether to append a hash to a resource name for immutability purposes
91 - Applies only to ConfigMap and Secret resources
92 - The parameter will be silently ignored for other resource kinds
93 - The full definition of an object is needed to generate the hash - this means that deleting an object created with append_hash
94 will only work if the same object is passed with state=absent (alternatively, just use state=absent with the name including
95 the generated hash and append_hash=no)
96 default: False
97 type: bool
98 apply:
99 description:
100 - C(apply) compares the desired resource definition with the previously supplied resource definition,
101 ignoring properties that are automatically generated
102 - C(apply) works better with Services than 'force=yes'
103 - Mutually exclusive with C(merge_type).
104 default: False
105 type: bool
106 template:
107 description:
108 - Provide a valid YAML template definition file for an object when creating or updating.
109 - Value can be provided as string or dictionary.
110 - The parameter accepts multiple template files. Added in version 2.0.0.
111 - Mutually exclusive with C(src) and C(resource_definition).
112 - Template files needs to be present on the Ansible Controller's file system.
113 - Additional parameters can be specified using dictionary.
114 - 'Valid additional parameters - '
115 - 'C(newline_sequence) (str): Specify the newline sequence to use for templating files.
116 valid choices are "\n", "\r", "\r\n". Default value "\n".'
117 - 'C(block_start_string) (str): The string marking the beginning of a block.
118 Default value "{%".'
119 - 'C(block_end_string) (str): The string marking the end of a block.
120 Default value "%}".'
121 - 'C(variable_start_string) (str): The string marking the beginning of a print statement.
122 Default value "{{".'
123 - 'C(variable_end_string) (str): The string marking the end of a print statement.
124 Default value "}}".'
125 - 'C(trim_blocks) (bool): Determine when newlines should be removed from blocks. When set to C(yes) the first newline
126 after a block is removed (block, not variable tag!). Default value is true.'
127 - 'C(lstrip_blocks) (bool): Determine when leading spaces and tabs should be stripped.
128 When set to C(yes) leading spaces and tabs are stripped from the start of a line to a block.
129 This functionality requires Jinja 2.7 or newer. Default value is false.'
130 type: raw
131 continue_on_error:
132 description:
133 - Whether to continue on creation/deletion errors when multiple resources are defined.
134 - This has no effect on the validation step which is controlled by the C(validate.fail_on_error) parameter.
135 type: bool
136 default: False
137 version_added: 2.0.0
138 label_selectors:
139 description:
140 - Selector (label query) to filter on.
141 type: list
142 elements: str
143 version_added: 2.2.0
144 generate_name:
145 description:
146 - Use to specify the basis of an object name and random characters will be added automatically on server to generate a unique name.
147 - This option is ignored when I(state) is not set to C(present) or when I(apply) is set to C(yes).
148 - If I(resource definition) is provided, the I(metadata.generateName) value from the I(resource_definition)
149 will override this option.
150 - If I(resource definition) is provided, and contains I(metadata.name), this option is ignored.
151 - mutually exclusive with C(name).
152 type: str
153 version_added: 2.3.0
154 server_side_apply:
155 description:
156 - When this option is set, apply runs in the server instead of the client.
157 - Ignored if C(apply) is not set or is set to False.
158 - This option requires "kubernetes >= 19.15.0".
159 type: dict
160 version_added: 2.3.0
161 suboptions:
162 field_manager:
163 type: str
164 description:
165 - Name of the manager used to track field ownership.
166 required: True
167 force_conflicts:
168 description:
169 - A conflict is a special status error that occurs when an Server Side Apply operation tries to change a field,
170 which another user also claims to manage.
171 - When set to True, server-side apply will force the changes against conflicts.
172 type: bool
173 default: False
174 delete_all:
175 description:
176 - When this option is set to I(true) and I(state=absent),
177 module will delete all resources of the specified resource type in the requested namespace.
178 - Ignored when C(state) is not set to I(absent) or when one of (src),
179 C(name) or C(resource_definition) is provided.
180 - Parameter C(kind) is required to use this option.
181 - This parameter can be used with C(label_selectors) to restrict the resources to be deleted.
182 type: bool
183 default: false
184 version_added: 3.0.0
185 aliases:
186 - all
187 hidden_fields:
188 description:
189 - Hide fields matching this option in the result
190 - An example might be C(hidden_fields=[metadata.managedFields])
191 or V(hidden_fields=[spec.containers[0].env[3].value])
192 or V(hidden_fields=[metadata.annotations[kubectl.kubernetes.io/last-applied-configuration]])
193 type: list
194 elements: str
195 version_added: 3.0.0
196
197 requirements:
198 - "python >= 3.9"
199 - "kubernetes >= 24.2.0"
200 - "PyYAML >= 3.11"
201 - "jsonpatch"
202 """
203
204 EXAMPLES = r"""
205 - name: Create a k8s namespace
206 kubernetes.core.k8s:
207 name: testing
208 api_version: v1
209 kind: Namespace
210 state: present
211
212 - name: Create a Service object from an inline definition
213 kubernetes.core.k8s:
214 state: present
215 definition:
216 apiVersion: v1
217 kind: Service
218 metadata:
219 name: web
220 namespace: testing
221 labels:
222 app: galaxy
223 service: web
224 spec:
225 selector:
226 app: galaxy
227 service: web
228 ports:
229 - protocol: TCP
230 targetPort: 8000
231 name: port-8000-tcp
232 port: 8000
233
234 - name: Remove an existing Service object
235 kubernetes.core.k8s:
236 state: absent
237 api_version: v1
238 kind: Service
239 namespace: testing
240 name: web
241
242 # Passing the object definition from a file
243
244 - name: Create a Deployment by reading the definition from a local file
245 kubernetes.core.k8s:
246 state: present
247 src: /testing/deployment.yml
248
249 - name: >-
250 Read definition file from the Ansible controller file system.
251 If the definition file has been encrypted with Ansible Vault it will automatically be decrypted.
252 kubernetes.core.k8s:
253 state: present
254 definition: "{{ lookup('file', '/testing/deployment.yml') | from_yaml }}"
255
256 - name: >-
257 (Alternative) Read definition file from the Ansible controller file system.
258 In this case, the definition file contains multiple YAML documents, separated by ---.
259 If the definition file has been encrypted with Ansible Vault it will automatically be decrypted.
260 kubernetes.core.k8s:
261 state: present
262 definition: "{{ lookup('file', '/testing/deployment.yml') | from_yaml_all }}"
263
264 - name: Read definition template file from the Ansible controller file system
265 kubernetes.core.k8s:
266 state: present
267 template: '/testing/deployment.j2'
268
269 - name: Read definition template file from the Ansible controller file system that uses custom start/end strings
270 kubernetes.core.k8s:
271 state: present
272 template:
273 path: '/testing/deployment.j2'
274 variable_start_string: '[['
275 variable_end_string: ']]'
276
277 - name: Read multiple definition template file from the Ansible controller file system
278 kubernetes.core.k8s:
279 state: present
280 template:
281 - path: '/testing/deployment_one.j2'
282 - path: '/testing/deployment_two.j2'
283 variable_start_string: '[['
284 variable_end_string: ']]'
285
286 - name: fail on validation errors
287 kubernetes.core.k8s:
288 state: present
289 definition: "{{ lookup('template', '/testing/deployment.yml') | from_yaml }}"
290 validate:
291 fail_on_error: yes
292
293 - name: warn on validation errors, check for unexpected properties
294 kubernetes.core.k8s:
295 state: present
296 definition: "{{ lookup('template', '/testing/deployment.yml') | from_yaml }}"
297 validate:
298 fail_on_error: no
299 strict: yes
300
301 # Download and apply manifest
302 - name: Download metrics-server manifest to the cluster.
303 ansible.builtin.get_url:
304 url: https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
305 dest: ~/metrics-server.yaml
306 mode: '0664'
307
308 - name: Apply metrics-server manifest to the cluster.
309 kubernetes.core.k8s:
310 state: present
311 src: ~/metrics-server.yaml
312
313 # Wait for a Deployment to pause before continuing
314 - name: Pause a Deployment.
315 kubernetes.core.k8s:
316 definition:
317 apiVersion: apps/v1
318 kind: Deployment
319 metadata:
320 name: example
321 namespace: testing
322 spec:
323 paused: True
324 wait: yes
325 wait_condition:
326 type: Progressing
327 status: Unknown
328 reason: DeploymentPaused
329
330 # Patch existing namespace : add label
331 - name: add label to existing namespace
332 kubernetes.core.k8s:
333 state: patched
334 kind: Namespace
335 name: patch_namespace
336 definition:
337 metadata:
338 labels:
339 support: patch
340
341 # Create object using generateName
342 - name: create resource using name generated by the server
343 kubernetes.core.k8s:
344 state: present
345 generate_name: pod-
346 definition:
347 apiVersion: v1
348 kind: Pod
349 spec:
350 containers:
351 - name: py
352 image: python:3.7-alpine
353 imagePullPolicy: IfNotPresent
354
355 # Server side apply
356 - name: Create configmap using server side apply
357 kubernetes.core.k8s:
358 namespace: testing
359 definition:
360 apiVersion: v1
361 kind: ConfigMap
362 metadata:
363 name: my-configmap
364 apply: yes
365 server_side_apply:
366 field_manager: ansible
367
368 # Delete all Deployment from specified namespace
369 - name: Delete all Deployment from specified namespace
370 kubernetes.core.k8s:
371 api_version: apps/v1
372 namespace: testing
373 kind: Deployment
374 delete_all: true
375 """
376
377 RETURN = r"""
378 result:
379 description:
380 - The created, patched, or otherwise present object. Will be empty in the case of a deletion.
381 returned: success
382 type: complex
383 contains:
384 api_version:
385 description: The versioned schema of this representation of an object.
386 returned: when O(resource_definition) or O(src) contains a single object.
387 type: str
388 kind:
389 description: Represents the REST resource this object represents.
390 returned: when O(resource_definition) or O(src) contains a single object.
391 type: str
392 metadata:
393 description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
394 returned: when O(resource_definition) or O(src) contains a single object.
395 type: complex
396 spec:
397 description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
398 returned: when O(resource_definition) or O(src) contains a single object.
399 type: complex
400 status:
401 description: Current status details for the object.
402 returned: when O(resource_definition) or O(src) contains a single object.
403 type: complex
404 duration:
405 description: elapsed time of task in seconds
406 returned: when C(wait) is true
407 type: int
408 sample: 48
409 error:
410 description: error while trying to create/delete the object.
411 returned: error
412 type: complex
413 results:
414 description: An array of created, patched, or otherwise present objects.
415 returned: when O(resource_definition) or O(src) contains a list of objects.
416 type: complex
417 contains:
418 api_version:
419 description: The versioned schema of this representation of an object.
420 returned: when O(resource_definition) or O(src) contains a single object.
421 type: str
422 kind:
423 description: Represents the REST resource this object represents.
424 returned: when O(resource_definition) or O(src) contains a single object.
425 type: str
426 metadata:
427 description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
428 returned: when O(resource_definition) or O(src) contains a single object.
429 type: complex
430 spec:
431 description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
432 returned: when O(resource_definition) or O(src) contains a single object.
433 type: complex
434 status:
435 description: Current status details for the object.
436 returned: when O(resource_definition) or O(src) contains a single object.
437 type: complex
438 duration:
439 description: elapsed time of task in seconds
440 returned: when C(wait) is true
441 type: int
442 sample: 48
443 error:
444 description: error while trying to create/delete the object.
445 returned: error
446 type: complex
447 method:
448 description:
449 - The method used to deploy the resource.
450 returned: success
451 type: str
452 sample: create
453 """
454
455 import copy
456
457 from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
458 AnsibleModule,
459 )
460 from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
461 AUTH_ARG_SPEC,
462 DELETE_OPTS_ARG_SPEC,
463 NAME_ARG_SPEC,
464 RESOURCE_ARG_SPEC,
465 WAIT_ARG_SPEC,
466 )
467 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
468 AnsibleK8SModule,
469 )
470 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
471 CoreException,
472 )
473 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.runner import (
474 run_module,
475 )
476
477
478 def validate_spec():
479 return dict(
480 fail_on_error=dict(type="bool"),
481 version=dict(),
482 strict=dict(type="bool", default=True),
483 )
484
485
486 def server_apply_spec():
487 return dict(
488 field_manager=dict(type="str", required=True),
489 force_conflicts=dict(type="bool", default=False),
490 )
491
492
493 def argspec():
494 argument_spec = copy.deepcopy(NAME_ARG_SPEC)
495 argument_spec.update(copy.deepcopy(RESOURCE_ARG_SPEC))
496 argument_spec.update(copy.deepcopy(AUTH_ARG_SPEC))
497 argument_spec.update(copy.deepcopy(WAIT_ARG_SPEC))
498 argument_spec["merge_type"] = dict(
499 type="list", elements="str", choices=["merge", "strategic-merge"]
500 )
501 argument_spec["validate"] = dict(type="dict", default=None, options=validate_spec())
502 argument_spec["append_hash"] = dict(type="bool", default=False)
503 argument_spec["apply"] = dict(type="bool", default=False)
504 argument_spec["template"] = dict(type="raw", default=None)
505 argument_spec["delete_options"] = dict(
506 type="dict", default=None, options=copy.deepcopy(DELETE_OPTS_ARG_SPEC)
507 )
508 argument_spec["continue_on_error"] = dict(type="bool", default=False)
509 argument_spec["state"] = dict(
510 default="present", choices=["present", "absent", "patched"]
511 )
512 argument_spec["force"] = dict(type="bool", default=False)
513 argument_spec["label_selectors"] = dict(type="list", elements="str")
514 argument_spec["generate_name"] = dict()
515 argument_spec["server_side_apply"] = dict(
516 type="dict", default=None, options=server_apply_spec()
517 )
518 argument_spec["delete_all"] = dict(type="bool", default=False, aliases=["all"])
519 argument_spec["hidden_fields"] = dict(type="list", elements="str")
520
521 return argument_spec
522
523
524 def main():
525 mutually_exclusive = [
526 ("resource_definition", "src"),
527 ("merge_type", "apply"),
528 ("template", "resource_definition"),
529 ("template", "src"),
530 ("name", "generate_name"),
531 ]
532
533 module = AnsibleK8SModule(
534 module_class=AnsibleModule,
535 argument_spec=argspec(),
536 mutually_exclusive=mutually_exclusive,
537 supports_check_mode=True,
538 )
539 try:
540 run_module(module)
541 except CoreException as e:
542 module.fail_from_exception(e)
543
544
545 if __name__ == "__main__":
546 main()