Created
October 22, 2020 07:10
-
-
Save tboerger/3ed9519303de4c8b48a5e151a67bc012 to your computer and use it in GitHub Desktop.
Dynamic inventory for Ansible on Hetzner Cloud
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import json | |
import requests | |
import os | |
def main(): | |
api_key = os.environ.get('HCLOUD_TOKEN', '') | |
if not api_key.strip(): | |
print('Missing HCLOUD_TOKEN environment variable!') | |
exit(1) | |
hosts = [] | |
hostvars = {} | |
root = { | |
'servers': { | |
'hosts': hosts | |
}, | |
'_meta': { | |
'hostvars': hostvars | |
} | |
} | |
url = 'https://api.hetzner.cloud/v1/servers?label_selector=provisioner==ansible' | |
headers = {'Authorization': 'Bearer ' + api_key} | |
r = requests.get(url, headers=headers) | |
for server in r.json()['servers']: | |
server_name = server['name'] | |
hosts.append(server_name) | |
hostvars[server_name] = fill_host_vars(server) | |
add_to_type(root, server) | |
add_to_location(root, server) | |
add_to_labels(root, server) | |
print(json.dumps(root)) | |
def fill_host_vars(server): | |
return { | |
'ansible_host': server['public_net']['ipv4']['ip'], | |
'hcloud_name': server['name'], | |
'hcloud_type': server['server_type']['name'], | |
'hcloud_image': server['image']['name'], | |
'hcloud_datacenter': server['datacenter']['name'], | |
'hcloud_location': server['datacenter']['location']['name'], | |
'hcloud_ipv4': server['public_net']['ipv4']['ip'], | |
'hcloud_ipv6': server['public_net']['ipv6']['ip'], | |
'hcloud_status': server['status'], | |
'ansible_become': 'true', | |
'ansible_python_interpreter': '/usr/bin/python3', | |
'ansible_ssh_common_args': '-o StrictHostKeyChecking=no' | |
} | |
def add_to_type(root, server): | |
t = server['server_type']['name'] | |
if not t in root: | |
root[t] = { 'hosts': [] } | |
root[t]['hosts'].append(server['name']) | |
def add_to_location(root, server): | |
l = server['datacenter']['location']['name'] | |
if not l in root: | |
root[l] = { 'hosts': [] } | |
root[l]['hosts'].append(server['name']) | |
def add_to_labels(root, server): | |
for label, value in server['labels'].items(): | |
if not label.startswith("ansible_group"): | |
continue | |
if not value in root: | |
root[value] = { 'hosts': [] } | |
root[value]['hosts'].append(server['name']) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment