Skip to content

Instantly share code, notes, and snippets.

@nathanleclaire
Created August 7, 2015 18:06
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save nathanleclaire/1bbf18de7c73f89aa36c to your computer and use it in GitHub Desktop.
Save nathanleclaire/1bbf18de7c73f89aa36c to your computer and use it in GitHub Desktop.
Ansible dynamic inventory plugin for Docker Machine
#!/usr/bin/env python
"""
Example Usage:
$ ansible -i machine.py machinename -m ping
"""
import argparse
import subprocess
try:
import json
except ImportError:
import simplejson as json
def dm(*args):
return subprocess.check_output(["docker-machine"] + list(args)).strip()
def dminspect(fmt, mcn):
return dm("inspect", "-f", fmt, mcn)
def get_host_and_vars(m):
hosts = [dminspect("{{.Driver.IPAddress}}", m)]
ssh_vars = {
"ansible_ssh_user": dminspect("{{.Driver.SSHUser}}", m),
"ansible_ssh_port": dminspect("{{.Driver.SSHPort}}", m),
"ansible_ssh_private_key_file": "{}/{}".format(dminspect("{{.StorePath}}", m), "id_rsa")
}
data = {"hosts": hosts, "vars": ssh_vars}
return data
class DockerMachineInventory(object):
def __init__(self):
self.inventory = {} # Ansible Inventory
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on Docker Machine status')
parser.add_argument('--list', action='store_true', help='List all active Droplets as Ansible inventory (default: True)')
self.args = parser.parse_args()
machines = dm("ls", "-q").splitlines()
json_data = {m: get_host_and_vars(m) for m in machines}
print json.dumps(json_data)
DockerMachineInventory()
@christobill
Copy link

christobill commented Jul 5, 2016

.StorePath path has changed to .HostOptions.AuthOptions.StorePath
(resulting in "ansible_ssh_private_key_file": "<no value>/id_rsa")

https://gist.github.com/christobill/ca6e874292902f611fbbdb6130df712b/revisions

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