Skip to content

Instantly share code, notes, and snippets.

@feldoh
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feldoh/fad5a31140193c48c82d to your computer and use it in GitHub Desktop.
Save feldoh/fad5a31140193c48c82d to your computer and use it in GitHub Desktop.
A quick python script to generate Ansible inventory lines from the Vagrant ssh-config. Note that you must have run `vagrant up` at least once to ensure that the ports are properly assigned.
import subprocess
import shlex
import sys
import os
# Define function to print a single ansible inventory line from a dictionary of ssh-config values.
def printInventoryLine(host):
print ("{0} ansible_ssh_host={1} ansible_ssh_port={2} " +
"ansible_ssh_private_key_file={3} ansible_ssh_user={4}"
).format(host["Host"], host["HostName"], host["Port"], host["IdentityFile"], host["User"])
# Ensure script was run from a directory where running vagrant will do something
if (not os.path.isfile('Vagrantfile')):
sys.exit('ERROR: Please run this script from the directory containing your Vagrantfile')
# Run vagrant ssh-config to get connection info for each server
process = subprocess.Popen(['vagrant', 'ssh-config'], shell=False, stdout=subprocess.PIPE)
# Lex the result into tokens, allowing paths and ip-addresses as single tokens
lexer = shlex.shlex(process.communicate()[0])
lexer.wordchars += './'
# Parse the tokens
server = None
while True:
# Get next token
token = lexer.get_token()
# At the end of the token stream
if not token:
# Print final ansible line if at least one server was parsed
if server is not None:
printInventoryLine(server)
break
# Parse a key-value pair
if (token == "Host"):
# Reset the buffered server, and print if this is not the first Host token we have seen.
if server is not None:
printInventoryLine(server)
server = {}
server[token] = lexer.get_token()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment