Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2015, Steve Gargan <[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: consul_session
11 short_description: Manipulate Consul sessions
12 description:
13 - Allows the addition, modification and deletion of sessions in a Consul cluster. These sessions can then be used in conjunction
14 with key value pairs to implement distributed locks. In depth documentation for working with sessions can be found at
15 U(http://www.consul.io/docs/internals/sessions.html).
16 author:
17 - Steve Gargan (@sgargan)
18 - Håkon Lerring (@Hakon)
19 extends_documentation_fragment:
20 - community.general._consul
21 - community.general._consul.actiongroup_consul
22 - community.general._consul.token
23 - community.general._attributes
24 attributes:
25 check_mode:
26 support: none
27 diff_mode:
28 support: none
29 action_group:
30 version_added: 8.3.0
31 options:
32 id:
33 description:
34 - ID of the session, required when O(state) is either V(info) or V(remove).
35 type: str
36 state:
37 description:
38 - Whether the session should be present, in other words it should be created if it does not exist, or absent, removed
39 if present. If created, the O(id) for the session is returned in the output. If V(absent), O(id) is required to remove
40 the session. Info for a single session, all the sessions for a node or all available sessions can be retrieved by
41 specifying V(info), V(node) or V(list) for the O(state); for V(node) or V(info), the node O(name) or session O(id)
42 is required as parameter.
43 choices: [absent, info, list, node, present]
44 type: str
45 default: present
46 name:
47 description:
48 - The name that should be associated with the session. Required when O(state=node) is used.
49 type: str
50 delay:
51 description:
52 - The optional lock delay that can be attached to the session when it is created. Locks for invalidated sessions ar
53 blocked from being acquired until this delay has expired. Durations are in seconds.
54 type: int
55 default: 15
56 node:
57 description:
58 - The name of the node that with which the session is associated. By default this is the name of the agent.
59 type: str
60 datacenter:
61 description:
62 - The name of the datacenter in which the session exists or should be created.
63 type: str
64 checks:
65 description:
66 - Checks that are used to verify the session health. If all the checks fail, the session is invalidated and any locks
67 associated with the session are released and can be acquired once the associated lock delay has expired.
68 type: list
69 elements: str
70 behavior:
71 description:
72 - The optional behavior that can be attached to the session when it is created. This controls the behavior when a session
73 is invalidated.
74 choices: [delete, release]
75 type: str
76 default: release
77 ttl:
78 description:
79 - Specifies the duration of a session in seconds (between 10 and 86400).
80 type: int
81 version_added: 5.4.0
82 token:
83 version_added: 5.6.0
84 """
85
86 EXAMPLES = r"""
87 - name: Register basic session with Consul
88 community.general.consul_session:
89 name: session1
90
91 - name: Register a session with an existing check
92 community.general.consul_session:
93 name: session_with_check
94 checks:
95 - existing_check_name
96
97 - name: Register a session with lock_delay
98 community.general.consul_session:
99 name: session_with_delay
100 delay: 20s
101
102 - name: Retrieve info about session by id
103 community.general.consul_session:
104 id: session_id
105 state: info
106
107 - name: Retrieve active sessions
108 community.general.consul_session:
109 state: list
110
111 - name: Register session with a ttl
112 community.general.consul_session:
113 name: session-with-ttl
114 ttl: 600 # sec
115 """
116
117 from ansible.module_utils.basic import AnsibleModule
118
119 from ansible_collections.community.general.plugins.module_utils._consul import AUTH_ARGUMENTS_SPEC, _ConsulModule
120
121
122 def execute(module, consul_module):
123 state = module.params.get("state")
124
125 if state in ["info", "list", "node"]:
126 lookup_sessions(module, consul_module)
127 elif state == "present":
128 update_session(module, consul_module)
129 else:
130 remove_session(module, consul_module)
131
132
133 def list_sessions(consul_module, datacenter):
134 return consul_module.get("session/list", params={"dc": datacenter})
135
136
137 def list_sessions_for_node(consul_module, node, datacenter):
138 return consul_module.get(("session", "node", node), params={"dc": datacenter})
139
140
141 def get_session_info(consul_module, session_id, datacenter):
142 return consul_module.get(("session", "info", session_id), params={"dc": datacenter})
143
144
145 def lookup_sessions(module, consul_module):
146 datacenter = module.params.get("datacenter")
147
148 state = module.params.get("state")
149 try:
150 if state == "list":
151 sessions_list = list_sessions(consul_module, datacenter)
152 # Ditch the index, this can be grabbed from the results
153 if sessions_list and len(sessions_list) >= 2:
154 sessions_list = sessions_list[1]
155 module.exit_json(changed=True, sessions=sessions_list)
156 elif state == "node":
157 node = module.params.get("node")
158 sessions = list_sessions_for_node(consul_module, node, datacenter)
159 module.exit_json(changed=True, node=node, sessions=sessions)
160 elif state == "info":
161 session_id = module.params.get("id")
162
163 session_by_id = get_session_info(consul_module, session_id, datacenter)
164 module.exit_json(changed=True, session_id=session_id, sessions=session_by_id)
165
166 except Exception as e:
167 module.fail_json(msg=f"Could not retrieve session info {e}")
168
169
170 def create_session(consul_module, name, behavior, ttl, node, lock_delay, datacenter, checks):
171 create_data = {
172 "LockDelay": lock_delay,
173 "Node": node,
174 "Name": name,
175 "Checks": checks,
176 "Behavior": behavior,
177 }
178 if ttl is not None:
179 create_data["TTL"] = f"{ttl}s" # TTL is in seconds
180 create_session_response_dict = consul_module.put("session/create", params={"dc": datacenter}, data=create_data)
181 return create_session_response_dict["ID"]
182
183
184 def update_session(module, consul_module):
185 name = module.params.get("name")
186 delay = module.params.get("delay")
187 checks = module.params.get("checks")
188 datacenter = module.params.get("datacenter")
189 node = module.params.get("node")
190 behavior = module.params.get("behavior")
191 ttl = module.params.get("ttl")
192
193 try:
194 session = create_session(
195 consul_module,
196 name=name,
197 behavior=behavior,
198 ttl=ttl,
199 node=node,
200 lock_delay=delay,
201 datacenter=datacenter,
202 checks=checks,
203 )
204 module.exit_json(
205 changed=True,
206 session_id=session,
207 name=name,
208 behavior=behavior,
209 ttl=ttl,
210 delay=delay,
211 checks=checks,
212 node=node,
213 )
214 except Exception as e:
215 module.fail_json(msg=f"Could not create/update session {e}")
216
217
218 def destroy_session(consul_module, session_id):
219 return consul_module.put(("session", "destroy", session_id))
220
221
222 def remove_session(module, consul_module):
223 session_id = module.params.get("id")
224
225 try:
226 destroy_session(consul_module, session_id)
227
228 module.exit_json(changed=True, session_id=session_id)
229 except Exception as e:
230 module.fail_json(msg=f"Could not remove session with id '{session_id}' {e}")
231
232
233 def main():
234 argument_spec = dict(
235 checks=dict(type="list", elements="str"),
236 delay=dict(type="int", default="15"),
237 behavior=dict(type="str", default="release", choices=["release", "delete"]),
238 ttl=dict(type="int"),
239 id=dict(type="str"),
240 name=dict(type="str"),
241 node=dict(type="str"),
242 state=dict(type="str", default="present", choices=["absent", "info", "list", "node", "present"]),
243 datacenter=dict(type="str"),
244 **AUTH_ARGUMENTS_SPEC,
245 )
246
247 module = AnsibleModule(
248 argument_spec=argument_spec,
249 required_if=[
250 ("state", "node", ["name"]),
251 ("state", "info", ["id"]),
252 ("state", "remove", ["id"]),
253 ],
254 supports_check_mode=False,
255 )
256 consul_module = _ConsulModule(module)
257
258 try:
259 execute(module, consul_module)
260 except Exception as e:
261 module.fail_json(msg=str(e))
262
263
264 if __name__ == "__main__":
265 main()