Debian Codegraph @

ansible_collections/community/general/plugins/modules/consul.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
11 short_description: Add, modify & delete services within a Consul cluster
12 description:
13 - Registers services and checks for an agent with a Consul cluster. A service is some process running on the agent node
14 that should be advertised by Consul's discovery mechanism. It may optionally supply a check definition, a periodic service
15 test to notify the Consul cluster of service's health.
16 - Checks may also be registered per node, for example disk usage, or cpu usage and notify the health of the entire node
17 to the cluster. Service level checks do not require a check name or ID as these are derived by Consul from the Service
18 name and ID respectively by appending V(service:) Node level checks require a O(check_name) and optionally a O(check_id).
19 - Currently, there is no complete way to retrieve the script, interval or TTL metadata for a registered check. Without this
20 metadata it is not possible to tell if the data supplied with ansible represents a change to a check. As a result this
21 does not attempt to determine changes and it always reports a changed occurred. An API method is planned to supply this
22 metadata so at that stage change management is to be added.
23 - See U(http://consul.io) for more details.
24 requirements:
25 - py-consul
26 - requests
27 author: "Steve Gargan (@sgargan)"
28 extends_documentation_fragment:
29 - community.general._attributes
30 attributes:
31 check_mode:
32 support: none
33 diff_mode:
34 support: none
35 options:
36 state:
37 type: str
38 description:
39 - Register or deregister the Consul service, defaults to present.
40 default: present
41 choices: ['present', 'absent']
42 service_name:
43 type: str
44 description:
45 - Unique name for the service on a node, must be unique per node, required if registering a service. May be omitted
46 if registering a node level check.
47 service_id:
48 type: str
49 description:
50 - The ID for the service, must be unique per node. If O(state=absent), defaults to the service name if supplied.
51 host:
52 type: str
53 description:
54 - Host of the Consul agent defaults to localhost.
55 default: localhost
56 port:
57 type: int
58 description:
59 - The port on which the Consul agent is running.
60 default: 8500
61 scheme:
62 type: str
63 description:
64 - The protocol scheme on which the Consul agent is running.
65 default: http
66 validate_certs:
67 description:
68 - Whether to verify the TLS certificate of the Consul agent.
69 type: bool
70 default: true
71 notes:
72 type: str
73 description:
74 - Notes to attach to check when registering it.
75 service_port:
76 type: int
77 description:
78 - The port on which the service is listening. Can optionally be supplied for registration of a service, that is if O(service_name)
79 or O(service_id) is set.
80 service_address:
81 type: str
82 description:
83 - The address to advertise that the service is listening on. This value is passed as the C(address) parameter to Consul's
84 C(/v1/agent/service/register) API method, so refer to the Consul API documentation for further details.
85 tags:
86 type: list
87 elements: str
88 description:
89 - Tags that are attached to the service registration.
90 script:
91 type: str
92 description:
93 - The script/command that is run periodically to check the health of the service.
94 - Requires O(interval) to be provided.
95 - Mutually exclusive with O(ttl), O(tcp) and O(http).
96 interval:
97 type: str
98 description:
99 - The interval at which the service check is run. This is a number with a V(s) or V(m) suffix to signify the units of
100 seconds or minutes, for example V(15s) or V(1m). If no suffix is supplied V(s) is used by default, for example V(10)
101 is V(10s).
102 - Required if one of the parameters O(script), O(http), or O(tcp) is specified.
103 check_id:
104 type: str
105 description:
106 - An ID for the service check. If O(state=absent), defaults to O(check_name). Ignored if part of a service definition.
107 check_name:
108 type: str
109 description:
110 - Name for the service check. Required if standalone, ignored if part of service definition.
111 check_node:
112 description:
113 - Node name.
114 type: str
115 check_host:
116 description:
117 - Host name.
118 type: str
119 ttl:
120 type: str
121 description:
122 - Checks can be registered with a TTL instead of a O(script) and O(interval) this means that the service checks in with
123 the agent before the TTL expires. If it does not the check is considered failed. Required if registering a check and
124 the script an interval are missing Similar to the interval this is a number with a V(s) or V(m) suffix to signify
125 the units of seconds or minutes, for example V(15s) or V(1m). If no suffix is supplied V(s) is used by default, for
126 example V(10) is equivalent to V(10s).
127 - Mutually exclusive with O(script), O(tcp) and O(http).
128 tcp:
129 type: str
130 description:
131 - Checks can be registered with a TCP port. This means that Consul checks if the connection attempt to that port is
132 successful (that is, the port is currently accepting connections). The format is V(host:port), for example V(localhost:80).
133 - Requires O(interval) to be provided.
134 - Mutually exclusive with O(script), O(ttl) and O(http).
135 version_added: '1.3.0'
136 http:
137 type: str
138 description:
139 - Checks can be registered with an HTTP endpoint. This means that Consul checks that the http endpoint returns a successful
140 HTTP status.
141 - Requires O(interval) to be provided.
142 - Mutually exclusive with O(script), O(ttl) and O(tcp).
143 timeout:
144 type: str
145 description:
146 - A custom HTTP check timeout. The Consul default is 10 seconds. Similar to the interval this is a number with a V(s)
147 or V(m) suffix to signify the units of seconds or minutes, for example V(15s) or V(1m). If no suffix is supplied V(s)
148 is used by default, for example V(10) is equivalent to V(10s).
149 token:
150 type: str
151 description:
152 - The token key identifying an ACL rule set. May be required to register services.
153 """
154
155 EXAMPLES = r"""
156 - name: Register nginx service with the local Consul agent
157 community.general.consul:
158 service_name: nginx
159 service_port: 80
160
161 - name: Register nginx service with curl check
162 community.general.consul:
163 service_name: nginx
164 service_port: 80
165 script: curl http://localhost
166 interval: 60s
167
168 - name: register nginx with a tcp check
169 community.general.consul:
170 service_name: nginx
171 service_port: 80
172 interval: 60s
173 tcp: localhost:80
174
175 - name: Register nginx with an http check
176 community.general.consul:
177 service_name: nginx
178 service_port: 80
179 interval: 60s
180 http: http://localhost:80/status
181
182 - name: Register external service nginx available at 10.1.5.23
183 community.general.consul:
184 service_name: nginx
185 service_port: 80
186 service_address: 10.1.5.23
187
188 - name: Register nginx with some service tags
189 community.general.consul:
190 service_name: nginx
191 service_port: 80
192 tags:
193 - prod
194 - webservers
195
196 - name: Remove nginx service
197 community.general.consul:
198 service_name: nginx
199 state: absent
200
201 - name: Register celery worker service
202 community.general.consul:
203 service_name: celery-worker
204 tags:
205 - prod
206 - worker
207
208 - name: Create a node level check to test disk usage
209 community.general.consul:
210 check_name: Disk usage
211 check_id: disk_usage
212 script: /opt/disk_usage.py
213 interval: 5m
214
215 - name: Register an http check against a service that's already registered
216 community.general.consul:
217 check_name: nginx-check2
218 check_id: nginx-check2
219 service_id: nginx
220 interval: 60s
221 http: http://localhost:80/morestatus
222 """
223
224 try:
225 import consul
226 from requests.exceptions import ConnectionError
227
228 class PatchedConsulAgentService(consul.Consul.Agent.Service):
229 def deregister(self, service_id, token=None):
230 params = {}
231 if token:
232 params["token"] = token
233 return self.agent.http.put(
234 consul.base.CB.bool(), f"/v1/agent/service/deregister/{service_id}", params=params
235 )
236
237 python_consul_installed = True
238 except ImportError:
239 python_consul_installed = False
240
241 import re
242
243 from ansible.module_utils.basic import AnsibleModule
244
245
246 def register_with_consul(module):
247 state = module.params["state"]
248
249 if state == "present":
250 add(module)
251 else:
252 remove(module)
253
254
255 def add(module):
256 """adds a service or a check depending on supplied configuration"""
257 check = parse_check(module)
258 service = parse_service(module)
259
260 if not service and not check:
261 module.fail_json(msg="a name and port are required to register a service")
262
263 if service:
264 if check:
265 service.add_check(check)
266 add_service(module, service)
267 elif check:
268 add_check(module, check)
269
270
271 def remove(module):
272 """removes a service or a check"""
273 service_id = module.params["service_id"] or module.params["service_name"]
274 check_id = module.params["check_id"] or module.params["check_name"]
275 if service_id:
276 remove_service(module, service_id)
277 else:
278 remove_check(module, check_id)
279
280
281 def add_check(module, check):
282 """registers a check with the given agent. currently there is no way
283 retrieve the full metadata of an existing check through the consul api.
284 Without this we can't compare to the supplied check and so we must assume
285 a change."""
286 if not check.name and not check.service_id:
287 module.fail_json(msg="a check name is required for a node level check, one not attached to a service")
288
289 consul_api = get_consul_api(module)
290 check.register(consul_api)
291
292 module.exit_json(
293 changed=True,
294 check_id=check.check_id,
295 check_name=check.name,
296 script=check.script,
297 interval=check.interval,
298 ttl=check.ttl,
299 tcp=check.tcp,
300 http=check.http,
301 timeout=check.timeout,
302 service_id=check.service_id,
303 )
304
305
306 def remove_check(module, check_id):
307 """removes a check using its id"""
308 consul_api = get_consul_api(module)
309
310 if check_id in consul_api.agent.checks():
311 consul_api.agent.check.deregister(check_id)
312 module.exit_json(changed=True, id=check_id)
313
314 module.exit_json(changed=False, id=check_id)
315
316
317 def add_service(module, service):
318 """registers a service with the current agent"""
319 result = service
320 changed = False
321
322 consul_api = get_consul_api(module)
323 existing = get_service_by_id_or_name(consul_api, service.id)
324
325 # there is no way to retrieve the details of checks so if a check is present
326 # in the service it must be re-registered
327 if service.has_checks() or not existing or existing != service:
328 service.register(consul_api)
329 # check that it registered correctly
330 registered = get_service_by_id_or_name(consul_api, service.id)
331 if registered:
332 result = registered
333 changed = True
334
335 module.exit_json(
336 changed=changed,
337 service_id=result.id,
338 service_name=result.name,
339 service_port=result.port,
340 checks=[check.to_dict() for check in service.checks()],
341 tags=result.tags,
342 )
343
344
345 def remove_service(module, service_id):
346 """deregister a service from the given agent using its service id"""
347 consul_api = get_consul_api(module)
348 service = get_service_by_id_or_name(consul_api, service_id)
349 if service:
350 consul_api.agent.service.deregister(service_id, token=module.params["token"])
351 module.exit_json(changed=True, id=service_id)
352
353 module.exit_json(changed=False, id=service_id)
354
355
356 def get_consul_api(module):
357 consulClient = consul.Consul(
358 host=module.params["host"],
359 port=module.params["port"],
360 scheme=module.params["scheme"],
361 verify=module.params["validate_certs"],
362 token=module.params["token"],
363 )
364 consulClient.agent.service = PatchedConsulAgentService(consulClient)
365 return consulClient
366
367
368 def get_service_by_id_or_name(consul_api, service_id_or_name):
369 """iterate the registered services and find one with the given id"""
370 for dummy, service in consul_api.agent.services().items():
371 if service_id_or_name in (service["ID"], service["Service"]):
372 return ConsulService(loaded=service)
373
374
375 def parse_check(module):
376 if module.params["check_id"] or any(module.params[p] is not None for p in ("script", "ttl", "tcp", "http")):
377 return ConsulCheck(
378 module.params["check_id"],
379 module.params["check_name"],
380 module.params["check_node"],
381 module.params["check_host"],
382 module.params["script"],
383 module.params["interval"],
384 module.params["ttl"],
385 module.params["notes"],
386 module.params["tcp"],
387 module.params["http"],
388 module.params["timeout"],
389 module.params["service_id"],
390 )
391
392
393 def parse_service(module):
394 return ConsulService(
395 module.params["service_id"],
396 module.params["service_name"],
397 module.params["service_address"],
398 module.params["service_port"],
399 module.params["tags"],
400 )
401
402
403 class ConsulService:
404 def __init__(self, service_id=None, name=None, address=None, port=-1, tags=None, loaded=None):
405 self.id = self.name = name
406 if service_id:
407 self.id = service_id
408 self.address = address
409 self.port = port
410 self.tags = tags
411 self._checks = []
412 if loaded:
413 self.id = loaded["ID"]
414 self.name = loaded["Service"]
415 self.port = loaded["Port"]
416 self.tags = loaded["Tags"]
417
418 def register(self, consul_api):
419 optional = {}
420
421 if self.port:
422 optional["port"] = self.port
423
424 if len(self._checks) > 0:
425 optional["check"] = self._checks[0].check
426
427 consul_api.agent.service.register(
428 self.name, service_id=self.id, address=self.address, tags=self.tags, **optional
429 )
430
431 def add_check(self, check):
432 self._checks.append(check)
433
434 def checks(self):
435 return self._checks
436
437 def has_checks(self):
438 return len(self._checks) > 0
439
440 def __eq__(self, other):
441 return (
442 isinstance(other, self.__class__)
443 and self.id == other.id
444 and self.name == other.name
445 and self.port == other.port
446 and self.tags == other.tags
447 )
448
449 def __ne__(self, other):
450 return not self.__eq__(other)
451
452 def to_dict(self):
453 data = {"id": self.id, "name": self.name}
454 if self.port:
455 data["port"] = self.port
456 if self.tags and len(self.tags) > 0:
457 data["tags"] = self.tags
458 if len(self._checks) > 0:
459 data["check"] = self._checks[0].to_dict()
460 return data
461
462
463 class ConsulCheck:
464 def __init__(
465 self,
466 check_id,
467 name,
468 node=None,
469 host="localhost",
470 script=None,
471 interval=None,
472 ttl=None,
473 notes=None,
474 tcp=None,
475 http=None,
476 timeout=None,
477 service_id=None,
478 ):
479 self.check_id = self.name = name
480 if check_id:
481 self.check_id = check_id
482 self.service_id = service_id
483 self.notes = notes
484 self.node = node
485 self.host = host
486
487 self.interval = self.validate_duration("interval", interval)
488 self.ttl = self.validate_duration("ttl", ttl)
489 self.script = script
490 self.tcp = tcp
491 self.http = http
492 self.timeout = self.validate_duration("timeout", timeout)
493
494 self.check = None
495
496 if script:
497 self.check = consul.Check.script(script, self.interval)
498
499 if ttl:
500 self.check = consul.Check.ttl(self.ttl)
501
502 if http:
503 self.check = consul.Check.http(http, self.interval, self.timeout)
504
505 if tcp:
506 regex = r"(?P<host>.*):(?P<port>(?:[0-9]+))$"
507 match = re.match(regex, tcp)
508
509 if not match:
510 raise Exception("tcp check must be in host:port format")
511
512 self.check = consul.Check.tcp(match.group("host").strip("[]"), int(match.group("port")), self.interval)
513
514 def validate_duration(self, name, duration):
515 if duration:
516 duration_units = ["ns", "us", "ms", "s", "m", "h"]
517 if not any(duration.endswith(suffix) for suffix in duration_units):
518 duration = f"{duration}s"
519 return duration
520
521 def register(self, consul_api):
522 consul_api.agent.check.register(
523 self.name, check_id=self.check_id, service_id=self.service_id, notes=self.notes, check=self.check
524 )
525
526 def __eq__(self, other):
527 return (
528 isinstance(other, self.__class__)
529 and self.check_id == other.check_id
530 and self.service_id == other.service_id
531 and self.name == other.name
532 and self.script == other.script
533 and self.interval == other.interval
534 )
535
536 def __ne__(self, other):
537 return not self.__eq__(other)
538
539 def to_dict(self):
540 data = {}
541 self._add(data, "id", attr="check_id")
542 self._add(data, "name", attr="check_name")
543 self._add(data, "script")
544 self._add(data, "node")
545 self._add(data, "notes")
546 self._add(data, "host")
547 self._add(data, "interval")
548 self._add(data, "ttl")
549 self._add(data, "tcp")
550 self._add(data, "http")
551 self._add(data, "timeout")
552 self._add(data, "service_id")
553 return data
554
555 def _add(self, data, key, attr=None):
556 try:
557 if attr is None:
558 attr = key
559 data[key] = getattr(self, attr)
560 except Exception:
561 pass
562
563
564 def test_dependencies(module):
565 if not python_consul_installed:
566 module.fail_json(
567 msg="py-consul required for this module. see https://github.com/criteo/py-consul?tab=readme-ov-file#installation"
568 )
569
570
571 def main():
572 module = AnsibleModule(
573 argument_spec=dict(
574 host=dict(default="localhost"),
575 port=dict(default=8500, type="int"),
576 scheme=dict(default="http"),
577 validate_certs=dict(default=True, type="bool"),
578 check_id=dict(),
579 check_name=dict(),
580 check_node=dict(),
581 check_host=dict(),
582 notes=dict(),
583 script=dict(),
584 service_id=dict(),
585 service_name=dict(),
586 service_address=dict(type="str"),
587 service_port=dict(type="int"),
588 state=dict(default="present", choices=["present", "absent"]),
589 interval=dict(type="str"),
590 ttl=dict(type="str"),
591 tcp=dict(type="str"),
592 http=dict(type="str"),
593 timeout=dict(type="str"),
594 tags=dict(type="list", elements="str"),
595 token=dict(no_log=True),
596 ),
597 mutually_exclusive=[
598 ("script", "ttl", "tcp", "http"),
599 ],
600 required_if=[
601 ("state", "present", ["service_name"]),
602 ("state", "absent", ["service_id", "service_name", "check_id", "check_name"], True),
603 ],
604 required_by={
605 "script": "interval",
606 "http": "interval",
607 "tcp": "interval",
608 },
609 supports_check_mode=False,
610 )
611 p = module.params
612
613 test_dependencies(module)
614 if p["state"] == "absent" and any(p[x] for x in ["script", "ttl", "tcp", "http", "interval"]):
615 module.fail_json(
616 msg="The use of parameters 'script', 'ttl', 'tcp', 'http', 'interval' along with 'state=absent' is no longer allowed."
617 )
618
619 try:
620 register_with_consul(module)
621 except SystemExit:
622 raise
623 except ConnectionError as e:
624 module.fail_json(msg=f"Could not connect to consul agent at {p['host']}:{p['port']}, error was {e}")
625 except Exception as e:
626 module.fail_json(msg=str(e))
627
628
629 if __name__ == "__main__":
630 main()