3

looking for ansible playbook script which can stop and destroy all container on remote and remove existing images as well the below given code is just stopping the running containers

---
 - hosts: all
   gather_facts: false

   tasks:
 - name: Get running containers
   docker_host_info:
    containers: yes
   register: docker_info

 - name: Stop running containers
   docker_container:
     name: "{{ item }}"
     state: stopped
   loop: "{{ docker_info.containers | map(attribute='Id') | list }}"
1
  • 1
    You can use the docker_host_info module to get a list of images (set images: true instead of containers: true).
    – larsks
    Jun 3, 2020 at 23:12

2 Answers 2

4

this is the final solution for my question and it worked 100% it will destroy all containers and remove images as well .

---
- hosts: all
gather_facts: false
tasks:
- name: Get running containers
  docker_host_info:
    containers: yes
  register: docker_info

- name: Stop running containers
  docker_container:
    name: "{{ item }}"
    state: stopped
  loop: "{{ docker_info.containers | map(attribute='Id') | list }}"
- name: Remove Stoped docker containers
  shell: |
     docker rm $(docker ps -a -q);
  when: docker_info.containers != 0

- name: Get details of all images
  docker_host_info:
    images: yes
    verbose_output: yes
  register: image_info
- name: Remove all images
  docker_image:
    name: "{{ item }}"
    state: absent
  loop: "{{ image_info.images | map(attribute='Id') | list }}"
1
  • 2
    when: docker_info.containers != 0 should be when: (docker_info.containers | length) != 0
    – nyet
    Jul 27, 2021 at 0:20
1

Previous answer mixes ansible modules and shell commands, should be avoided if possible. Also unnecessary usage of docker_host_info and issues with the loop declaration.

The solution below is alot cleaner and also considers volumes with the "keep_volumes" directive.

In my case i want to remove all volumes as well.

Tested and working fine with ansible 2.14.3.

- name: Get host info
  community.docker.docker_host_info:
    containers: yes
    images: yes
  register: docker_info

- name: Remove all containers and their volumes
  community.docker.docker_container:
    name: "{{ item }}"
    state: absent
    keep_volumes: no
  loop: "{{ docker_info.containers | map(attribute='Id') }}"

- name: Remove all images
  community.docker.docker_image:
    name: "{{ item }}"
    state: absent
    force_absent: yes
  loop: "{{ docker_info.images | map(attribute='Id') }}"
2
  • is this deleting all containers or running ones only? imho all
    – Naramsim
    Sep 22 at 5:45
  • All containers are deleted
    – JazzCat
    2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.