I'm creating an Ansible role to do a OS and config update on VMs on which I'm hosting different docker containers.
At beginning of the role I want to stop all docker containers if there are some. I've found this thread, but it is a bit old so I'm trying to open a new question. Hope that's ok.
The simplest way would be this:
- name: Stop docker containers
shell: |
docker stop $(docker ps -aq)
Unfortunately I'm getting an error when a host has no docker container. And working with ignore_errors: yes wouldn't be a good way I think. So I tried that way
- name: Get info on docker host and list images
docker_host_info:
containers: yes
register: containers_to_stop
- name: Stop docker containers
shell: |
docker stop $(docker ps -aq)
when: containers_to_stop.containers != 0
but still the same as in first part. I'm getting an error when a host has no docker container.
So as in the linked thread I'm trying to use the docker_container module like this:
- name: Get info on docker host and list images
docker_host_info:
containers: yes
register: containers_to_stop
- name: Stop running docker containers
docker_container:
name: '{{ item.Names }}'
image: '{{ item.Image }}'
state: stopped
loop: '{{ containers_to_stop.containers }}'
Unfortunately the docker_host_info module doesn't work fine because all my docker container names will begin with a /. I've debugged that for you all:
failed: [app01] (item={u'Status': u'Up 12 minutes', u'Command': u'./replace_props_and_start.sh', u'Names': [u'/image-name'], u'Created': 1588071879, u'Image': u'image-name', u'Ports': [{u'IP': u'0.0.0.0', u'Type': u'tcp', u'PublicPort': 8091, u'PrivatePort': 80}], u'Id': u'ad5b0b3d6d623e2ac1d0a2ead9fbbf8a5ce5bca58492410a31035fd160de149a'}) => {"ansible_loop_var": "item", "changed": false, "item": {"Command": "./replace_props_and_start.sh", "Created": 1588071879, "Id": "ad5b0b3d6d623e2ac1d0a2ead9fbbf8a5ce5bca58492410a31035fd160de149a", "Image": "image-name", "Names": ["/image-name"], "Ports": [{"IP": "0.0.0.0", "PrivatePort": 80, "PublicPort": 8091, "Type": "tcp"}], "Status": "Up 12 minutes"}, "msg": "Error creating container: 400 Client Error: Bad Request ("Invalid container name (['/image-name']), only [a-zA-Z0-9][a-zA-Z0-9_.-] are allowed")"}
So my container is named /image-name and not image-name in the directory which Ansible is creating for me. So the error is clear, but how could I fix that?
Maybe that's a module problem and I need to go to Ansible developers?
Thanks and regards,