From 5517b0384f02326d7a256265baad6189f4f69a9d Mon Sep 17 00:00:00 2001 From: Scott Luther Date: Sat, 30 Mar 2019 06:33:17 -0700 Subject: [PATCH] fix remove_orphans using APIs exposed via AnsibleDockerClient (#54316) Co-Authored-By: sluther --- .../fragments/26937-fix-remove-orphans.yml | 2 ++ .../modules/cloud/docker/docker_compose.py | 21 ++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/26937-fix-remove-orphans.yml diff --git a/changelogs/fragments/26937-fix-remove-orphans.yml b/changelogs/fragments/26937-fix-remove-orphans.yml new file mode 100644 index 00000000000..bee7dd3918e --- /dev/null +++ b/changelogs/fragments/26937-fix-remove-orphans.yml @@ -0,0 +1,2 @@ +bugfixes: + - docker_compose - fixed an issue where ``remove_orphans`` doesn't work reliably. diff --git a/lib/ansible/modules/cloud/docker/docker_compose.py b/lib/ansible/modules/cloud/docker/docker_compose.py index 3b088eee6e6..101a69cc4b5 100644 --- a/lib/ansible/modules/cloud/docker/docker_compose.py +++ b/lib/ansible/modules/cloud/docker/docker_compose.py @@ -463,7 +463,7 @@ try: from compose.cli.command import project_from_options from compose.service import NoSuchImageError from compose.cli.main import convergence_strategy_from_opts, build_action_from_opts, image_type_from_opt - from compose.const import DEFAULT_TIMEOUT + from compose.const import DEFAULT_TIMEOUT, LABEL_SERVICE, LABEL_PROJECT, LABEL_ONE_OFF HAS_COMPOSE = True HAS_COMPOSE_EXC = None MINIMUM_COMPOSE_VERSION = '1.7.0' @@ -717,6 +717,25 @@ class ContainerManager(DockerBaseClass): result['changed'] = build_output['changed'] result['actions'] += build_output['actions'] + if self.remove_orphans: + containers = self.client.containers( + filters={ + 'label': [ + '{0}={1}'.format(LABEL_PROJECT, self.project.name), + '{0}={1}'.format(LABEL_ONE_OFF, "False") + ], + } + ) + + orphans = [] + for container in containers: + service_name = container.get('Labels', {}).get(LABEL_SERVICE) + if service_name not in self.project.service_names: + orphans.append(service_name) + + if orphans: + result['changed'] = True + for service in self.project.services: if not service_names or service.name in service_names: plan = service.convergence_plan(strategy=converge)