Skip to content

Instantly share code, notes, and snippets.

@ptman
Created November 25, 2021 15:51
Show Gist options
  • Save ptman/8cfd4ef766076353e2b07bf781edcb24 to your computer and use it in GitHub Desktop.
Save ptman/8cfd4ef766076353e2b07bf781edcb24 to your computer and use it in GitHub Desktop.
Ansible Tailscale inventory script
#!/usr/bin/env python3
# Copyright (c) 2021 Paul Tötterman <paul.totterman@iki.fi>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
# AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
# INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
# LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
import requests
import pprint
import json
import sys
import os
from urllib.parse import urljoin
BASEURL = 'https://api.tailscale.com/api/v2/'
def fetchdata(tailnet, key):
url = urljoin(urljoin(urljoin(BASEURL, 'tailnet/'), tailnet + '/'),
'devices')
res = requests.get(url, auth=(key, '')).json()
result = {}
result['all'] = {}
result['all']['children'] = ['ungrouped']
result['ungrouped'] = {}
result['ungrouped']['hosts'] = []
result['_meta'] = {}
result['_meta']['hostvars'] = {}
for device in res['devices']:
d = {}
d['ansible_host'] = device['addresses'][0]
d['tailscale_fqdn'] = device['name'] + '.beta.tailscale.net'
d['tailscale_ipv4'] = device['addresses'][0]
if len(device['addresses']) > 1:
d['tailscale_ipv6'] = device['addresses'][1]
result['_meta']['hostvars'][device['name']] = d
result['ungrouped']['hosts'] += [device['name']]
return result
def main():
key = os.getenv('TAILSCALE_APIKEY', '')
tailnet = os.getenv('TAILSCALE_TAILNET', '')
result = fetchdata(tailnet, key)
if len(sys.argv) > 1 and sys.argv[1] == '--list':
print(json.dumps(result))
elif len(sys.argv) > 2 and sys.argv[1] == '--host':
print(json.dumps(result['_meta']['hostvars'][sys.argv[2]]))
if __name__ == '__main__':
main()
@ptman
Copy link
Author

ptman commented Jun 30, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment