Skip to content

Instantly share code, notes, and snippets.

@mrinalwadhwa
Last active February 19, 2021 01:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrinalwadhwa/de85f079ce01cff1d725 to your computer and use it in GitHub Desktop.
Save mrinalwadhwa/de85f079ce01cff1d725 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import argparse
import json
import re
import subprocess
import sys
def ssh_config_lookup(key, config_text):
return re.search("(({})\s+(.*))".format(key), config_text).group(3)
def get_host_vars(host):
cmd = "vagrant ssh-config {}".format(host)
config = subprocess.check_output(cmd.split()).rstrip()
return {
'ansible_ssh_host': ssh_config_lookup('HostName', config),
'ansible_ssh_port': ssh_config_lookup('Port', config),
'ansible_ssh_user': ssh_config_lookup('User', config),
'ansible_ssh_private_key_file': ssh_config_lookup('IdentityFile', config)
}
def get_hosts():
cmd = "vagrant status --machine-readable"
status = subprocess.check_output(cmd.split()).rstrip()
hosts = []
for line in status.split('\n'):
(_, host, key, value) = line.split(',')
if key == 'state' and value == 'running':
hosts.append(host)
return hosts
def parse_args():
parser = argparse.ArgumentParser(description="Vegrant Inventory")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true')
group.add_argument('--host')
return parser.parse_args()
def main():
args = parse_args()
if args.list:
hosts = get_hosts()
hostvars = {}
for host in hosts:
hostvars[host] = get_host_vars(host)
print json.dumps({
'vagrant': hosts,
'_meta': {
'hostvars': hostvars
}
}, sys.stdout)
elif args.host:
print json.dumps(get_host_vars(args.host), sys.stdout)
else:
exit(1)
exit(0)
main()
# REFERENCES
# --------------
# docs.ansible.com/intro_dynamic_inventory.html
# docs.ansible.com/developing_inventory.html
# github.com/ansible/ansible/blob/devel/plugins/inventory/vagrant.py
# github.com/ansible/ansible/blob/devel/plugins/inventory/docker.py
# gist.github.com/lorin/4cae51e123b596d5c60d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment