问题
I am trying to stop all running containers as a first step and then remove them.
I know that I can do it using Anslible shell package and run this command:
docker container stop $(docker container ls -aq)
As a second step I can do the same with shell package and clean the dead containers / images / volumes:
docker system prune -a -f --volumes
I have tried something like this (sample of code):
- name: Stop all containers:
shell: "docker container stop $(docker container ls -aq)"
ignore_errors: yes
Unfortunately when containers are 0 this throws an error which I would like to handle.
I could improve it by adding the following:
- name: Get info on docker host and list images
docker_host_info:
containers: yes
register: result
- name: Stop all containers
shell: "docker container stop $(docker container ls -aq)"
when: result.host_info.Containers != 0
I would like to do it with by using purely an Ansible package e.g. (docker_host_info). I am able to extract a complex list with containers, that include all the information but I can not found a way to get either the Id or name of the containers.
My plan is to make a loop after with the Ids or names and stop them one by one.
I managed to extract the number of containers (string format), but I can not find a way to convert it to index so I can loop through.
Sample of code:
- name: Get info on docker host and list images
docker_host_info:
containers: yes
register: result
- name: Debug dockerInfo
debug:
var: result.containers
# var: result.host_info.Containers
# loop: "{{ result.host_info.Containers }}"
# loop: "{{ range(0, 4)|list }}"
when: result.host_info.Containers != 0
Is it possible to convert the returned string to an index and iterate through this index e.g. (fake sample of code):
- name: Debug dockerInfo
debug:
var: "{{ result.containers[item].Id }}
loop: result.host_info.Containers
when: result.host_info.Containers != 0
回答1:
result.containers
is a list so you can iterate directly on it:
- name: Debug dockerInfo
debug:
var: item
loop: "{{ result.containers }}"
when: result.containers | length != 0
BTW, the var
of debug
only takes a variable name, to debug an expression you have to use msg
instead.
BTW2, for the loop
keyword you must use the curly braces to evaluate the expression.
来源:https://stackoverflow.com/questions/58460180/how-to-stop-all-containers-with-ansible