| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# Copyright Ansible Project |
| 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: redis |
| 11 |
short_description: Various redis commands, replica and flush |
| 12 |
description: |
| 13 |
- Unified utility to interact with redis instances. |
| 14 |
extends_documentation_fragment: |
| 15 |
- community.general._redis |
| 16 |
- community.general._attributes |
| 17 |
attributes: |
| 18 |
check_mode: |
| 19 |
support: full |
| 20 |
diff_mode: |
| 21 |
support: none |
| 22 |
options: |
| 23 |
command: |
| 24 |
description: |
| 25 |
- The selected redis command. |
| 26 |
- V(config) ensures a configuration setting on an instance. |
| 27 |
- V(flush) flushes all the instance or a specified db. |
| 28 |
- V(replica) sets a redis instance in replica or master mode. (V(slave) is an alias for V(replica)). |
| 29 |
choices: [config, flush, replica, slave] |
| 30 |
type: str |
| 31 |
tls: |
| 32 |
default: false |
| 33 |
version_added: 4.6.0 |
| 34 |
login_user: |
| 35 |
version_added: 4.6.0 |
| 36 |
validate_certs: |
| 37 |
version_added: 4.6.0 |
| 38 |
ca_certs: |
| 39 |
version_added: 4.6.0 |
| 40 |
master_host: |
| 41 |
description: |
| 42 |
- The host of the master instance [replica command]. |
| 43 |
type: str |
| 44 |
master_port: |
| 45 |
description: |
| 46 |
- The port of the master instance [replica command]. |
| 47 |
type: int |
| 48 |
replica_mode: |
| 49 |
description: |
| 50 |
- The mode of the redis instance [replica command]. |
| 51 |
- V(slave) is an alias for V(replica). |
| 52 |
default: replica |
| 53 |
choices: [master, replica, slave] |
| 54 |
type: str |
| 55 |
aliases: |
| 56 |
- slave_mode |
| 57 |
db: |
| 58 |
description: |
| 59 |
- The database to flush (used in DB mode) [flush command]. |
| 60 |
type: int |
| 61 |
flush_mode: |
| 62 |
description: |
| 63 |
- Type of flush (all the DBs in a redis instance or a specific one) [flush command]. |
| 64 |
default: all |
| 65 |
choices: [all, db] |
| 66 |
type: str |
| 67 |
name: |
| 68 |
description: |
| 69 |
- A redis config key. |
| 70 |
type: str |
| 71 |
value: |
| 72 |
description: |
| 73 |
- A redis config value. When memory size is needed, it is possible to specify it in the usual form of 1KB, 2M, 400MB |
| 74 |
where the base is 1024. Units are case insensitive, in other words 1m = 1mb = 1M = 1MB. |
| 75 |
type: str |
| 76 |
|
| 77 |
notes: |
| 78 |
- Requires the C(redis-py) Python package on the remote host. You can install it with pip (C(pip install redis)) or with |
| 79 |
a package manager. U(https://github.com/andymccurdy/redis-py). |
| 80 |
- If the redis master instance you are making replica of is password protected this needs to be in the C(redis.conf) in |
| 81 |
the C(masterauth) variable. |
| 82 |
seealso: |
| 83 |
- module: community.general.redis_info |
| 84 |
requirements: [redis] |
| 85 |
author: "Xabier Larrakoetxea (@slok)" |
| 86 |
""" |
| 87 |
|
| 88 |
EXAMPLES = r""" |
| 89 |
- name: Set local redis instance to be a replica of melee.island on port 6377 |
| 90 |
community.general.redis: |
| 91 |
command: replica |
| 92 |
master_host: melee.island |
| 93 |
master_port: 6377 |
| 94 |
|
| 95 |
- name: Deactivate replica mode |
| 96 |
community.general.redis: |
| 97 |
command: replica |
| 98 |
replica_mode: master |
| 99 |
|
| 100 |
- name: Flush all the redis db |
| 101 |
community.general.redis: |
| 102 |
command: flush |
| 103 |
flush_mode: all |
| 104 |
|
| 105 |
- name: Flush only one db in a redis instance |
| 106 |
community.general.redis: |
| 107 |
command: flush |
| 108 |
db: 1 |
| 109 |
flush_mode: db |
| 110 |
|
| 111 |
- name: Configure local redis to have 10000 max clients |
| 112 |
community.general.redis: |
| 113 |
command: config |
| 114 |
name: maxclients |
| 115 |
value: 10000 |
| 116 |
|
| 117 |
- name: Configure local redis maxmemory to 4GB |
| 118 |
community.general.redis: |
| 119 |
command: config |
| 120 |
name: maxmemory |
| 121 |
value: 4GB |
| 122 |
|
| 123 |
- name: Configure local redis to have lua time limit of 100 ms |
| 124 |
community.general.redis: |
| 125 |
command: config |
| 126 |
name: lua-time-limit |
| 127 |
value: 100 |
| 128 |
|
| 129 |
- name: Connect using TLS and certificate authentication |
| 130 |
community.general.redis: |
| 131 |
command: config |
| 132 |
name: lua-time-limit |
| 133 |
value: 100 |
| 134 |
tls: true |
| 135 |
ca_certs: /etc/redis/certs/ca.crt |
| 136 |
client_cert_file: /etc/redis/certs/redis.crt |
| 137 |
client_key_file: /etc/redis/certs/redis.key |
| 138 |
""" |
| 139 |
|
| 140 |
import traceback |
| 141 |
|
| 142 |
REDIS_IMP_ERR = None |
| 143 |
try: |
| 144 |
import redis |
| 145 |
except ImportError: |
| 146 |
REDIS_IMP_ERR = traceback.format_exc() |
| 147 |
redis_found = False |
| 148 |
else: |
| 149 |
redis_found = True |
| 150 |
|
| 151 |
import re |
| 152 |
|
| 153 |
from ansible.module_utils.basic import AnsibleModule |
| 154 |
from ansible.module_utils.common.text.formatters import human_to_bytes |
| 155 |
|
| 156 |
from ansible_collections.community.general.plugins.module_utils._redis import ( |
| 157 |
fail_imports, |
| 158 |
redis_auth_argument_spec, |
| 159 |
redis_auth_params, |
| 160 |
) |
| 161 |
|
| 162 |
|
| 163 |
# Redis module specific support methods. |
| 164 |
def set_replica_mode(client, master_host, master_port): |
| 165 |
try: |
| 166 |
return client.slaveof(master_host, master_port) |
| 167 |
except Exception: |
| 168 |
return False |
| 169 |
|
| 170 |
|
| 171 |
def set_master_mode(client): |
| 172 |
try: |
| 173 |
return client.slaveof() |
| 174 |
except Exception: |
| 175 |
return False |
| 176 |
|
| 177 |
|
| 178 |
def flush(client, db=None): |
| 179 |
try: |
| 180 |
if not isinstance(db, int): |
| 181 |
return client.flushall() |
| 182 |
else: |
| 183 |
# The passed client has been connected to the database already |
| 184 |
return client.flushdb() |
| 185 |
except Exception: |
| 186 |
return False |
| 187 |
|
| 188 |
|
| 189 |
# Module execution. |
| 190 |
def main(): |
| 191 |
redis_auth_args = redis_auth_argument_spec(tls_default=False) |
| 192 |
module_args = dict( |
| 193 |
command=dict(type="str", choices=["config", "flush", "replica", "slave"]), |
| 194 |
master_host=dict(type="str"), |
| 195 |
master_port=dict(type="int"), |
| 196 |
replica_mode=dict( |
| 197 |
type="str", default="replica", choices=["master", "replica", "slave"], aliases=["slave_mode"] |
| 198 |
), |
| 199 |
db=dict(type="int"), |
| 200 |
flush_mode=dict(type="str", default="all", choices=["all", "db"]), |
| 201 |
name=dict(type="str"), |
| 202 |
value=dict(type="str"), |
| 203 |
) |
| 204 |
module_args.update(redis_auth_args) |
| 205 |
module = AnsibleModule( |
| 206 |
argument_spec=module_args, |
| 207 |
supports_check_mode=True, |
| 208 |
) |
| 209 |
|
| 210 |
fail_imports(module, module.params["tls"]) |
| 211 |
|
| 212 |
redis_params = redis_auth_params(module) |
| 213 |
|
| 214 |
command = module.params["command"] |
| 215 |
if command == "slave": |
| 216 |
command = "replica" |
| 217 |
|
| 218 |
# Replica Command section ----------- |
| 219 |
if command == "replica": |
| 220 |
master_host = module.params["master_host"] |
| 221 |
master_port = module.params["master_port"] |
| 222 |
mode = module.params["replica_mode"] |
| 223 |
if mode == "slave": |
| 224 |
mode = "replica" |
| 225 |
|
| 226 |
# Check if we have all the data |
| 227 |
if mode == "replica": # Only need data if we want to be replica |
| 228 |
if not master_host: |
| 229 |
module.fail_json(msg="In replica mode master host must be provided") |
| 230 |
|
| 231 |
if not master_port: |
| 232 |
module.fail_json(msg="In replica mode master port must be provided") |
| 233 |
|
| 234 |
# Connect and check |
| 235 |
r = redis.StrictRedis(**redis_params) |
| 236 |
try: |
| 237 |
r.ping() |
| 238 |
except Exception as e: |
| 239 |
module.fail_json(msg=f"unable to connect to database: {e}", exception=traceback.format_exc()) |
| 240 |
|
| 241 |
# Check if we are already in the mode that we want |
| 242 |
info = r.info() |
| 243 |
if mode == "master" and info["role"] == "master": |
| 244 |
module.exit_json(changed=False, mode=mode) |
| 245 |
|
| 246 |
elif ( |
| 247 |
mode == "replica" |
| 248 |
and info["role"] == "slave" |
| 249 |
and info["master_host"] == master_host |
| 250 |
and info["master_port"] == master_port |
| 251 |
): |
| 252 |
status = dict( |
| 253 |
status=mode, |
| 254 |
master_host=master_host, |
| 255 |
master_port=master_port, |
| 256 |
) |
| 257 |
module.exit_json(changed=False, mode=status) |
| 258 |
else: |
| 259 |
# Do the stuff |
| 260 |
# (Check Check_mode before commands so the commands aren't evaluated |
| 261 |
# if not necessary) |
| 262 |
if mode == "replica": |
| 263 |
if module.check_mode or set_replica_mode(r, master_host, master_port): |
| 264 |
info = r.info() |
| 265 |
status = { |
| 266 |
"status": mode, |
| 267 |
"master_host": master_host, |
| 268 |
"master_port": master_port, |
| 269 |
} |
| 270 |
module.exit_json(changed=True, mode=status) |
| 271 |
else: |
| 272 |
module.fail_json(msg="Unable to set replica mode") |
| 273 |
|
| 274 |
else: |
| 275 |
if module.check_mode or set_master_mode(r): |
| 276 |
module.exit_json(changed=True, mode=mode) |
| 277 |
else: |
| 278 |
module.fail_json(msg="Unable to set master mode") |
| 279 |
|
| 280 |
# flush Command section ----------- |
| 281 |
elif command == "flush": |
| 282 |
db = module.params["db"] |
| 283 |
mode = module.params["flush_mode"] |
| 284 |
|
| 285 |
# Check if we have all the data |
| 286 |
if mode == "db": |
| 287 |
if db is None: |
| 288 |
module.fail_json(msg="In db mode the db number must be provided") |
| 289 |
|
| 290 |
# Connect and check |
| 291 |
r = redis.StrictRedis(db=db, **redis_params) |
| 292 |
try: |
| 293 |
r.ping() |
| 294 |
except Exception as e: |
| 295 |
module.fail_json(msg=f"unable to connect to database: {e}", exception=traceback.format_exc()) |
| 296 |
|
| 297 |
# Do the stuff |
| 298 |
# (Check Check_mode before commands so the commands aren't evaluated |
| 299 |
# if not necessary) |
| 300 |
if mode == "all": |
| 301 |
if module.check_mode or flush(r): |
| 302 |
module.exit_json(changed=True, flushed=True) |
| 303 |
else: # Flush never fails :) |
| 304 |
module.fail_json(msg="Unable to flush all databases") |
| 305 |
|
| 306 |
else: |
| 307 |
if module.check_mode or flush(r, db): |
| 308 |
module.exit_json(changed=True, flushed=True, db=db) |
| 309 |
else: # Flush never fails :) |
| 310 |
module.fail_json(msg=f"Unable to flush '{db}' database") |
| 311 |
elif command == "config": |
| 312 |
name = module.params["name"] |
| 313 |
|
| 314 |
try: # try to parse the value as if it were the memory size |
| 315 |
if re.match(r"^\s*(\d*\.?\d*)\s*([A-Za-z]+)?\s*$", module.params["value"].upper()): |
| 316 |
value = str(human_to_bytes(module.params["value"].upper())) |
| 317 |
else: |
| 318 |
value = module.params["value"] |
| 319 |
except ValueError: |
| 320 |
value = module.params["value"] |
| 321 |
|
| 322 |
r = redis.StrictRedis(**redis_params) |
| 323 |
|
| 324 |
try: |
| 325 |
r.ping() |
| 326 |
except Exception as e: |
| 327 |
module.fail_json(msg=f"unable to connect to database: {e}", exception=traceback.format_exc()) |
| 328 |
|
| 329 |
try: |
| 330 |
old_value = r.config_get(name)[name] |
| 331 |
except Exception as e: |
| 332 |
module.fail_json(msg=f"unable to read config: {e}", exception=traceback.format_exc()) |
| 333 |
changed = old_value != value |
| 334 |
|
| 335 |
if module.check_mode or not changed: |
| 336 |
module.exit_json(changed=changed, name=name, value=value) |
| 337 |
else: |
| 338 |
try: |
| 339 |
r.config_set(name, value) |
| 340 |
except Exception as e: |
| 341 |
module.fail_json(msg=f"unable to write config: {e}", exception=traceback.format_exc()) |
| 342 |
module.exit_json(changed=changed, name=name, value=value) |
| 343 |
else: |
| 344 |
module.fail_json(msg="A valid command must be provided") |
| 345 |
|
| 346 |
|
| 347 |
if __name__ == "__main__": |
| 348 |
main() |