From 36bd9efb70a7860c4bd1c76d4f14a20d545b765a Mon Sep 17 00:00:00 2001 From: James Cammarata Date: Thu, 14 Aug 2014 23:35:54 -0500 Subject: [PATCH] Stop/remove existing docker container if the specified tag is different Fixes #8278 --- library/cloud/docker | 32 ++++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/library/cloud/docker b/library/cloud/docker index f14c568399..d19a1f997a 100644 --- a/library/cloud/docker +++ b/library/cloud/docker @@ -742,6 +742,7 @@ def main(): state = module.params.get('state') count = int(module.params.get('count')) name = module.params.get('name') + image = module.params.get('image') if count < 0: module.fail_json(msg="Count must be greater than zero") @@ -760,12 +761,31 @@ def main(): if state in [ "running", "present" ]: # make sure a container with `name` exists, if not create and start it - if name and "/" + name not in map(lambda x: x.get('Name'), deployed_containers): - containers = manager.create_containers(1) - if state == "present": #otherwise it get (re)started later anyways.. - manager.start_containers(containers) - running_containers = manager.get_running_containers() - deployed_containers = manager.get_deployed_containers() + if name: + # first determine if a container with this name exists + existing_container = None + for deployed_container in deployed_containers: + if deployed_container.get('Name') == '/%s' % name: + existing_container = deployed_container + break + + # the named container is running, but with a + # different image or tag, so we stop it first + if existing_container and existing_container.get('Config', dict()).get('Image') != image: + manager.stop_containers([existing_container]) + manager.remove_containers([existing_container]) + running_containers = manager.get_running_containers() + deployed_containers = manager.get_deployed_containers() + existing_container = None + + # if the container isn't running (or if we stopped the + # old version above), create and (maybe) start it up now + if not existing_container: + containers = manager.create_containers(1) + if state == "present": # otherwise it get (re)started later anyways.. + manager.start_containers(containers) + running_containers = manager.get_running_containers() + deployed_containers = manager.get_deployed_containers() if state == "running": # make sure a container with `name` is running