| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright (c) 2015, Steve Gargan <[email protected]> |
| 4 |
# Copyright (c) 2018 Genome Research Ltd. |
| 5 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
module: consul_kv |
| 12 |
short_description: Manipulate entries in the key/value store of a Consul cluster |
| 13 |
description: |
| 14 |
- Allows the retrieval, addition, modification and deletion of key/value entries in a Consul cluster using the agent. The |
| 15 |
entire contents of the record, including the indices, flags and session are returned as RV(ignore:value). |
| 16 |
- If the O(key) represents a prefix then note that when a value is removed, the existing value if any is returned as part |
| 17 |
of the results. |
| 18 |
- See http://www.consul.io/docs/agent/http.html#kv for more details. |
| 19 |
requirements: |
| 20 |
- py-consul |
| 21 |
- requests |
| 22 |
author: |
| 23 |
- Steve Gargan (@sgargan) |
| 24 |
- Colin Nolan (@colin-nolan) |
| 25 |
extends_documentation_fragment: |
| 26 |
- community.general._attributes |
| 27 |
attributes: |
| 28 |
check_mode: |
| 29 |
support: full |
| 30 |
diff_mode: |
| 31 |
support: none |
| 32 |
options: |
| 33 |
state: |
| 34 |
description: |
| 35 |
- The action to take with the supplied key and value. If the state is V(present) and O(value) is set, the key contents |
| 36 |
is set to the value supplied and RV(ignore:changed) is set to V(true) only if the value was different to the current contents. |
| 37 |
If the state is V(present) and O(value) is not set, the existing value associated to the key is returned. The state |
| 38 |
V(absent) is used to remove the key/value pair, again RV(ignore:changed) is set to V(true) only if the key actually existed |
| 39 |
prior to the removal. An attempt can be made to obtain or free the lock associated with a key/value pair with the |
| 40 |
states V(acquire) or V(release) respectively. A valid session must be supplied to make the attempt RV(ignore:changed) is V(true) |
| 41 |
if the attempt is successful, V(false) otherwise. |
| 42 |
type: str |
| 43 |
choices: [absent, acquire, present, release] |
| 44 |
default: present |
| 45 |
key: |
| 46 |
description: |
| 47 |
- The key at which the value should be stored. |
| 48 |
type: str |
| 49 |
required: true |
| 50 |
value: |
| 51 |
description: |
| 52 |
- The value should be associated with the given key, required if O(state) is V(present). |
| 53 |
type: str |
| 54 |
recurse: |
| 55 |
description: |
| 56 |
- If the key represents a prefix, each entry with the prefix can be retrieved by setting this to V(true). |
| 57 |
type: bool |
| 58 |
retrieve: |
| 59 |
description: |
| 60 |
- If the O(state) is V(present) and O(value) is set, perform a read after setting the value and return this value. |
| 61 |
default: true |
| 62 |
type: bool |
| 63 |
session: |
| 64 |
description: |
| 65 |
- The session that should be used to acquire or release a lock associated with a key/value pair. |
| 66 |
type: str |
| 67 |
token: |
| 68 |
description: |
| 69 |
- The token key identifying an ACL rule set that controls access to the key value pair. |
| 70 |
type: str |
| 71 |
cas: |
| 72 |
description: |
| 73 |
- Used when acquiring a lock with a session. If the O(cas) is V(0), then Consul only puts the key if it does not already |
| 74 |
exist. If the O(cas) value is non-zero, then the key is only set if the index matches the ModifyIndex of that key. |
| 75 |
type: str |
| 76 |
flags: |
| 77 |
description: |
| 78 |
- Opaque positive integer value that can be passed when setting a value. |
| 79 |
type: str |
| 80 |
host: |
| 81 |
description: |
| 82 |
- Host of the Consul agent. |
| 83 |
type: str |
| 84 |
default: localhost |
| 85 |
port: |
| 86 |
description: |
| 87 |
- The port on which the Consul agent is running. |
| 88 |
type: int |
| 89 |
default: 8500 |
| 90 |
scheme: |
| 91 |
description: |
| 92 |
- The protocol scheme on which the Consul agent is running. |
| 93 |
type: str |
| 94 |
default: http |
| 95 |
validate_certs: |
| 96 |
description: |
| 97 |
- Whether to verify the TLS certificate of the Consul agent. |
| 98 |
- Instead of setting this to V(false), please consider using O(ca_path) instead. |
| 99 |
type: bool |
| 100 |
default: true |
| 101 |
ca_path: |
| 102 |
description: |
| 103 |
- The CA bundle to use for HTTPS connections. |
| 104 |
type: str |
| 105 |
version_added: "12.6.0" |
| 106 |
datacenter: |
| 107 |
description: |
| 108 |
- The name of the datacenter to query. If unspecified, the query defaults to the datacenter of the Consul agent on O(host). |
| 109 |
type: str |
| 110 |
version_added: 10.0.0 |
| 111 |
""" |
| 112 |
|
| 113 |
|
| 114 |
EXAMPLES = r""" |
| 115 |
# If the key does not exist, the value associated to the "data" property in `retrieved_key` will be `None` |
| 116 |
# If the key value is empty string, `retrieved_key["data"]["Value"]` will be `None` |
| 117 |
- name: Retrieve a value from the key/value store |
| 118 |
community.general.consul_kv: |
| 119 |
key: somekey |
| 120 |
register: retrieved_key |
| 121 |
|
| 122 |
- name: Add or update the value associated with a key in the key/value store |
| 123 |
community.general.consul_kv: |
| 124 |
key: somekey |
| 125 |
value: somevalue |
| 126 |
|
| 127 |
- name: Remove a key from the store |
| 128 |
community.general.consul_kv: |
| 129 |
key: somekey |
| 130 |
state: absent |
| 131 |
|
| 132 |
- name: Add a node to an arbitrary group using Consul inventory (see consul.ini) |
| 133 |
community.general.consul_kv: |
| 134 |
key: ansible/groups/dc1/somenode |
| 135 |
value: top_secret |
| 136 |
|
| 137 |
- name: Register a key/value pair with an associated session |
| 138 |
community.general.consul_kv: |
| 139 |
key: stg/node/server_birthday |
| 140 |
value: 20160509 |
| 141 |
session: "{{ sessionid }}" |
| 142 |
state: acquire |
| 143 |
""" |
| 144 |
|
| 145 |
from ansible.module_utils.common.text.converters import to_text |
| 146 |
|
| 147 |
try: |
| 148 |
import consul |
| 149 |
from requests.exceptions import ConnectionError |
| 150 |
|
| 151 |
python_consul_installed = True |
| 152 |
except ImportError: |
| 153 |
python_consul_installed = False |
| 154 |
|
| 155 |
from ansible.module_utils.basic import AnsibleModule |
| 156 |
|
| 157 |
# Note: although the py-consul implementation implies that using a key with a value of `None` with `put` has a special |
| 158 |
# meaning (https://github.com/criteo/py-consul/blob/master/consul/api/kv.py), if not set in the subsequently API call, |
| 159 |
# the value just defaults to an empty string (https://www.consul.io/api/kv.html#create-update-key) |
| 160 |
NOT_SET = None |
| 161 |
|
| 162 |
|
| 163 |
def _has_value_changed(consul_client, key, target_value): |
| 164 |
""" |
| 165 |
Uses the given Consul client to determine if the value associated to the given key is different to the given target |
| 166 |
value. |
| 167 |
:param consul_client: Consul connected client |
| 168 |
:param key: key in Consul |
| 169 |
:param target_value: value to be associated to the key |
| 170 |
:return: tuple where the first element is the value of the "X-Consul-Index" header and the second is `True` if the |
| 171 |
value has changed (i.e. the stored value is not the target value) |
| 172 |
""" |
| 173 |
index, existing = consul_client.kv.get(key) |
| 174 |
if not existing: |
| 175 |
return index, True |
| 176 |
try: |
| 177 |
changed = to_text(existing["Value"], errors="surrogate_or_strict") != target_value |
| 178 |
return index, changed |
| 179 |
except UnicodeError: |
| 180 |
# Existing value was not decodable but all values we set are valid utf-8 |
| 181 |
return index, True |
| 182 |
|
| 183 |
|
| 184 |
def execute(module): |
| 185 |
state = module.params.get("state") |
| 186 |
|
| 187 |
if state == "acquire" or state == "release": |
| 188 |
lock(module, state) |
| 189 |
elif state == "present": |
| 190 |
if module.params.get("value") is NOT_SET: |
| 191 |
get_value(module) |
| 192 |
else: |
| 193 |
set_value(module) |
| 194 |
elif state == "absent": |
| 195 |
remove_value(module) |
| 196 |
else: |
| 197 |
module.exit_json(msg=f"Unsupported state: {state}") |
| 198 |
|
| 199 |
|
| 200 |
def lock(module, state): |
| 201 |
consul_api = get_consul_api(module) |
| 202 |
|
| 203 |
session = module.params.get("session") |
| 204 |
key = module.params.get("key") |
| 205 |
value = module.params.get("value") |
| 206 |
|
| 207 |
if not session: |
| 208 |
module.fail(msg=f"{state} of lock for {key} requested but no session supplied") |
| 209 |
|
| 210 |
index, changed = _has_value_changed(consul_api, key, value) |
| 211 |
|
| 212 |
if changed and not module.check_mode: |
| 213 |
if state == "acquire": |
| 214 |
changed = consul_api.kv.put( |
| 215 |
key, value, cas=module.params.get("cas"), acquire=session, flags=module.params.get("flags") |
| 216 |
) |
| 217 |
else: |
| 218 |
changed = consul_api.kv.put( |
| 219 |
key, value, cas=module.params.get("cas"), release=session, flags=module.params.get("flags") |
| 220 |
) |
| 221 |
|
| 222 |
module.exit_json(changed=changed, index=index, key=key) |
| 223 |
|
| 224 |
|
| 225 |
def get_value(module): |
| 226 |
consul_api = get_consul_api(module) |
| 227 |
key = module.params.get("key") |
| 228 |
|
| 229 |
index, existing_value = consul_api.kv.get(key, recurse=module.params.get("recurse")) |
| 230 |
|
| 231 |
module.exit_json(changed=False, index=index, data=existing_value) |
| 232 |
|
| 233 |
|
| 234 |
def set_value(module): |
| 235 |
consul_api = get_consul_api(module) |
| 236 |
|
| 237 |
key = module.params.get("key") |
| 238 |
value = module.params.get("value") |
| 239 |
|
| 240 |
if value is NOT_SET: |
| 241 |
raise AssertionError(f'Cannot set value of "{key}" to `NOT_SET`') |
| 242 |
|
| 243 |
index, changed = _has_value_changed(consul_api, key, value) |
| 244 |
|
| 245 |
if changed and not module.check_mode: |
| 246 |
changed = consul_api.kv.put(key, value, cas=module.params.get("cas"), flags=module.params.get("flags")) |
| 247 |
|
| 248 |
stored = None |
| 249 |
if module.params.get("retrieve"): |
| 250 |
index, stored = consul_api.kv.get(key) |
| 251 |
|
| 252 |
module.exit_json(changed=changed, index=index, key=key, data=stored) |
| 253 |
|
| 254 |
|
| 255 |
def remove_value(module): |
| 256 |
"""remove the value associated with the given key. if the recurse parameter |
| 257 |
is set then any key prefixed with the given key will be removed.""" |
| 258 |
consul_api = get_consul_api(module) |
| 259 |
|
| 260 |
key = module.params.get("key") |
| 261 |
|
| 262 |
index, existing = consul_api.kv.get(key, recurse=module.params.get("recurse")) |
| 263 |
|
| 264 |
changed = existing is not None |
| 265 |
if changed and not module.check_mode: |
| 266 |
consul_api.kv.delete(key, module.params.get("recurse")) |
| 267 |
|
| 268 |
module.exit_json(changed=changed, index=index, key=key, data=existing) |
| 269 |
|
| 270 |
|
| 271 |
def get_consul_api(module): |
| 272 |
ca_path = module.params.get("ca_path") |
| 273 |
validate_certs = module.params.get("validate_certs") |
| 274 |
verify = (ca_path or validate_certs) if validate_certs else False |
| 275 |
return consul.Consul( |
| 276 |
host=module.params.get("host"), |
| 277 |
port=module.params.get("port"), |
| 278 |
scheme=module.params.get("scheme"), |
| 279 |
verify=verify, |
| 280 |
token=module.params.get("token"), |
| 281 |
dc=module.params.get("datacenter"), |
| 282 |
) |
| 283 |
|
| 284 |
|
| 285 |
def test_dependencies(module): |
| 286 |
if not python_consul_installed: |
| 287 |
module.fail_json( |
| 288 |
msg="python-consul required for this module. " |
| 289 |
"see https://python-consul.readthedocs.io/en/latest/#installation" |
| 290 |
) |
| 291 |
|
| 292 |
|
| 293 |
def main(): |
| 294 |
module = AnsibleModule( |
| 295 |
argument_spec=dict( |
| 296 |
cas=dict(type="str"), |
| 297 |
datacenter=dict(type="str"), |
| 298 |
flags=dict(type="str"), |
| 299 |
key=dict(type="str", required=True, no_log=False), |
| 300 |
host=dict(type="str", default="localhost"), |
| 301 |
scheme=dict(type="str", default="http"), |
| 302 |
validate_certs=dict(type="bool", default=True), |
| 303 |
ca_path=dict(type="str"), |
| 304 |
port=dict(type="int", default=8500), |
| 305 |
recurse=dict(type="bool"), |
| 306 |
retrieve=dict(type="bool", default=True), |
| 307 |
state=dict(type="str", default="present", choices=["absent", "acquire", "present", "release"]), |
| 308 |
token=dict(type="str", no_log=True), |
| 309 |
value=dict(type="str", default=NOT_SET), |
| 310 |
session=dict(type="str"), |
| 311 |
), |
| 312 |
supports_check_mode=True, |
| 313 |
) |
| 314 |
|
| 315 |
test_dependencies(module) |
| 316 |
|
| 317 |
try: |
| 318 |
execute(module) |
| 319 |
except ConnectionError as e: |
| 320 |
module.fail_json( |
| 321 |
msg=f"Could not connect to consul agent at {module.params.get('host')}:{module.params.get('port')}, error was {e}" |
| 322 |
) |
| 323 |
except Exception as e: |
| 324 |
module.fail_json(msg=str(e)) |
| 325 |
|
| 326 |
|
| 327 |
if __name__ == "__main__": |
| 328 |
main() |