|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | +""" |
| 4 | +
|
| 5 | +Ansible dynamic inventory that gets the docker-machine host and it's |
| 6 | +variables into the inventory to the 'docker-host' group. |
| 7 | +
|
| 8 | +Example Usage: |
| 9 | +
|
| 10 | +> eval "$(docker-machine env MACHINE_NAME)" |
| 11 | +$ ansible-playbook playbook.yml -i docker-machine.py |
| 12 | +
|
| 13 | +Debug: |
| 14 | +
|
| 15 | +python docker-machine.py |
| 16 | +
|
| 17 | +""" |
| 18 | + |
| 19 | +import os |
| 20 | +import argparse |
| 21 | +import subprocess |
| 22 | + |
| 23 | +try: |
| 24 | + import json |
| 25 | +except ImportError: |
| 26 | + import simplejson as json |
| 27 | + |
| 28 | + |
| 29 | +""" |
| 30 | + Gets information about a docker machine. |
| 31 | + docker-machine host |
| 32 | +""" |
| 33 | +def getDockerMachineInfo(machineName, format): |
| 34 | + return subprocess.check_output([ |
| 35 | + "docker-machine", |
| 36 | + "inspect", |
| 37 | + "-f", |
| 38 | + format, |
| 39 | + machineName ]).strip() |
| 40 | + |
| 41 | + |
| 42 | +""" |
| 43 | + Gets all available docker machines. |
| 44 | + Returning the list of available docker machines |
| 45 | +""" |
| 46 | +def getAllDockerMachines(machineName, format): |
| 47 | + return subprocess.check_output([ |
| 48 | + "docker-machine", |
| 49 | + "ls", |
| 50 | + "-q" ]).strip() |
| 51 | + |
| 52 | + |
| 53 | +""" |
| 54 | + Get the docker machine inventory group. |
| 55 | + Returns the docker host group |
| 56 | +""" |
| 57 | +def getAnsibleDockerInventoryGroup(dmName): |
| 58 | + |
| 59 | + return { |
| 60 | + "hosts": ["localhost"], |
| 61 | + "vars": { |
| 62 | + |
| 63 | + # at the moment docker-machine is always using this port |
| 64 | + "docker_host_url": "tcp://{}:2376".format( |
| 65 | + getDockerMachineInfo(dmName, "{{.Driver.IPAddress}}")), |
| 66 | + |
| 67 | + "docker_host_cert_path": getDockerMachineInfo(dmName, "{{.HostOptions.AuthOptions.StorePath}}"), |
| 68 | + |
| 69 | + "ansible_connection": "local" |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + |
| 74 | +# get the current docker machine name |
| 75 | +docker_machine_name = os.environ['DOCKER_MACHINE_NAME'] |
| 76 | +if docker_machine_name is None: |
| 77 | + raise Exception('Missing DOCKER_MACHINE_NAME environment variable') |
| 78 | + |
| 79 | +# add the docker-machine to the inventory |
| 80 | +json_data = { |
| 81 | + "docker-host": getAnsibleDockerInventoryGroup(docker_machine_name), |
| 82 | + "local": { |
| 83 | + "hosts": ["localhost"], |
| 84 | + "vars": { "ansible_connection": "local" } |
| 85 | + } |
| 86 | +} |
| 87 | + |
| 88 | +print json.dumps(json_data, indent=4) |
0 commit comments