Skip to content

Instantly share code, notes, and snippets.

@lorin
Created September 25, 2014 21:25
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 14 You must be signed in to fork a gist
  • Save lorin/4cae51e123b596d5c60d to your computer and use it in GitHub Desktop.
Save lorin/4cae51e123b596d5c60d to your computer and use it in GitHub Desktop.
Vagrant dynamic inventory script for Ansible
#!/usr/bin/env python
# Adapted from Mark Mandel's implementation
# https://github.com/ansible/ansible/blob/devel/plugins/inventory/vagrant.py
import argparse
import json
import paramiko
import subprocess
import sys
def parse_args():
parser = argparse.ArgumentParser(description="Vagrant 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 list_running_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 get_host_details(host):
cmd = "vagrant ssh-config {}".format(host)
p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
config = paramiko.SSHConfig()
config.parse(p.stdout)
c = config.lookup(host)
return {'ansible_ssh_host': c['hostname'],
'ansible_ssh_port': c['port'],
'ansible_ssh_user': c['user'],
'ansible_ssh_private_key_file': c['identityfile'][0]}
def main():
args = parse_args()
if args.list:
hosts = list_running_hosts()
json.dump({'vagrant': hosts}, sys.stdout)
else:
details = get_host_details(args.host)
json.dump(details, sys.stdout)
if __name__ == '__main__':
main()
@arbabnazar
Copy link

@lorin I am getting this error:

Traceback (most recent call last):
File "vagrant.py", line 52, in
main()
File "vagrant.py", line 45, in main
hosts = list_running_hosts()
File "vagrant.py", line 21, in list_running_hosts
status = subprocess.check_output(cmd.split()).rstrip()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 573, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['vagrant', 'status', '--machine-readable']' returned non-zero exit status 1

@majidaldo
Copy link

@arbabnazar check that you're in a directory with a vagrantfile

@mfrommelt
Copy link

File "/Users/mfrommelt/playbooks/inventory/vagrant.py", line 24, in list_running_hosts
(_, host, key, value) = line.split(',')
ValueError: too many values to unpack

@mfrommelt
Copy link

Fixed by changing:

for line in status.split('\n'):
(_, host, key, value) = line.split(',')

to

for line in status.split('\n'):
(_, host, key, value) = line.split(',',3)

@LaoZhuBaba
Copy link

LaoZhuBaba commented Sep 27, 2020

Both calls to subprocess.check_output need text=True in new versions of Python3

E.g.,
status = subprocess.check_output(cmd.split(),text=True).rstrip()

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