Debian Codegraph @

ansible_collections/community/okd/plugins/modules/k8s.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (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
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12 # STARTREMOVE (downstream)
13 DOCUMENTATION = r"""
14
15 module: k8s
16
17 short_description: Manage OpenShift 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 - Optimized for OKD/OpenShift Kubernetes flavors.
32
33 extends_documentation_fragment:
34 - kubernetes.core.k8s_name_options
35 - kubernetes.core.k8s_resource_options
36 - kubernetes.core.k8s_auth_options
37 - kubernetes.core.k8s_wait_options
38 - kubernetes.core.k8s_delete_options
39
40 options:
41 state:
42 description:
43 - Determines if an object should be created, patched, or deleted. When set to C(present), an object will be
44 created, if it does not already exist. If set to C(absent), an existing object will be deleted. If set to
45 C(present), an existing object will be patched, if its attributes differ from those specified using
46 I(resource_definition) or I(src).
47 - 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).
48 type: str
49 default: present
50 choices: [ absent, present, patched ]
51 force:
52 description:
53 - If set to C(yes), and I(state) is C(present), an existing object will be replaced.
54 type: bool
55 default: no
56 merge_type:
57 description:
58 - Whether to override the default patch merge approach with a specific type. By default, the strategic
59 merge will typically be used.
60 - For example, Custom Resource Definitions typically aren't updatable by the usual strategic merge. You may
61 want to use C(merge) if you see "strategic merge patch format is not supported"
62 - See U(https://kubernetes.io/docs/tasks/run-application/update-api-object-kubectl-patch/#use-a-json-merge-patch-to-update-a-deployment)
63 - If more than one merge_type is given, the merge_types will be tried in order
64 - Defaults to C(['strategic-merge', 'merge']), which is ideal for using the same parameters
65 on resource kinds that combine Custom Resources and built-in resources.
66 - mutually exclusive with C(apply)
67 - I(merge_type=json) has been removed in version 4.0.0. Please use M(kubernetes.core.k8s_json_patch) instead.
68 choices:
69 - merge
70 - strategic-merge
71 type: list
72 elements: str
73 validate:
74 description:
75 - how (if at all) to validate the resource definition against the kubernetes schema.
76 Requires the kubernetes-validate python module
77 suboptions:
78 fail_on_error:
79 description: whether to fail on validation errors.
80 type: bool
81 version:
82 description: version of Kubernetes to validate against. defaults to Kubernetes server version
83 type: str
84 strict:
85 description: whether to fail when passing unexpected properties
86 default: True
87 type: bool
88 type: dict
89 append_hash:
90 description:
91 - Whether to append a hash to a resource name for immutability purposes
92 - Applies only to ConfigMap and Secret resources
93 - The parameter will be silently ignored for other resource kinds
94 - The full definition of an object is needed to generate the hash - this means that deleting an object created with append_hash
95 will only work if the same object is passed with state=absent (alternatively, just use state=absent with the name including
96 the generated hash and append_hash=no)
97 type: bool
98 default: false
99 apply:
100 description:
101 - C(apply) compares the desired resource definition with the previously supplied resource definition,
102 ignoring properties that are automatically generated
103 - C(apply) works better with Services than 'force=yes'
104 - mutually exclusive with C(merge_type)
105 type: bool
106 default: false
107 template:
108 description:
109 - Provide a valid YAML template definition file for an object when creating or updating.
110 - Value can be provided as string or dictionary.
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 version_added: '2.0.0'
132 continue_on_error:
133 description:
134 - Whether to continue on creation/deletion errors when multiple resources are defined.
135 - This has no effect on the validation step which is controlled by the C(validate.fail_on_error) parameter.
136 type: bool
137 default: False
138 version_added: 2.0.0
139
140 requirements:
141 - "python >= 3.6"
142 - "kubernetes >= 12.0.0"
143 - "PyYAML >= 3.11"
144 """
145
146 EXAMPLES = r"""
147 - name: Create an OCP project
148 community.okd.k8s:
149 state: present
150 resource_definition:
151 apiVersion: project.openshift.io/v1
152 kind: Project
153 metadata:
154 name: testing
155
156 - name: Create a k8s namespace
157 community.okd.k8s:
158 name: testing
159 api_version: v1
160 kind: Namespace
161 state: present
162
163 - name: Create a Service object from an inline definition
164 community.okd.k8s:
165 state: present
166 definition:
167 apiVersion: v1
168 kind: Service
169 metadata:
170 name: web
171 namespace: testing
172 labels:
173 app: galaxy
174 service: web
175 spec:
176 selector:
177 app: galaxy
178 service: web
179 ports:
180 - protocol: TCP
181 targetPort: 8000
182 name: port-8000-tcp
183 port: 8000
184
185 - name: Remove an existing Service object
186 community.okd.k8s:
187 state: absent
188 api_version: v1
189 kind: Service
190 namespace: testing
191 name: web
192
193 # Passing the object definition from a file
194
195 - name: Create a Deployment by reading the definition from a local file
196 community.okd.k8s:
197 state: present
198 src: /testing/deployment.yml
199
200 - name: >-
201 Read definition file from the Ansible controller file system.
202 If the definition file has been encrypted with Ansible Vault it will automatically be decrypted.
203 community.okd.k8s:
204 state: present
205 definition: "{{ lookup('file', '/testing/deployment.yml') | from_yaml }}"
206
207 - name: Read definition file from the Ansible controller file system after Jinja templating
208 community.okd.k8s:
209 state: present
210 definition: "{{ lookup('template', '/testing/deployment.yml') | from_yaml }}"
211
212 - name: fail on validation errors
213 community.okd.k8s:
214 state: present
215 definition: "{{ lookup('template', '/testing/deployment.yml') | from_yaml }}"
216 validate:
217 fail_on_error: true
218
219 - name: warn on validation errors, check for unexpected properties
220 community.okd.k8s:
221 state: present
222 definition: "{{ lookup('template', '/testing/deployment.yml') | from_yaml }}"
223 validate:
224 fail_on_error: false
225 strict: true
226 """
227
228 RETURN = r"""
229 result:
230 description:
231 - The created, patched, or otherwise present object. Will be empty in the case of a deletion.
232 returned: success
233 type: complex
234 contains:
235 api_version:
236 description: The versioned schema of this representation of an object.
237 returned: success
238 type: str
239 kind:
240 description: Represents the REST resource this object represents.
241 returned: success
242 type: str
243 metadata:
244 description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
245 returned: success
246 type: complex
247 spec:
248 description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
249 returned: success
250 type: complex
251 status:
252 description: Current status details for the object.
253 returned: success
254 type: complex
255 items:
256 description: Returned only when multiple yaml documents are passed to src or resource_definition
257 returned: when resource_definition or src contains list of objects
258 type: list
259 duration:
260 description: elapsed time of task in seconds
261 returned: when C(wait) is true
262 type: int
263 sample: 48
264 error:
265 description: Error while trying to create/delete the object.
266 returned: error
267 type: complex
268 """
269 # ENDREMOVE (downstream)
270
271 from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
272 NAME_ARG_SPEC,
273 RESOURCE_ARG_SPEC,
274 AUTH_ARG_SPEC,
275 WAIT_ARG_SPEC,
276 DELETE_OPTS_ARG_SPEC,
277 )
278
279
280 def validate_spec():
281 return dict(
282 fail_on_error=dict(type="bool"),
283 version=dict(),
284 strict=dict(type="bool", default=True),
285 )
286
287
288 def argspec():
289 argument_spec = {}
290 argument_spec.update(NAME_ARG_SPEC)
291 argument_spec.update(RESOURCE_ARG_SPEC)
292 argument_spec.update(AUTH_ARG_SPEC)
293 argument_spec.update(WAIT_ARG_SPEC)
294 argument_spec["merge_type"] = dict(
295 type="list", elements="str", choices=["merge", "strategic-merge"]
296 )
297 argument_spec["validate"] = dict(type="dict", default=None, options=validate_spec())
298 argument_spec["append_hash"] = dict(type="bool", default=False)
299 argument_spec["apply"] = dict(type="bool", default=False)
300 argument_spec["template"] = dict(type="raw", default=None)
301 argument_spec["delete_options"] = dict(
302 type="dict", default=None, options=DELETE_OPTS_ARG_SPEC
303 )
304 argument_spec["continue_on_error"] = dict(type="bool", default=False)
305 argument_spec["state"] = dict(
306 default="present", choices=["present", "absent", "patched"]
307 )
308 argument_spec["force"] = dict(type="bool", default=False)
309 return argument_spec
310
311
312 def main():
313 mutually_exclusive = [
314 ("resource_definition", "src"),
315 ("merge_type", "apply"),
316 ("template", "resource_definition"),
317 ("template", "src"),
318 ]
319
320 from ansible_collections.community.okd.plugins.module_utils.k8s import OKDRawModule
321
322 module = OKDRawModule(
323 argument_spec=argspec(),
324 supports_check_mode=True,
325 mutually_exclusive=mutually_exclusive,
326 )
327 module.run_module()
328
329
330 if __name__ == "__main__":
331 main()