Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2018, Jean-Philippe Evrard <[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 module: etcd3
11 short_description: Set or delete key value pairs from an etcd3 cluster
12 requirements:
13 - etcd3
14 description:
15 - Sets or deletes values in etcd3 cluster using its v3 API.
16 - Needs python etcd3 lib to work.
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: none
24 options:
25 key:
26 type: str
27 description:
28 - The key where the information is stored in the cluster.
29 required: true
30 value:
31 type: str
32 description:
33 - The information stored.
34 required: true
35 host:
36 type: str
37 description:
38 - The IP address of the cluster.
39 default: 'localhost'
40 port:
41 type: int
42 description:
43 - The port number used to connect to the cluster.
44 default: 2379
45 state:
46 type: str
47 description:
48 - The state of the value for the key.
49 - Can be present or absent.
50 required: true
51 choices: [present, absent]
52 user:
53 type: str
54 description:
55 - The etcd user to authenticate with.
56 password:
57 type: str
58 description:
59 - The password to use for authentication.
60 - Required if O(user) is defined.
61 ca_cert:
62 type: path
63 description:
64 - The Certificate Authority to use to verify the etcd host.
65 - Required if O(client_cert) and O(client_key) are defined.
66 client_cert:
67 type: path
68 description:
69 - PEM formatted certificate chain file to be used for SSL client authentication.
70 - Required if O(client_key) is defined.
71 client_key:
72 type: path
73 description:
74 - PEM formatted file that contains your private key to be used for SSL client authentication.
75 - Required if O(client_cert) is defined.
76 timeout:
77 type: int
78 description:
79 - The socket level timeout in seconds.
80 author:
81 - Jean-Philippe Evrard (@evrardjp)
82 - Victor Fauth (@vfauth)
83 """
84
85 EXAMPLES = r"""
86 - name: Store a value "bar" under the key "foo" for a cluster located "http://localhost:2379"
87 community.general.etcd3:
88 key: "foo"
89 value: "baz3"
90 host: "localhost"
91 port: 2379
92 state: "present"
93
94 - name: Authenticate using user/password combination with a timeout of 10 seconds
95 community.general.etcd3:
96 key: "foo"
97 value: "baz3"
98 state: "present"
99 user: "someone"
100 password: "password123"
101 timeout: 10
102
103 - name: Authenticate using TLS certificates
104 community.general.etcd3:
105 key: "foo"
106 value: "baz3"
107 state: "present"
108 ca_cert: "/etc/ssl/certs/CA_CERT.pem"
109 client_cert: "/etc/ssl/certs/cert.crt"
110 client_key: "/etc/ssl/private/key.pem"
111 """
112
113 RETURN = r"""
114 key:
115 description: The key that was queried.
116 returned: always
117 type: str
118 old_value:
119 description: The previous value in the cluster.
120 returned: always
121 type: str
122 """
123
124 import traceback
125
126 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
127 from ansible.module_utils.common.text.converters import to_native
128
129 try:
130 import etcd3
131
132 HAS_ETCD = True
133 ETCD_IMP_ERR = None
134 except ImportError:
135 ETCD_IMP_ERR = traceback.format_exc()
136 HAS_ETCD = False
137
138
139 def run_module():
140 # define the available arguments/parameters that a user can pass to
141 # the module
142 module_args = dict(
143 key=dict(type="str", required=True, no_log=False),
144 value=dict(type="str", required=True),
145 host=dict(type="str", default="localhost"),
146 port=dict(type="int", default=2379),
147 state=dict(type="str", required=True, choices=["present", "absent"]),
148 user=dict(type="str"),
149 password=dict(type="str", no_log=True),
150 ca_cert=dict(type="path"),
151 client_cert=dict(type="path"),
152 client_key=dict(type="path"),
153 timeout=dict(type="int"),
154 )
155
156 # seed the result dict in the object
157 # we primarily care about changed and state
158 # change is if this module effectively modified the target
159 # state will include any data that you want your module to pass back
160 # for consumption, for example, in a subsequent task
161 result = dict(
162 changed=False,
163 )
164
165 # the AnsibleModule object will be our abstraction working with Ansible
166 # this includes instantiation, a couple of common attr would be the
167 # args/params passed to the execution, as well as if the module
168 # supports check mode
169 module = AnsibleModule(
170 argument_spec=module_args,
171 supports_check_mode=True,
172 required_together=[["client_cert", "client_key"], ["user", "password"]],
173 )
174
175 # It is possible to set `ca_cert` to verify the server identity without
176 # setting `client_cert` or `client_key` to authenticate the client
177 # so required_together is enough
178 # Due to `required_together=[['client_cert', 'client_key']]`, checking the presence
179 # of either `client_cert` or `client_key` is enough
180 if module.params["ca_cert"] is None and module.params["client_cert"] is not None:
181 module.fail_json(msg="The 'ca_cert' parameter must be defined when 'client_cert' and 'client_key' are present.")
182
183 result["key"] = module.params.get("key")
184 module.params["cert_cert"] = module.params.pop("client_cert")
185 module.params["cert_key"] = module.params.pop("client_key")
186
187 if not HAS_ETCD:
188 module.fail_json(msg=missing_required_lib("etcd3"), exception=ETCD_IMP_ERR)
189
190 allowed_keys = ["host", "port", "ca_cert", "cert_cert", "cert_key", "timeout", "user", "password"]
191
192 client_params = {key: value for key, value in module.params.items() if key in allowed_keys}
193 try:
194 etcd = etcd3.client(**client_params)
195 except Exception as exp:
196 module.fail_json(msg=f"Cannot connect to etcd cluster: {exp}", exception=traceback.format_exc())
197 try:
198 cluster_value = etcd.get(module.params["key"])
199 except Exception as exp:
200 module.fail_json(msg=f"Cannot reach data: {exp}", exception=traceback.format_exc())
201
202 # Make the cluster_value[0] a string for string comparisons
203 result["old_value"] = to_native(cluster_value[0])
204
205 if module.params["state"] == "absent":
206 if cluster_value[0] is not None:
207 if module.check_mode:
208 result["changed"] = True
209 else:
210 try:
211 etcd.delete(module.params["key"])
212 except Exception as exp:
213 module.fail_json(
214 msg=f"Cannot delete {module.params['key']}: {exp}", exception=traceback.format_exc()
215 )
216 else:
217 result["changed"] = True
218 elif module.params["state"] == "present":
219 if result["old_value"] != module.params["value"]:
220 if module.check_mode:
221 result["changed"] = True
222 else:
223 try:
224 etcd.put(module.params["key"], module.params["value"])
225 except Exception as exp:
226 module.fail_json(
227 msg=f"Cannot add or edit key {module.params['key']}: {exp}", exception=traceback.format_exc()
228 )
229 else:
230 result["changed"] = True
231 else:
232 module.fail_json(msg="State not recognized")
233
234 # manipulate or modify the state as needed (this is going to be the
235 # part where your module will do what it needs to do)
236
237 # during the execution of the module, if there is an exception or a
238 # conditional state that effectively causes a failure, run
239 # AnsibleModule.fail_json() to pass in the message and the result
240
241 # in the event of a successful module execution, you will want to
242 # simple AnsibleModule.exit_json(), passing the key/value results
243 module.exit_json(**result)
244
245
246 def main():
247 run_module()
248
249
250 if __name__ == "__main__":
251 main()