Ansible: Up/down scaling of load-balanced containers

Viewed 58

Ansible has a nice example how to scale a container to n instances using with_sequence:

- name: Start 4 load-balanced containers
  community.docker.docker_container:
    name: "container{{ item }}"
    recreate: yes
    image: someuser/anotherappimage
    command: sleep 1d
  with_sequence: count=4

This allows me to update the count as desired and thus scale up my service. When scaling down (e.g. count=4 → count=3) however, the containers which are no longer used will just continue running.

All I can imagine for now to perform the clean up would be to list all containers, filter, and then remove them one by one, which seems rather crude considering the simplicity of above’s snippet -- is there a simpler way which I'm missing here?

1 Answers

Here's the solution which I use for now.

I assign a label to the scaled containers, collect (a) the IDs of the restarted containers, (b) the IDs of all tagged containers, then remove those by ID which were not (re)started.

- name: Start 4 load-balanced containers
  community.docker.docker_container:
    name: "container{{ item }}"
    recreate: yes
    image: someuser/anotherappimage
    command: sleep 1d
    labels:
      # tag for cleanup
      com.example.cleanup: 'my-container'
  with_sequence: count=4
  register: start_container_result

- name: Extract started container IDs
  set_fact:
    started_container_ids: "{{ start_container_result | json_query('results[*].container.Id') }}"

- name: Get running containers
  community.docker.docker_host_info:
    containers: yes
    containers_filters:
      label:
        - com.example.cleanup=my-container
  register: running_container_result

- name: Extract running container IDs
  set_fact:
    running_container_ids: "{{ running_container_result | json_query('containers[*].Id') }}"

- name: Remove obsolete API containers
  with_items: "{{ running_container_ids }}"
  when: item not in started_container_ids
  shell: docker stop {{ item }} | xargs docker rm
Related