Debian Codegraph @

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

raw
1 # Copyright (c) 2013, Jan-Piet Mens <jpmens(at)gmail.com>
2 # (m) 2016, Mihai Moldovanu <[email protected]>
3 # (m) 2017, Juan Manuel Parrilla <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 author:
11 - Jan-Piet Mens (@jpmens)
12 name: etcd
13 short_description: Get info from an etcd server
14 description:
15 - Retrieves data from an etcd server.
16 options:
17 _terms:
18 description:
19 - The list of keys to lookup on the etcd server.
20 type: list
21 elements: string
22 required: true
23 url:
24 description:
25 - Environment variable with the URL for the etcd server.
26 type: string
27 default: 'http://127.0.0.1:4001'
28 env:
29 - name: ANSIBLE_ETCD_URL
30 version:
31 description:
32 - Environment variable with the etcd protocol version.
33 type: string
34 default: 'v1'
35 env:
36 - name: ANSIBLE_ETCD_VERSION
37 validate_certs:
38 description:
39 - Toggle checking that the ssl certificates are valid, you normally only want to turn this off with self-signed certs.
40 default: true
41 type: boolean
42 seealso:
43 - module: community.general.etcd3
44 - plugin: community.general.etcd3
45 plugin_type: lookup
46 """
47
48 EXAMPLES = r"""
49 - name: "a value from a locally running etcd"
50 ansible.builtin.debug:
51 msg: "{{ lookup('community.general.etcd', 'foo/bar') }}"
52
53 - name: "values from multiple folders on a locally running etcd"
54 ansible.builtin.debug:
55 msg: "{{ lookup('community.general.etcd', 'foo', 'bar', 'baz') }}"
56
57 - name: "you can set server options inline"
58 ansible.builtin.debug:
59 msg: "{{ lookup('community.general.etcd', 'foo', version='v2', url='http://192.168.0.27:4001') }}"
60 """
61
62 RETURN = r"""
63 _raw:
64 description:
65 - List of values associated with input keys.
66 type: list
67 elements: string
68 """
69
70 import json
71
72 from ansible.module_utils.urls import open_url
73 from ansible.plugins.lookup import LookupBase
74
75 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
76
77 # this can be made configurable, not should not use ansible.cfg
78 #
79 # Made module configurable from playbooks:
80 # If etcd v2 running on host 192.168.1.21 on port 2379
81 # we can use the following in a playbook to retrieve /tfm/network/config key
82 #
83 # - ansible.builtin.debug: msg={{lookup('etcd','/tfm/network/config', url='http://192.168.1.21:2379' , version='v2')}}
84 #
85 # Example Output:
86 #
87 # TASK [debug] *******************************************************************
88 # ok: [localhost] => {
89 # "msg": {
90 # "Backend": {
91 # "Type": "vxlan"
92 # },
93 # "Network": "172.30.0.0/16",
94 # "SubnetLen": 24
95 # }
96 # }
97 #
98 #
99 #
100 #
101
102
103 class Etcd:
104 def __init__(self, url, version, validate_certs):
105 self.url = url
106 self.version = version
107 self.baseurl = f"{self.url}/{self.version}/keys"
108 self.validate_certs = validate_certs
109
110 def _parse_node(self, node):
111 # This function will receive all etcd tree,
112 # if the level requested has any node, the recursion starts
113 # create a list in the dir variable and it is passed to the
114 # recursive function, and so on, if we get a variable,
115 # the function will create a key-value at this level and
116 # undoing the loop.
117 path = {}
118 if node.get("dir", False):
119 for n in node.get("nodes", []):
120 path[n["key"].split("/")[-1]] = self._parse_node(n)
121
122 else:
123 path = node["value"]
124
125 return path
126
127 def get(self, key):
128 url = f"{self.baseurl}/{key}?recursive=true"
129 data = None
130 value = {}
131 try:
132 r = open_url(url, validate_certs=self.validate_certs)
133 data = r.read()
134 except Exception:
135 return None
136
137 try:
138 # I will not support Version 1 of etcd for folder parsing
139 item = json.loads(data)
140 if self.version == "v1":
141 # When ETCD are working with just v1
142 if "value" in item:
143 value = item["value"]
144 else:
145 if "node" in item:
146 # When a usual result from ETCD
147 value = self._parse_node(item["node"])
148
149 if "errorCode" in item:
150 # Here return an error when an unknown entry responds
151 value = "ENOENT"
152 except Exception:
153 raise
154
155 return value
156
157
158 class LookupModule(LookupBase):
159 def run(self, terms, variables, **kwargs):
160 self.set_options(var_options=variables, direct=kwargs)
161 check_for_wrong_terms(self, direct=kwargs)
162
163 validate_certs = self.get_option("validate_certs")
164 url = self.get_option("url")
165 version = self.get_option("version")
166
167 etcd = Etcd(url=url, version=version, validate_certs=validate_certs)
168
169 ret = []
170 for term in terms:
171 key = term.split()[0]
172 value = etcd.get(key)
173 ret.append(value)
174 return ret