Created
April 20, 2014 03:13
-
-
Save joshuaconner/11104025 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# | |
# all_docker_containers | |
# | |
# The Ansible `docker` module only returns the containers you've changed, but | |
# what if you need to get ALL of the docker containers running on a machine? | |
# | |
# That's what this is for - it uses the docker API to return all of the running | |
# containers on a machine, so if you need to stuff to containers you haven't | |
# done something to, you'll be able to do that. | |
############################################################################### | |
try: | |
import sys | |
import docker.client | |
from requests.exceptions import * | |
from urlparse import urlparse | |
except ImportError, e: | |
print "failed=True msg='failed to import python module: %s'" % e | |
sys.exit(1) | |
def _docker_id_quirk(inspect): | |
# XXX: some quirk in docker | |
if 'ID' in inspect: | |
inspect['Id'] = inspect['ID'] | |
del inspect['ID'] | |
return inspect | |
class DockerManager: | |
def __init__(self, module): | |
self.module = module | |
# connect to docker server | |
docker_url = urlparse(module.params.get('docker_url')) | |
self.client = docker.Client(base_url=docker_url.geturl()) | |
def get_containers(self): | |
# determine which images/commands are running already | |
containers = self.client.containers() | |
response = [] | |
for i in containers: | |
details = self.client.inspect_container(i['Id']) | |
details = _docker_id_quirk(details) | |
response.append(details) | |
return response | |
def main(): | |
module = AnsibleModule( | |
argument_spec = dict( | |
docker_url = dict(default='unix://var/run/docker.sock'), | |
user = dict(default=None), | |
password = dict(), | |
) | |
) | |
try: | |
manager = DockerManager(module) | |
module.exit_json(failed=False, changed=False, all_docker_containers=manager.get_containers()) | |
except docker.client.APIError, e: | |
changed = manager.has_changed() | |
module.exit_json(failed=True, changed=changed, msg="Docker API error: " + e.explanation) | |
except RequestException, e: | |
changed = manager.has_changed() | |
module.exit_json(failed=True, changed=changed, msg=repr(e)) | |
# import module snippets | |
from ansible.module_utils.basic import * | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment