Skip to content
Snippets Groups Projects
  • Evangelos Foutras's avatar
    452090f6
    hcloud_inventory: Optimize --list to avoid --host calls · 452090f6
    Evangelos Foutras authored
    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).
    Verified
    452090f6
    History
    hcloud_inventory: Optimize --list to avoid --host calls
    Evangelos Foutras authored
    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).
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
hcloud_inventory.py 1.14 KiB
#!/usr/bin/env python
#
# Dynamic inventory script for getting infrastructure information from hcloud

import argparse
import json
import sys

from hcloud import Client

from misc.get_key import load_vault


def parse_args():
    parser = argparse.ArgumentParser(description="Hcloud dynamic inventory script")
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--list', action='store_true')
    group.add_argument('--host')
    return parser.parse_args()


def get_host_details(server):
    return {'ansible_host': server.public_net.ipv4.ip,
            'ansible_port': 22,
            'ansible_user': "root"}


def main():
    args = parse_args()
    loaded = load_vault('misc/vault_hetzner.yml')
    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:
        hosts = [server.name for server in servers]
        json.dump({'hcloud': hosts, '_meta': {'hostvars': hostvars}}, sys.stdout)
    else:
        json.dump(hostvars[args.host], sys.stdout)


if __name__ == '__main__':
    main()