Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2021, Alina Buzachis <@alinabuzachis>
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
13 DOCUMENTATION = r"""
14 module: k8s_taint
15 short_description: Taint a node in a Kubernetes/OpenShift cluster
16 version_added: 2.3.0
17 author: Alina Buzachis (@alinabuzachis)
18 description:
19 - Taint allows a node to refuse Pod to be scheduled unless that Pod has a matching toleration.
20 - Untaint will remove taints from nodes as needed.
21 extends_documentation_fragment:
22 - kubernetes.core.k8s_auth_options
23 options:
24 state:
25 description:
26 - Determines whether to add or remove taints.
27 type: str
28 default: present
29 choices: [ present, absent ]
30 name:
31 description:
32 - The name of the node.
33 required: true
34 type: str
35 taints:
36 description:
37 - List containing the taints.
38 type: list
39 required: true
40 elements: dict
41 suboptions:
42 key:
43 description:
44 - The taint key to be applied to a node.
45 type: str
46 value:
47 description:
48 - The taint value corresponding to the taint key.
49 type: str
50 effect:
51 description:
52 - The effect of the taint on Pods that do not tolerate the taint.
53 - Required when I(state=present).
54 type: str
55 choices: [ NoSchedule, NoExecute, PreferNoSchedule ]
56 replace:
57 description:
58 - If C(true), allow taints to be replaced.
59 required: false
60 default: false
61 type: bool
62 requirements:
63 - python >= 3.9
64 - kubernetes >= 24.2.0
65 """
66
67 EXAMPLES = r"""
68 - name: Taint node "foo"
69 kubernetes.core.k8s_taint:
70 state: present
71 name: foo
72 taints:
73 - effect: NoExecute
74 key: "key1"
75
76 - name: Taint node "foo"
77 kubernetes.core.k8s_taint:
78 state: present
79 name: foo
80 taints:
81 - effect: NoExecute
82 key: "key1"
83 value: "value1"
84 - effect: NoSchedule
85 key: "key1"
86 value: "value1"
87
88 - name: Remove taint from "foo".
89 kubernetes.core.k8s_taint:
90 state: absent
91 name: foo
92 taints:
93 - effect: NoExecute
94 key: "key1"
95 value: "value1"
96 """
97
98 RETURN = r"""
99 result:
100 description:
101 - The tainted Node object. Will be empty in the case of a deletion.
102 returned: success
103 type: complex
104 contains:
105 api_version:
106 description: The versioned schema of this representation of an object.
107 returned: success
108 type: str
109 kind:
110 description: Represents the REST resource this object represents.
111 returned: success
112 type: str
113 metadata:
114 description: Standard object metadata. Includes name, namespace, annotations, labels, etc.
115 returned: success
116 type: complex
117 spec:
118 description: Specific attributes of the object. Will vary based on the I(api_version) and I(kind).
119 returned: success
120 type: complex
121 status:
122 description: Current status details for the object.
123 returned: success
124 type: complex
125 """
126
127 import copy
128
129 from ansible.module_utils.common.text.converters import to_native
130 from ansible_collections.kubernetes.core.plugins.module_utils.ansiblemodule import (
131 AnsibleModule,
132 )
133 from ansible_collections.kubernetes.core.plugins.module_utils.args_common import (
134 AUTH_ARG_SPEC,
135 )
136 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
137 get_api_client,
138 )
139 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.core import (
140 AnsibleK8SModule,
141 )
142 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.exceptions import (
143 CoreException,
144 )
145
146 try:
147 from kubernetes.client.api import core_v1_api
148 from kubernetes.client.exceptions import ApiException
149 except ImportError:
150 # ImportErrors are handled during module setup
151 pass
152
153
154 def _equal_dicts(a, b):
155 keys = ["key", "effect"]
156 if "effect" not in set(a).intersection(b):
157 keys.remove("effect")
158
159 return all((a[x] == b[x] for x in keys))
160
161
162 def _get_difference(a, b):
163 return [
164 a_item for a_item in a if not any(_equal_dicts(a_item, b_item) for b_item in b)
165 ]
166
167
168 def _get_intersection(a, b):
169 return [a_item for a_item in a if any(_equal_dicts(a_item, b_item) for b_item in b)]
170
171
172 def _update_exists(a, b):
173 return any(
174 (
175 any(
176 _equal_dicts(a_item, b_item)
177 and a_item.get("value") != b_item.get("value")
178 for b_item in b
179 )
180 for a_item in a
181 )
182 )
183
184
185 def argspec():
186 argument_spec = copy.deepcopy(AUTH_ARG_SPEC)
187 argument_spec.update(
188 dict(
189 state=dict(type="str", choices=["present", "absent"], default="present"),
190 name=dict(type="str", required=True),
191 taints=dict(type="list", required=True, elements="dict"),
192 replace=dict(type="bool", default=False),
193 )
194 )
195
196 return argument_spec
197
198
199 class K8sTaintAnsible:
200 def __init__(self, module, client):
201 self.module = module
202 self.api_instance = core_v1_api.CoreV1Api(client.client)
203 self.changed = False
204
205 def get_node(self, name):
206 try:
207 node = self.api_instance.read_node(name=name)
208 except ApiException as exc:
209 if exc.reason == "Not Found":
210 self.module.fail_json(msg="Node '{0}' has not been found.".format(name))
211 self.module.fail_json(
212 msg="Failed to retrieve node '{0}' due to: {1}".format(
213 name, exc.reason
214 ),
215 status=exc.status,
216 )
217 except Exception as exc:
218 self.module.fail_json(
219 msg="Failed to retrieve node '{0}' due to: {1}".format(
220 name, to_native(exc)
221 )
222 )
223
224 return node
225
226 def patch_node(self, taints):
227 body = {"spec": {"taints": taints}}
228
229 try:
230 result = self.api_instance.patch_node(
231 name=self.module.params.get("name"), body=body
232 )
233 except Exception as exc:
234 self.module.fail_json(
235 msg="Failed to patch node due to: {0}".format(to_native(exc))
236 )
237
238 return result.to_dict()
239
240 def execute_module(self):
241 result = {"result": {}}
242 state = self.module.params.get("state")
243 taints = self.module.params.get("taints")
244 name = self.module.params.get("name")
245
246 node = self.get_node(name)
247 existing_taints = node.spec.to_dict().get("taints") or []
248 diff = _get_difference(taints, existing_taints)
249
250 if state == "present":
251 if diff:
252 # There are new taints to be added
253 self.changed = True
254 if self.module.check_mode:
255 self.module.exit_json(changed=self.changed, **result)
256
257 if self.module.params.get("replace"):
258 # Patch with the new taints
259 result["result"] = self.patch_node(taints=taints)
260 self.module.exit_json(changed=self.changed, **result)
261
262 result["result"] = self.patch_node(
263 taints=[*_get_difference(existing_taints, taints), *taints]
264 )
265 else:
266 # No new taints to be added, but maybe there is something to be updated
267 if _update_exists(existing_taints, taints):
268 self.changed = True
269 if self.module.check_mode:
270 self.module.exit_json(changed=self.changed, **result)
271 result["result"] = self.patch_node(
272 taints=[*_get_difference(existing_taints, taints), *taints]
273 )
274 else:
275 result["result"] = node.to_dict()
276 elif state == "absent":
277 # Nothing to be removed
278 if not existing_taints:
279 result["result"] = node.to_dict()
280 if not diff:
281 self.changed = True
282 if self.module.check_mode:
283 self.module.exit_json(changed=self.changed, **result)
284 self.patch_node(taints=_get_difference(existing_taints, taints))
285 else:
286 if _get_intersection(existing_taints, taints):
287 self.changed = True
288 if self.module.check_mode:
289 self.module.exit_json(changed=self.changed, **result)
290 self.patch_node(taints=_get_difference(existing_taints, taints))
291 else:
292 self.module.exit_json(changed=self.changed, **result)
293
294 self.module.exit_json(changed=self.changed, **result)
295
296
297 def main():
298 module = AnsibleK8SModule(
299 module_class=AnsibleModule,
300 argument_spec=argspec(),
301 supports_check_mode=True,
302 )
303 try:
304 client = get_api_client(module)
305 k8s_taint = K8sTaintAnsible(module, client.client)
306 k8s_taint.execute_module()
307 except CoreException as e:
308 module.fail_from_exception(e)
309
310
311 if __name__ == "__main__":
312 main()