Debian Codegraph @

ansible_collections/community/general/plugins/lookup/etcd3.py

raw
1 #
2 # Copyright (c) 2020, SCC France, Eric Belhomme <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 from __future__ import annotations
7
8 DOCUMENTATION = r"""
9 author:
10 - Eric Belhomme (@eric-belhomme) <[email protected]>
11 version_added: '0.2.0'
12 name: etcd3
13 short_description: Get key values from etcd3 server
14 description:
15 - Retrieves key values and/or key prefixes from etcd3 server using its native gRPC API.
16 - Try to reuse M(community.general.etcd3) options for connection parameters, but add support for some E(ETCDCTL_*) environment
17 variables.
18 - See U(https://github.com/etcd-io/etcd/tree/master/Documentation/op-guide) for etcd overview.
19 options:
20 _terms:
21 description:
22 - The list of keys (or key prefixes) to look up on the etcd3 server.
23 type: list
24 elements: str
25 required: true
26 prefix:
27 description:
28 - Look for key or prefix key.
29 type: bool
30 default: false
31 endpoints:
32 description:
33 - Counterpart of E(ETCDCTL_ENDPOINTS) environment variable. Specify the etcd3 connection with an URL form, for example
34 V(https://hostname:2379), or V(<host>:<port>) form.
35 - The V(host) part is overwritten by O(host) option, if defined.
36 - The V(port) part is overwritten by O(port) option, if defined.
37 - Note that specifying V(https://) in the endpoint URL does not by itself enable TLS. To connect to an HTTPS etcd3
38 endpoint, you must provide O(ca_cert) (and optionally O(cert_cert) and O(cert_key)).
39 env:
40 - name: ETCDCTL_ENDPOINTS
41 default: '127.0.0.1:2379'
42 type: str
43 host:
44 description:
45 - Etcd3 listening client host.
46 - Takes precedence over O(endpoints).
47 - Must be a bare hostname or IP address without a URL scheme. If a V(https://) or V(http://) prefix is present,
48 it will be stripped automatically.
49 type: str
50 port:
51 description:
52 - Etcd3 listening client port.
53 - Takes precedence over O(endpoints).
54 type: int
55 ca_cert:
56 description:
57 - Etcd3 CA authority.
58 - Required to enable TLS when connecting to an HTTPS etcd3 endpoint.
59 env:
60 - name: ETCDCTL_CACERT
61 type: str
62 cert_cert:
63 description:
64 - Etcd3 client certificate.
65 env:
66 - name: ETCDCTL_CERT
67 type: str
68 cert_key:
69 description:
70 - Etcd3 client private key.
71 env:
72 - name: ETCDCTL_KEY
73 type: str
74 timeout:
75 description:
76 - Client timeout.
77 default: 60
78 env:
79 - name: ETCDCTL_DIAL_TIMEOUT
80 type: int
81 user:
82 description:
83 - Authenticated user name.
84 env:
85 - name: ETCDCTL_USER
86 type: str
87 password:
88 description:
89 - Authenticated user password.
90 env:
91 - name: ETCDCTL_PASSWORD
92 type: str
93
94 notes:
95 - O(host) and O(port) options take precedence over O(endpoints) option.
96 - The recommended way to connect to etcd3 server is using E(ETCDCTL_ENDPOINT) environment variable and keep O(endpoints),
97 O(host), and O(port) unused.
98 - To connect to an HTTPS etcd3 endpoint, the O(ca_cert) option must be provided. Merely specifying V(https://) in
99 O(endpoints) is not sufficient to enable TLS.
100 seealso:
101 - module: community.general.etcd3
102 - plugin: community.general.etcd
103 plugin_type: lookup
104
105 requirements:
106 - "etcd3 >= 0.10"
107 """
108
109 EXAMPLES = r"""
110 - name: "a value from a locally running etcd"
111 ansible.builtin.debug:
112 msg: "{{ lookup('community.general.etcd3', 'foo/bar') }}"
113
114 - name: "values from multiple folders on a locally running etcd"
115 ansible.builtin.debug:
116 msg: "{{ lookup('community.general.etcd3', 'foo', 'bar', 'baz') }}"
117
118 - name: "look for a key prefix"
119 ansible.builtin.debug:
120 msg: "{{ lookup('community.general.etcd3', '/foo/bar', prefix=True) }}"
121
122 - name: "connect to etcd3 with a client certificate"
123 ansible.builtin.debug:
124 msg: "{{ lookup('community.general.etcd3', 'foo/bar', cert_cert='/etc/ssl/etcd/client.pem', cert_key='/etc/ssl/etcd/client.key') }}"
125
126 - name: "connect to etcd3 over HTTPS"
127 ansible.builtin.debug:
128 msg: "{{ lookup('community.general.etcd3', 'foo/bar', endpoints='https://etcd.example.com:2379', ca_cert='/etc/ssl/etcd/ca.pem') }}"
129 """
130
131 RETURN = r"""
132 _raw:
133 description:
134 - List of keys and associated values.
135 type: list
136 elements: dict
137 contains:
138 key:
139 description: The element's key.
140 type: str
141 value:
142 description: The element's value.
143 type: str
144 """
145
146 import re
147
148 from ansible.errors import AnsibleLookupError
149 from ansible.module_utils.basic import missing_required_lib
150 from ansible.module_utils.common.text.converters import to_native
151 from ansible.plugins.lookup import LookupBase
152 from ansible.utils.display import Display
153
154 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
155
156 try:
157 import etcd3
158
159 HAS_ETCD = True
160 except ImportError:
161 HAS_ETCD = False
162
163 display = Display()
164
165 etcd3_cnx_opts = (
166 "host",
167 "port",
168 "ca_cert",
169 "cert_key",
170 "cert_cert",
171 "timeout",
172 "user",
173 "password",
174 # 'grpc_options' Etcd3Client() option currently not supported by lookup module (maybe in future ?)
175 )
176
177
178 def etcd3_client(client_params):
179 try:
180 etcd = etcd3.client(**client_params)
181 etcd.status()
182 except Exception as exp:
183 raise AnsibleLookupError(f"Cannot connect to etcd cluster: {exp}") from exp
184 return etcd
185
186
187 class LookupModule(LookupBase):
188 def run(self, terms, variables, **kwargs):
189 self.set_options(var_options=variables, direct=kwargs)
190 check_for_wrong_terms(self, direct=kwargs)
191
192 if not HAS_ETCD:
193 display.error(missing_required_lib("etcd3"))
194 return None
195
196 # create the etcd3 connection parameters dict to pass to etcd3 class
197 client_params = {}
198
199 # etcd3 class expects host and port as connection parameters, so endpoints
200 # must be mangled a bit to fit in this scheme.
201 # so here we use a regex to extract server and port
202 is_https = False
203 match = re.compile(
204 r"^(?P<scheme>https?://)?(?P<host>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|([-_\d\w\.]+))(:(?P<port>\d{1,5}))?/?$"
205 ).match(self.get_option("endpoints"))
206 if match:
207 if match.group("host"):
208 client_params["host"] = match.group("host")
209 if match.group("port"):
210 client_params["port"] = match.group("port")
211 if match.group("scheme") and match.group("scheme").startswith("https"):
212 is_https = True
213
214 for opt in etcd3_cnx_opts:
215 if self.get_option(opt):
216 client_params[opt] = self.get_option(opt)
217
218 # strip URL scheme from host if present
219 if "host" in client_params:
220 host_match = re.match(r"^(?P<scheme>https?://)(?P<host>.+)$", client_params["host"])
221 if host_match:
222 display.warning(
223 f"The host option contained a URL scheme '{host_match.group('scheme')}' which has been removed. "
224 "Use a bare hostname or IP address for the host option. "
225 "To enable TLS, provide the ca_cert option."
226 )
227 client_params["host"] = host_match.group("host")
228 if host_match.group("scheme").startswith("https"):
229 is_https = True
230
231 if is_https and not self.get_option("ca_cert"):
232 display.warning(
233 "An HTTPS endpoint was specified but ca_cert was not provided. "
234 "The connection will be attempted without TLS. "
235 "To enable TLS, provide the ca_cert option."
236 )
237
238 cnx_log = dict(client_params)
239 if "password" in cnx_log:
240 cnx_log["password"] = "<redacted>"
241 display.verbose(f"etcd3 connection parameters: {cnx_log}")
242
243 # connect to etcd3 server
244 etcd = etcd3_client(client_params)
245
246 ret = []
247 # we can pass many keys to lookup
248 for term in terms:
249 if self.get_option("prefix"):
250 try:
251 for val, meta in etcd.get_prefix(term):
252 if val and meta:
253 ret.append({"key": to_native(meta.key), "value": to_native(val)})
254 except Exception as exp:
255 display.warning(f"Caught except during etcd3.get_prefix: {exp}")
256 else:
257 try:
258 val, meta = etcd.get(term)
259 if val and meta:
260 ret.append({"key": to_native(meta.key), "value": to_native(val)})
261 except Exception as exp:
262 display.warning(f"Caught except during etcd3.get: {exp}")
263 return ret