hcloud_inventory.py 1.14 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
#
# Dynamic inventory script for getting infrastructure information from hcloud

import argparse
import json
import sys

from hcloud import Client

11
from misc.get_key import load_vault
12
13
14
15
16
17
18
19
20
21


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()


22
def get_host_details(server):
23
24
25
    return {'ansible_host': server.public_net.ipv4.ip,
            'ansible_port': 22,
            'ansible_user': "root"}
26
27
28
29


def main():
    args = parse_args()
30
    loaded = load_vault('misc/vault_hetzner.yml')
31
    client = Client(token=loaded["hetzner_cloud_api_key"])
32
    servers = client.servers.get_all()
33

34
    hostvars = {server.name: get_host_details(server) for server in servers}
35
    if args.list:
36
37
        hosts = [server.name for server in servers]
        json.dump({'hcloud': hosts, '_meta': {'hostvars': hostvars}}, sys.stdout)
38
    else:
39
        json.dump(hostvars[args.host], sys.stdout)
40
41
42
43


if __name__ == '__main__':
    main()