Debian Codegraph @

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

raw symbols SCIP
1 #
2 # Copyright 2018 Red Hat | Ansible
3 #
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import absolute_import, division, print_function
7
8 __metaclass__ = type
9
10 DOCUMENTATION = """
11 name: k8s
12
13 short_description: Query the K8s API
14
15 author:
16 - Chris Houseknecht (@chouseknecht)
17 - Fabian von Feilitzsch (@fabianvf)
18
19 description:
20 - Uses the Kubernetes Python client to fetch a specific object by name, all matching objects within a
21 namespace, or all matching objects for all namespaces, as well as information about the cluster.
22 - Provides access the full range of K8s APIs.
23 - Enables authentication via config file, certificates, password or token.
24 notes:
25 - While querying, please use C(query) or C(lookup) format with C(wantlist=True) to provide an easier and more
26 consistent interface. For more details, see
27 U(https://docs.ansible.com/ansible/latest/plugins/lookup.html#forcing-lookups-to-return-lists-query-and-wantlist-true).
28 options:
29 cluster_info:
30 description:
31 - Use to specify the type of cluster information you are attempting to retrieve. Will take priority
32 over all the other options.
33 api_version:
34 description:
35 - Use to specify the API version. If I(resource definition) is provided, the I(apiVersion) from the
36 I(resource_definition) will override this option.
37 default: v1
38 kind:
39 description:
40 - Use to specify an object model. If I(resource definition) is provided, the I(kind) from a
41 I(resource_definition) will override this option.
42 required: true
43 resource_name:
44 description:
45 - Fetch a specific object by name. If I(resource definition) is provided, the I(metadata.name) value
46 from the I(resource_definition) will override this option.
47 namespace:
48 description:
49 - Limit the objects returned to a specific namespace. If I(resource definition) is provided, the
50 I(metadata.namespace) value from the I(resource_definition) will override this option.
51 label_selector:
52 description:
53 - Additional labels to include in the query. Ignored when I(resource_name) is provided.
54 field_selector:
55 description:
56 - Specific fields on which to query. Ignored when I(resource_name) is provided.
57 resource_definition:
58 description:
59 - "Provide a YAML configuration for an object. NOTE: I(kind), I(api_version), I(resource_name),
60 and I(namespace) will be overwritten by corresponding values found in the provided I(resource_definition)."
61 src:
62 description:
63 - "Provide a path to a file containing a valid YAML definition of an object dated. Mutually
64 exclusive with I(resource_definition). NOTE: I(kind), I(api_version), I(resource_name), and I(namespace)
65 will be overwritten by corresponding values found in the configuration read in from the I(src) file."
66 - Reads from the local file system. To read from the Ansible controller's file system, use the file lookup
67 plugin or template lookup plugin, combined with the from_yaml filter, and pass the result to
68 I(resource_definition). See Examples below.
69 host:
70 description:
71 - Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.
72 api_key:
73 description:
74 - Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment variable.
75 kubeconfig:
76 description:
77 - Path to an existing Kubernetes config file. If not provided, and no other connection
78 options are provided, the Kubernetes client will attempt to load the default
79 configuration file from I(~/.kube/config). Can also be specified via K8S_AUTH_KUBECONFIG environment
80 variable.
81 context:
82 description:
83 - The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment
84 variable.
85 username:
86 description:
87 - Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME environment
88 variable.
89 no_proxy:
90 description:
91 - The comma separated list of hosts/domains/IP/CIDR that shouldn't go through proxy.
92 Can also be specified via K8S_AUTH_NO_PROXY environment variable.
93 - Please note that this module does not pick up typical proxy settings from the environment (e.g. NO_PROXY).
94 - This feature requires kubernetes>=19.15.0.
95 When kubernetes library is less than 19.15.0, it fails even if no_proxy is set correctly.
96 type: str
97 password:
98 description:
99 - Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD environment
100 variable.
101 proxy:
102 description:
103 - The URL of an HTTP proxy to use for the connection. Can also be specified via K8S_AUTH_PROXY environment variable.
104 - Please note that this module does not pick up typical proxy settings from the environment (e.g. HTTP_PROXY).
105 type: str
106 proxy_headers:
107 description:
108 - The Header used for the HTTP proxy.
109 - Documentation can be found here
110 U(https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html?highlight=proxy_headers#urllib3.util.make_headers).
111 type: dict
112 suboptions:
113 proxy_basic_auth:
114 type: str
115 description:
116 - Colon-separated username:password for proxy basic authentication header.
117 - Can also be specified via K8S_AUTH_PROXY_HEADERS_PROXY_BASIC_AUTH environment.
118 basic_auth:
119 type: str
120 description:
121 - Colon-separated username:password for basic authentication header.
122 - Can also be specified via K8S_AUTH_PROXY_HEADERS_BASIC_AUTH environment.
123 user_agent:
124 type: str
125 description:
126 - String representing the user-agent you want, such as foo/1.0.
127 - Can also be specified via K8S_AUTH_PROXY_HEADERS_USER_AGENT environment.
128 client_cert:
129 description:
130 - Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE environment
131 variable.
132 aliases: [ cert_file ]
133 client_key:
134 description:
135 - Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE environment
136 variable.
137 aliases: [ key_file ]
138 ca_cert:
139 description:
140 - Path to a CA certificate used to authenticate with the API. Can also be specified via K8S_AUTH_SSL_CA_CERT
141 environment variable.
142 aliases: [ ssl_ca_cert ]
143 validate_certs:
144 description:
145 - Whether or not to verify the API server's SSL certificates. Can also be specified via K8S_AUTH_VERIFY_SSL
146 environment variable.
147 type: bool
148 aliases: [ verify_ssl ]
149
150 requirements:
151 - "python >= 3.9"
152 - "kubernetes >= 24.2.0"
153 - "PyYAML >= 3.11"
154 """
155
156 EXAMPLES = """
157 - name: Fetch a list of namespaces
158 set_fact:
159 projects: "{{ query('kubernetes.core.k8s', api_version='v1', kind='Namespace') }}"
160
161 - name: Fetch all deployments
162 set_fact:
163 deployments: "{{ query('kubernetes.core.k8s', kind='Deployment') }}"
164
165 - name: Fetch all deployments in a namespace
166 set_fact:
167 deployments: "{{ query('kubernetes.core.k8s', kind='Deployment', namespace='testing') }}"
168
169 - name: Fetch a specific deployment by name
170 set_fact:
171 deployments: "{{ query('kubernetes.core.k8s', kind='Deployment', namespace='testing', resource_name='elastic') }}"
172
173 - name: Fetch with label selector
174 set_fact:
175 service: "{{ query('kubernetes.core.k8s', kind='Service', label_selector='app=galaxy') }}"
176
177 # Use parameters from a YAML config
178
179 - name: Load config from the Ansible controller filesystem
180 set_fact:
181 config: "{{ lookup('file', 'service.yml') | from_yaml }}"
182
183 - name: Using the config (loaded from a file in prior task), fetch the latest version of the object
184 set_fact:
185 service: "{{ query('kubernetes.core.k8s', resource_definition=config) }}"
186
187 - name: Use a config from the local filesystem
188 set_fact:
189 service: "{{ query('kubernetes.core.k8s', src='service.yml') }}"
190 """
191
192 RETURN = """
193 _list:
194 description:
195 - One ore more object definitions returned from the API.
196 type: list
197 elements: dict
198 sample:
199 - kind: ConfigMap
200 apiVersion: v1
201 metadata:
202 creationTimestamp: "2022-03-04T13:59:49Z"
203 name: my-config-map
204 namespace: default
205 resourceVersion: "418"
206 uid: 5714b011-d090-4eac-8272-a0ea82ec0abd
207 data:
208 key1: val1
209 """
210
211 import os
212
213 from ansible.errors import AnsibleError
214 from ansible.module_utils.common._collections_compat import KeysView
215 from ansible.module_utils.common.validation import check_type_bool
216 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.client import (
217 get_api_client,
218 )
219 from ansible_collections.kubernetes.core.plugins.module_utils.k8s.resource import (
220 create_definitions,
221 )
222
223 try:
224 enable_turbo_mode = check_type_bool(os.environ.get("ENABLE_TURBO_MODE"))
225 except TypeError:
226 enable_turbo_mode = False
227
228 if enable_turbo_mode:
229 try:
230 from ansible_collections.cloud.common.plugins.plugin_utils.turbo.lookup import (
231 TurboLookupBase as LookupBase,
232 )
233 except ImportError:
234 from ansible.plugins.lookup import LookupBase # noqa: F401
235 else:
236 from ansible.plugins.lookup import LookupBase # noqa: F401
237
238 try:
239 from kubernetes.dynamic.exceptions import NotFoundError
240
241 HAS_K8S_MODULE_HELPER = True
242 k8s_import_exception = None
243 except ImportError as e:
244 HAS_K8S_MODULE_HELPER = False
245 k8s_import_exception = e
246
247
248 class KubernetesLookup(object):
249 def __init__(self):
250 if not HAS_K8S_MODULE_HELPER:
251 raise Exception(
252 "Requires the Kubernetes Python client. Try `pip install kubernetes`. Detail: {0}".format(
253 k8s_import_exception
254 )
255 )
256
257 self.kind = None
258 self.name = None
259 self.namespace = None
260 self.api_version = None
261 self.label_selector = None
262 self.field_selector = None
263 self.include_uninitialized = None
264 self.resource_definition = None
265 self.helper = None
266 self.connection = {}
267
268 def fail(self, msg=None):
269 raise AnsibleError(msg)
270
271 def run(self, terms, variables=None, **kwargs):
272 self.params = kwargs
273 self.client = get_api_client(**kwargs)
274
275 cluster_info = kwargs.get("cluster_info")
276 if cluster_info == "version":
277 return [self.client.client.version]
278 if cluster_info == "api_groups":
279 if isinstance(self.client.resources.api_groups, KeysView):
280 return [list(self.client.resources.api_groups)]
281 return [self.client.resources.api_groups]
282
283 self.kind = kwargs.get("kind")
284 self.name = kwargs.get("resource_name")
285 self.namespace = kwargs.get("namespace")
286 self.api_version = kwargs.get("api_version", "v1")
287 self.label_selector = kwargs.get("label_selector")
288 self.field_selector = kwargs.get("field_selector")
289 self.include_uninitialized = kwargs.get("include_uninitialized", False)
290
291 resource_definition = kwargs.get("resource_definition")
292 src = kwargs.get("src")
293 if src:
294 definitions = create_definitions(params=dict(src=src))
295 if definitions:
296 self.kind = definitions[0].kind
297 self.name = definitions[0].name
298 self.namespace = definitions[0].namespace
299 self.api_version = definitions[0].api_version or "v1"
300 if resource_definition:
301 self.kind = resource_definition.get("kind", self.kind)
302 self.api_version = resource_definition.get("apiVersion", self.api_version)
303 self.name = resource_definition.get("metadata", {}).get("name", self.name)
304 self.namespace = resource_definition.get("metadata", {}).get(
305 "namespace", self.namespace
306 )
307
308 if not self.kind:
309 raise AnsibleError(
310 "Error: no Kind specified. Use the 'kind' parameter, or provide an object YAML configuration "
311 "using the 'resource_definition' parameter."
312 )
313
314 resource = self.client.resource(self.kind, self.api_version)
315 try:
316 params = dict(
317 name=self.name,
318 namespace=self.namespace,
319 label_selector=self.label_selector,
320 field_selector=self.field_selector,
321 )
322 k8s_obj = self.client.get(resource, **params)
323 except NotFoundError:
324 return []
325
326 if self.name:
327 return [k8s_obj.to_dict()]
328
329 return k8s_obj.to_dict().get("items")
330
331
332 class LookupModule(LookupBase):
333 def _run(self, terms, variables=None, **kwargs):
334 return KubernetesLookup().run(terms, variables=variables, **kwargs)
335
336 run = _run if not hasattr(LookupBase, "run_on_daemon") else LookupBase.run_on_daemon