Debian Codegraph @

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

raw symbols SCIP
1 #
2 # Copyright 2021 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 DOCUMENTATION = """
7 name: kustomize
8
9 short_description: Build a set of kubernetes resources using a 'kustomization.yaml' file.
10
11 version_added: 2.2.0
12
13 author:
14 - Aubin Bikouo (@abikouo)
15 notes:
16 - If both kustomize and kubectl are part of the PATH, kustomize will be used by the plugin.
17 description:
18 - Uses the kustomize or the kubectl tool.
19 - Return the result of C(kustomize build) or C(kubectl kustomize).
20 options:
21 dir:
22 description:
23 - The directory path containing 'kustomization.yaml',
24 or a git repository URL with a path suffix specifying same with respect to the repository root.
25 - If omitted, '.' is assumed.
26 default: "."
27 binary_path:
28 description:
29 - The path of a kustomize or kubectl binary to use.
30 opt_dirs:
31 description:
32 - An optional list of directories to search for the executable in addition to PATH.
33 enable_helm:
34 description:
35 - Enable the helm chart inflation generator
36 default: "False"
37 environment:
38 description:
39 - The environment variables to pass to the kustomize or kubectl command.
40 - This can be a dictionary or a string in the format key=value, multiple pairs separated by space.
41 type: raw
42 default: {}
43 version_added: 6.2.0
44
45 requirements:
46 - "python >= 3.6"
47 """
48
49 EXAMPLES = """
50 - name: Run lookup using kustomize
51 ansible.builtin.set_fact:
52 resources: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kustomize') }}"
53
54 - name: Run lookup using kubectl kustomize
55 ansible.builtin.set_fact:
56 resources: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl') }}"
57
58 - name: Create kubernetes resources for lookup output
59 kubernetes.core.k8s:
60 definition: "{{ lookup('kubernetes.core.kustomize', dir='/path/to/kustomization') }}"
61
62 - name: Create kubernetes resources for lookup output with `--enable-helm` set
63 kubernetes.core.k8s:
64 definition: "{{ lookup('kubernetes.core.kustomize', dir='/path/to/kustomization', enable_helm=True) }}"
65
66 - name: Create kubernetes resources for lookup output with environment variables in string format
67 kubernetes.core.k8s:
68 definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment='HTTP_PROXY=http://proxy.example.com:3128') }}"
69
70 - name: Create kubernetes resources for lookup output with environment variables in dict format
71 kubernetes.core.k8s:
72 definition: "{{ lookup('kubernetes.core.kustomize', binary_path='/path/to/kubectl', environment={'HTTP_PROXY': 'http://proxy.example.com:3128'}) }}"
73 """
74
75 RETURN = """
76 _list:
77 description:
78 - YAML string for the object definitions returned from the tool execution.
79 type: str
80 sample:
81 kind: ConfigMap
82 apiVersion: v1
83 metadata:
84 name: my-config-map
85 namespace: default
86 data:
87 key1: val1
88 """
89
90 import os
91 import subprocess
92
93 from ansible.errors import AnsibleLookupError
94 from ansible.module_utils.common.process import get_bin_path
95 from ansible.plugins.lookup import LookupBase
96
97
98 def get_binary_from_path(name, opt_dirs=None):
99 opt_arg = {}
100 try:
101 if opt_dirs is not None:
102 if not isinstance(opt_dirs, list):
103 opt_dirs = [opt_dirs]
104 opt_arg["opt_dirs"] = opt_dirs
105 bin_path = get_bin_path(name, **opt_arg)
106 return bin_path
107 except ValueError:
108 return None
109
110
111 def run_command(command, environ=None):
112 cmd = subprocess.Popen(
113 command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=environ
114 )
115 stdout, stderr = cmd.communicate()
116 return cmd.returncode, stdout, stderr
117
118
119 class LookupModule(LookupBase):
120 def run(
121 self,
122 terms,
123 variables=None,
124 dir=".",
125 binary_path=None,
126 opt_dirs=None,
127 enable_helm=False,
128 environment=None,
129 **kwargs
130 ):
131 executable_path = binary_path
132 if executable_path is None:
133 executable_path = get_binary_from_path(name="kustomize", opt_dirs=opt_dirs)
134 if executable_path is None:
135 executable_path = get_binary_from_path(
136 name="kubectl", opt_dirs=opt_dirs
137 )
138
139 # validate that at least one tool was found
140 if executable_path is None:
141 raise AnsibleLookupError(
142 "Failed to find required executable 'kubectl' and 'kustomize' in paths"
143 )
144
145 # check input directory
146 kustomization_dir = dir
147
148 command = [executable_path]
149 if executable_path.endswith("kustomize"):
150 command += ["build", kustomization_dir]
151 elif executable_path.endswith("kubectl"):
152 command += ["kustomize", kustomization_dir]
153 else:
154 raise AnsibleLookupError(
155 "unexpected tool provided as parameter {0}, expected one of kustomize, kubectl.".format(
156 executable_path
157 )
158 )
159
160 if enable_helm:
161 command += ["--enable-helm"]
162
163 environ = None
164 if environment:
165 environ = os.environ.copy()
166 if isinstance(environment, str):
167 if not all(env.count("=") == 1 for env in environment.split(" ")):
168 raise AnsibleLookupError(
169 "environment should be dict or string in the format key=value, multiple pairs separated by space"
170 )
171 for env in environment.split(" "):
172 key, value = env.split("=")
173 environ[key] = value
174 if isinstance(environment, dict):
175 environ.update(environment)
176
177 (ret, out, err) = run_command(command, environ=environ)
178 if ret != 0:
179 if err:
180 raise AnsibleLookupError(
181 "kustomize command failed. exit code: {0}, error: {1}".format(
182 ret, err.decode("utf-8")
183 )
184 )
185 else:
186 raise AnsibleLookupError(
187 "kustomize command failed with unknown error. exit code: {0}".format(
188 ret
189 )
190 )
191 return [out.decode("utf-8")]