Skip to content

Instantly share code, notes, and snippets.

@d-a-n
Last active June 12, 2019 08:39
Show Gist options
  • Save d-a-n/baabf3b010a6851f0e84 to your computer and use it in GitHub Desktop.
Save d-a-n/baabf3b010a6851f0e84 to your computer and use it in GitHub Desktop.
dynamic ansible vagrant inventory file
#!/usr/bin/env python
# -*- coding: utf-8 -*-
### A simple helper script for using ansible and vagrant together.
# Usually you don't need an inventory file for vagrant, since one is created
# automatically. But if you want to give your vagrant host a special group
# or assign some variables, this script becomes handy.
#
# Use it like this:
# 1) create a file e.g ansible/inventories/vagrant.py and paste the content of this gist
# 2) give the file execution permissions: chmod +x ansible/inventories/vagrant.py
# 3) open your Vagrantfile and change it accordingly:
#
# config.vm.provision "ansible" do |ansible|
# [..]
# ansible.inventory_path = "ansible/inventories/vagrant.py"
# [..]
#
# end
import json, subprocess
def get_vagrant_sshconfig():
p = subprocess.Popen("vagrant ssh-config", stdout=subprocess.PIPE, shell=True)
raw = p.communicate()[0]
sshconfig = {}
lines = raw.split("\n")
for line in lines:
kv = line.strip().split(" ", 1)
if len(kv) == 2:
sshconfig[kv[0]] = kv[1]
return sshconfig
sshconfig = get_vagrant_sshconfig()
host = {
"dev": {
"hosts": [ "vagrant" ],
"vars": {
"ansible_ssh_host": sshconfig.get('HostName', '127.0.0.1'),
"ansible_ssh_port": sshconfig.get('Port', '2222'),
"ansible_ssh_user": sshconfig.get('User', 'vagrant'),
"ansible_ssh_private_key_file": sshconfig.get('IdentityFile', '.vagrant/machines/default/virtualbox/private_key')
}
}
}
print json.dumps(host);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment