1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-04-13 15:35:08 +00:00

Reformat everything.

This commit is contained in:
Felix Fontein 2025-11-01 12:08:41 +01:00
parent 3f2213791a
commit 340ff8586d
1008 changed files with 61301 additions and 58309 deletions

View file

@ -230,10 +230,10 @@ try:
def deregister(self, service_id, token=None):
params = {}
if token:
params['token'] = token
return self.agent.http.put(consul.base.CB.bool(),
f'/v1/agent/service/deregister/{service_id}',
params=params)
params["token"] = token
return self.agent.http.put(
consul.base.CB.bool(), f"/v1/agent/service/deregister/{service_id}", params=params
)
python_consul_installed = True
except ImportError:
@ -244,21 +244,21 @@ from ansible.module_utils.basic import AnsibleModule
def register_with_consul(module):
state = module.params['state']
state = module.params["state"]
if state == 'present':
if state == "present":
add(module)
else:
remove(module)
def add(module):
''' adds a service or a check depending on supplied configuration'''
"""adds a service or a check depending on supplied configuration"""
check = parse_check(module)
service = parse_service(module)
if not service and not check:
module.fail_json(msg='a name and port are required to register a service')
module.fail_json(msg="a name and port are required to register a service")
if service:
if check:
@ -269,9 +269,9 @@ def add(module):
def remove(module):
''' removes a service or a check '''
service_id = module.params['service_id'] or module.params['service_name']
check_id = module.params['check_id'] or module.params['check_name']
"""removes a service or a check"""
service_id = module.params["service_id"] or module.params["service_name"]
check_id = module.params["check_id"] or module.params["check_name"]
if service_id:
remove_service(module, service_id)
else:
@ -279,30 +279,32 @@ def remove(module):
def add_check(module, check):
''' registers a check with the given agent. currently there is no way
"""registers a check with the given agent. currently there is no way
retrieve the full metadata of an existing check through the consul api.
Without this we can't compare to the supplied check and so we must assume
a change. '''
a change."""
if not check.name and not check.service_id:
module.fail_json(msg='a check name is required for a node level check, one not attached to a service')
module.fail_json(msg="a check name is required for a node level check, one not attached to a service")
consul_api = get_consul_api(module)
check.register(consul_api)
module.exit_json(changed=True,
check_id=check.check_id,
check_name=check.name,
script=check.script,
interval=check.interval,
ttl=check.ttl,
tcp=check.tcp,
http=check.http,
timeout=check.timeout,
service_id=check.service_id)
module.exit_json(
changed=True,
check_id=check.check_id,
check_name=check.name,
script=check.script,
interval=check.interval,
ttl=check.ttl,
tcp=check.tcp,
http=check.http,
timeout=check.timeout,
service_id=check.service_id,
)
def remove_check(module, check_id):
''' removes a check using its id '''
"""removes a check using its id"""
consul_api = get_consul_api(module)
if check_id in consul_api.agent.checks():
@ -313,7 +315,7 @@ def remove_check(module, check_id):
def add_service(module, service):
''' registers a service with the current agent '''
"""registers a service with the current agent"""
result = service
changed = False
@ -323,7 +325,6 @@ def add_service(module, service):
# there is no way to retrieve the details of checks so if a check is present
# in the service it must be re-registered
if service.has_checks() or not existing or not existing == service:
service.register(consul_api)
# check that it registered correctly
registered = get_service_by_id_or_name(consul_api, service.id)
@ -331,74 +332,76 @@ def add_service(module, service):
result = registered
changed = True
module.exit_json(changed=changed,
service_id=result.id,
service_name=result.name,
service_port=result.port,
checks=[check.to_dict() for check in service.checks()],
tags=result.tags)
module.exit_json(
changed=changed,
service_id=result.id,
service_name=result.name,
service_port=result.port,
checks=[check.to_dict() for check in service.checks()],
tags=result.tags,
)
def remove_service(module, service_id):
''' deregister a service from the given agent using its service id '''
"""deregister a service from the given agent using its service id"""
consul_api = get_consul_api(module)
service = get_service_by_id_or_name(consul_api, service_id)
if service:
consul_api.agent.service.deregister(service_id, token=module.params['token'])
consul_api.agent.service.deregister(service_id, token=module.params["token"])
module.exit_json(changed=True, id=service_id)
module.exit_json(changed=False, id=service_id)
def get_consul_api(module):
consulClient = consul.Consul(host=module.params['host'],
port=module.params['port'],
scheme=module.params['scheme'],
verify=module.params['validate_certs'],
token=module.params['token'])
consulClient = consul.Consul(
host=module.params["host"],
port=module.params["port"],
scheme=module.params["scheme"],
verify=module.params["validate_certs"],
token=module.params["token"],
)
consulClient.agent.service = PatchedConsulAgentService(consulClient)
return consulClient
def get_service_by_id_or_name(consul_api, service_id_or_name):
''' iterate the registered services and find one with the given id '''
"""iterate the registered services and find one with the given id"""
for dummy, service in consul_api.agent.services().items():
if service_id_or_name in (service['ID'], service['Service']):
if service_id_or_name in (service["ID"], service["Service"]):
return ConsulService(loaded=service)
def parse_check(module):
if module.params['check_id'] or any(module.params[p] is not None for p in ('script', 'ttl', 'tcp', 'http')):
if module.params["check_id"] or any(module.params[p] is not None for p in ("script", "ttl", "tcp", "http")):
return ConsulCheck(
module.params['check_id'],
module.params['check_name'],
module.params['check_node'],
module.params['check_host'],
module.params['script'],
module.params['interval'],
module.params['ttl'],
module.params['notes'],
module.params['tcp'],
module.params['http'],
module.params['timeout'],
module.params['service_id'],
module.params["check_id"],
module.params["check_name"],
module.params["check_node"],
module.params["check_host"],
module.params["script"],
module.params["interval"],
module.params["ttl"],
module.params["notes"],
module.params["tcp"],
module.params["http"],
module.params["timeout"],
module.params["service_id"],
)
def parse_service(module):
return ConsulService(
module.params['service_id'],
module.params['service_name'],
module.params['service_address'],
module.params['service_port'],
module.params['tags'],
module.params["service_id"],
module.params["service_name"],
module.params["service_address"],
module.params["service_port"],
module.params["tags"],
)
class ConsulService:
def __init__(self, service_id=None, name=None, address=None, port=-1,
tags=None, loaded=None):
def __init__(self, service_id=None, name=None, address=None, port=-1, tags=None, loaded=None):
self.id = self.name = name
if service_id:
self.id = service_id
@ -407,26 +410,23 @@ class ConsulService:
self.tags = tags
self._checks = []
if loaded:
self.id = loaded['ID']
self.name = loaded['Service']
self.port = loaded['Port']
self.tags = loaded['Tags']
self.id = loaded["ID"]
self.name = loaded["Service"]
self.port = loaded["Port"]
self.tags = loaded["Tags"]
def register(self, consul_api):
optional = {}
if self.port:
optional['port'] = self.port
optional["port"] = self.port
if len(self._checks) > 0:
optional['check'] = self._checks[0].check
optional["check"] = self._checks[0].check
consul_api.agent.service.register(
self.name,
service_id=self.id,
address=self.address,
tags=self.tags,
**optional)
self.name, service_id=self.id, address=self.address, tags=self.tags, **optional
)
def add_check(self, check):
self._checks.append(check)
@ -438,30 +438,44 @@ class ConsulService:
return len(self._checks) > 0
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.id == other.id and
self.name == other.name and
self.port == other.port and
self.tags == other.tags)
return (
isinstance(other, self.__class__)
and self.id == other.id
and self.name == other.name
and self.port == other.port
and self.tags == other.tags
)
def __ne__(self, other):
return not self.__eq__(other)
def to_dict(self):
data = {'id': self.id, "name": self.name}
data = {"id": self.id, "name": self.name}
if self.port:
data['port'] = self.port
data["port"] = self.port
if self.tags and len(self.tags) > 0:
data['tags'] = self.tags
data["tags"] = self.tags
if len(self._checks) > 0:
data['check'] = self._checks[0].to_dict()
data["check"] = self._checks[0].to_dict()
return data
class ConsulCheck:
def __init__(self, check_id, name, node=None, host='localhost',
script=None, interval=None, ttl=None, notes=None, tcp=None, http=None, timeout=None, service_id=None):
def __init__(
self,
check_id,
name,
node=None,
host="localhost",
script=None,
interval=None,
ttl=None,
notes=None,
tcp=None,
http=None,
timeout=None,
service_id=None,
):
self.check_id = self.name = name
if check_id:
self.check_id = check_id
@ -470,12 +484,12 @@ class ConsulCheck:
self.node = node
self.host = host
self.interval = self.validate_duration('interval', interval)
self.ttl = self.validate_duration('ttl', ttl)
self.interval = self.validate_duration("interval", interval)
self.ttl = self.validate_duration("ttl", ttl)
self.script = script
self.tcp = tcp
self.http = http
self.timeout = self.validate_duration('timeout', timeout)
self.timeout = self.validate_duration("timeout", timeout)
self.check = None
@ -493,47 +507,49 @@ class ConsulCheck:
match = re.match(regex, tcp)
if not match:
raise Exception('tcp check must be in host:port format')
raise Exception("tcp check must be in host:port format")
self.check = consul.Check.tcp(match.group('host').strip('[]'), int(match.group('port')), self.interval)
self.check = consul.Check.tcp(match.group("host").strip("[]"), int(match.group("port")), self.interval)
def validate_duration(self, name, duration):
if duration:
duration_units = ['ns', 'us', 'ms', 's', 'm', 'h']
duration_units = ["ns", "us", "ms", "s", "m", "h"]
if not any(duration.endswith(suffix) for suffix in duration_units):
duration = f"{duration}s"
return duration
def register(self, consul_api):
consul_api.agent.check.register(self.name, check_id=self.check_id, service_id=self.service_id,
notes=self.notes,
check=self.check)
consul_api.agent.check.register(
self.name, check_id=self.check_id, service_id=self.service_id, notes=self.notes, check=self.check
)
def __eq__(self, other):
return (isinstance(other, self.__class__) and
self.check_id == other.check_id and
self.service_id == other.service_id and
self.name == other.name and
self.script == other.script and
self.interval == other.interval)
return (
isinstance(other, self.__class__)
and self.check_id == other.check_id
and self.service_id == other.service_id
and self.name == other.name
and self.script == other.script
and self.interval == other.interval
)
def __ne__(self, other):
return not self.__eq__(other)
def to_dict(self):
data = {}
self._add(data, 'id', attr='check_id')
self._add(data, 'name', attr='check_name')
self._add(data, 'script')
self._add(data, 'node')
self._add(data, 'notes')
self._add(data, 'host')
self._add(data, 'interval')
self._add(data, 'ttl')
self._add(data, 'tcp')
self._add(data, 'http')
self._add(data, 'timeout')
self._add(data, 'service_id')
self._add(data, "id", attr="check_id")
self._add(data, "name", attr="check_name")
self._add(data, "script")
self._add(data, "node")
self._add(data, "notes")
self._add(data, "host")
self._add(data, "interval")
self._add(data, "ttl")
self._add(data, "tcp")
self._add(data, "http")
self._add(data, "timeout")
self._add(data, "service_id")
return data
def _add(self, data, key, attr=None):
@ -547,16 +563,18 @@ class ConsulCheck:
def test_dependencies(module):
if not python_consul_installed:
module.fail_json(msg="py-consul required for this module. see https://github.com/criteo/py-consul?tab=readme-ov-file#installation")
module.fail_json(
msg="py-consul required for this module. see https://github.com/criteo/py-consul?tab=readme-ov-file#installation"
)
def main():
module = AnsibleModule(
argument_spec=dict(
host=dict(default='localhost'),
port=dict(default=8500, type='int'),
scheme=dict(default='http'),
validate_certs=dict(default=True, type='bool'),
host=dict(default="localhost"),
port=dict(default=8500, type="int"),
scheme=dict(default="http"),
validate_certs=dict(default=True, type="bool"),
check_id=dict(),
check_name=dict(),
check_node=dict(),
@ -565,35 +583,35 @@ def main():
script=dict(),
service_id=dict(),
service_name=dict(),
service_address=dict(type='str'),
service_port=dict(type='int'),
state=dict(default='present', choices=['present', 'absent']),
interval=dict(type='str'),
ttl=dict(type='str'),
tcp=dict(type='str'),
http=dict(type='str'),
timeout=dict(type='str'),
tags=dict(type='list', elements='str'),
service_address=dict(type="str"),
service_port=dict(type="int"),
state=dict(default="present", choices=["present", "absent"]),
interval=dict(type="str"),
ttl=dict(type="str"),
tcp=dict(type="str"),
http=dict(type="str"),
timeout=dict(type="str"),
tags=dict(type="list", elements="str"),
token=dict(no_log=True),
),
mutually_exclusive=[
('script', 'ttl', 'tcp', 'http'),
("script", "ttl", "tcp", "http"),
],
required_if=[
('state', 'present', ['service_name']),
('state', 'absent', ['service_id', 'service_name', 'check_id', 'check_name'], True),
("state", "present", ["service_name"]),
("state", "absent", ["service_id", "service_name", "check_id", "check_name"], True),
],
required_by={
'script': 'interval',
'http': 'interval',
'tcp': 'interval',
"script": "interval",
"http": "interval",
"tcp": "interval",
},
supports_check_mode=False,
)
p = module.params
test_dependencies(module)
if p['state'] == 'absent' and any(p[x] for x in ['script', 'ttl', 'tcp', 'http', 'interval']):
if p["state"] == "absent" and any(p[x] for x in ["script", "ttl", "tcp", "http", "interval"]):
module.fail_json(
msg="The use of parameters 'script', 'ttl', 'tcp', 'http', 'interval' along with 'state=absent' is no longer allowed."
)
@ -608,5 +626,5 @@ def main():
module.fail_json(msg=str(e))
if __name__ == '__main__':
if __name__ == "__main__":
main()