Skip to content
Snippets Groups Projects
Verified Commit 452090f6 authored by Evangelos Foutras's avatar Evangelos Foutras :smiley_cat:
Browse files

hcloud_inventory: Optimize --list to avoid --host calls

By adding a top-level element called "_meta" to the --list response,
Ansible will not call the inventory script with --host for each host
thus saving a lot of time and many requests to the Hetzner Cloud API.

The speed-up is significant; `ansible-inventory --list` is down from
about 1 minute to just 7 seconds in my testing (with ~60ms latency).
parent b3f94001
No related branches found
No related tags found
1 merge request!459hcloud_inventory: Optimize --list to avoid --host calls
Pipeline #9649 passed
...@@ -19,12 +19,7 @@ def parse_args(): ...@@ -19,12 +19,7 @@ def parse_args():
return parser.parse_args() return parser.parse_args()
def list_running_hosts(client): def get_host_details(server):
return [server.name for server in client.servers.get_all()]
def get_host_details(client, host):
server = client.servers.get_by_name(host)
return {'ansible_host': server.public_net.ipv4.ip, return {'ansible_host': server.public_net.ipv4.ip,
'ansible_port': 22, 'ansible_port': 22,
'ansible_user': "root"} 'ansible_user': "root"}
...@@ -34,13 +29,14 @@ def main(): ...@@ -34,13 +29,14 @@ def main():
args = parse_args() args = parse_args()
loaded = load_vault('misc/vault_hetzner.yml') loaded = load_vault('misc/vault_hetzner.yml')
client = Client(token=loaded["hetzner_cloud_api_key"]) client = Client(token=loaded["hetzner_cloud_api_key"])
servers = client.servers.get_all()
hostvars = {server.name: get_host_details(server) for server in servers}
if args.list: if args.list:
hosts = list_running_hosts(client=client) hosts = [server.name for server in servers]
json.dump({'hcloud': hosts}, sys.stdout) json.dump({'hcloud': hosts, '_meta': {'hostvars': hostvars}}, sys.stdout)
else: else:
details = get_host_details(client, args.host) json.dump(hostvars[args.host], sys.stdout)
json.dump(details, sys.stdout)
if __name__ == '__main__': if __name__ == '__main__':
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment