Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2021, Andreas Botzner <andreas at botzner dot com>
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_data
11 short_description: Set key value pairs in Redis
12 version_added: 3.7.0
13 description:
14 - Set key value pairs in Redis database.
15 author: "Andreas Botzner (@paginabianca)"
16 attributes:
17 check_mode:
18 support: full
19 diff_mode:
20 support: none
21 options:
22 key:
23 description:
24 - Database key.
25 required: true
26 type: str
27 value:
28 description:
29 - Value that key should be set to.
30 type: str
31 expiration:
32 description:
33 - Expiration time in milliseconds. Setting this option always results in a change in the database.
34 type: int
35 non_existing:
36 description:
37 - Only set key if it does not already exist.
38 type: bool
39 existing:
40 description:
41 - Only set key if it already exists.
42 type: bool
43 keep_ttl:
44 description:
45 - Retain the time to live associated with the key.
46 type: bool
47 state:
48 description:
49 - State of the key.
50 default: present
51 type: str
52 choices:
53 - present
54 - absent
55
56 extends_documentation_fragment:
57 - community.general._redis.documentation
58 - community.general._attributes
59
60 seealso:
61 - module: community.general.redis_data_incr
62 - module: community.general.redis_data_info
63 - module: community.general.redis
64 """
65
66 EXAMPLES = r"""
67 - name: Set key foo=bar on localhost with no username
68 community.general.redis_data:
69 login_host: localhost
70 login_password: supersecret
71 key: foo
72 value: bar
73 state: present
74
75 - name: Set key foo=bar if non existing with expiration of 30s
76 community.general.redis_data:
77 login_host: localhost
78 login_password: supersecret
79 key: foo
80 value: bar
81 non_existing: true
82 expiration: 30000
83 state: present
84
85 - name: Set key foo=bar if existing and keep current TTL
86 community.general.redis_data:
87 login_host: localhost
88 login_password: supersecret
89 key: foo
90 value: bar
91 existing: true
92 keep_ttl: true
93
94 - name: Set key foo=bar on redishost with custom ca-cert file
95 community.general.redis_data:
96 login_host: redishost
97 login_password: supersecret
98 login_user: someuser
99 validate_certs: true
100 ssl_ca_certs: /path/to/ca/certs
101 key: foo
102 value: bar
103
104 - name: Delete key foo on localhost with no username
105 community.general.redis_data:
106 login_host: localhost
107 login_password: supersecret
108 key: foo
109 state: absent
110 """
111
112 RETURN = r"""
113 old_value:
114 description: Value of key before setting.
115 returned: on_success if O(state=present) and key exists in database.
116 type: str
117 sample: 'old_value_of_key'
118 value:
119 description: Value key was set to.
120 returned: on success if O(state=present).
121 type: str
122 sample: 'new_value_of_key'
123 msg:
124 description: A short message.
125 returned: always
126 type: str
127 sample: 'Set key: foo to bar'
128 """
129
130 from ansible.module_utils.basic import AnsibleModule
131
132 from ansible_collections.community.general.plugins.module_utils._redis import (
133 RedisAnsible,
134 fail_imports,
135 redis_auth_argument_spec,
136 )
137
138
139 def main():
140 redis_auth_args = redis_auth_argument_spec()
141 module_args = dict(
142 key=dict(type="str", required=True, no_log=False),
143 value=dict(type="str"),
144 expiration=dict(type="int"),
145 non_existing=dict(type="bool"),
146 existing=dict(type="bool"),
147 keep_ttl=dict(type="bool"),
148 state=dict(type="str", default="present", choices=["present", "absent"]),
149 )
150 module_args.update(redis_auth_args)
151
152 module = AnsibleModule(
153 argument_spec=module_args,
154 supports_check_mode=True,
155 required_if=[("state", "present", ("value",))],
156 mutually_exclusive=[["non_existing", "existing"], ["keep_ttl", "expiration"]],
157 )
158 fail_imports(module)
159
160 redis = RedisAnsible(module)
161
162 key = module.params["key"]
163 value = module.params["value"]
164 px = module.params["expiration"]
165 nx = module.params["non_existing"]
166 xx = module.params["existing"]
167 keepttl = module.params["keep_ttl"]
168 state = module.params["state"]
169 set_args = {"name": key, "value": value, "px": px, "nx": nx, "xx": xx, "keepttl": keepttl}
170
171 result = {"changed": False}
172
173 old_value = None
174 try:
175 old_value = redis.connection.get(key)
176 except Exception as e:
177 msg = f"Failed to get value of key: {key} with exception: {e}"
178 result["msg"] = msg
179 module.fail_json(**result)
180
181 if state == "absent":
182 if module.check_mode:
183 if old_value is None:
184 msg = f"Key: {key} not present"
185 result["msg"] = msg
186 module.exit_json(**result)
187 else:
188 msg = f"Deleted key: {key}"
189 result["msg"] = msg
190 module.exit_json(**result)
191 try:
192 ret = redis.connection.delete(key)
193 if ret == 0:
194 msg = f"Key: {key} not present"
195 result["msg"] = msg
196 module.exit_json(**result)
197 else:
198 msg = f"Deleted key: {key}"
199 result["msg"] = msg
200 result["changed"] = True
201 module.exit_json(**result)
202 except Exception as e:
203 msg = f"Failed to delete key: {key} with exception: {e}"
204 result["msg"] = msg
205 module.fail_json(**result)
206
207 old_value = None
208 try:
209 old_value = redis.connection.get(key)
210 except Exception as e:
211 msg = f"Failed to get value of key: {key} with exception: {e}"
212 result["msg"] = msg
213 module.fail_json(**result)
214
215 result["old_value"] = old_value
216 if old_value == value and keepttl is not False and px is None:
217 msg = f"Key {key} already has desired value"
218 result["msg"] = msg
219 result["value"] = value
220 module.exit_json(**result)
221 if module.check_mode:
222 result["msg"] = f"Set key: {key}"
223 result["value"] = value
224 module.exit_json(**result)
225 try:
226 ret = redis.connection.set(**set_args)
227 if ret is None:
228 if nx:
229 msg = f"Could not set key: {key}. Key already present."
230 else:
231 msg = f"Could not set key: {key}. Key not present."
232 result["msg"] = msg
233 module.fail_json(**result)
234 msg = f"Set key: {key}"
235 result["msg"] = msg
236 result["changed"] = True
237 result["value"] = value
238 module.exit_json(**result)
239 except Exception as e:
240 msg = f"Failed to set key: {key} with exception: {e}"
241 result["msg"] = msg
242 module.fail_json(**result)
243
244
245 if __name__ == "__main__":
246 main()