Search code examples
dockerdocker-composeansibleansible-inventory

Restart mutiple Docker Containers using Ansible not happening


I am trying to restart my docker containers one by one for a particular image using Ansible but it doesn't seem to be happening. Below is my yml and what it is doing is exiting the current running container.

---
- name: restart app servers
  hosts: shashank-VM
  connection: local
  become: yes
  become_method: sudo
  tasks:
    - name: Get info on the Container
      shell: docker ps | awk '/{{ item }}/{print $1}'
      register: list_of_containers
      with_items:
        - ubuntu

    - name: Restart Docker Service
      docker_container:
       name: "{{ item }}"
       # image: ubuntu
       state: started
       restart: yes
      with_items: "{{ list_of_containers.results | map(attribute='stdout_lines') | list }}"

If you see the below output when i run docker ps there are no running containers.

TASK [Restart Docker Service] ****************************************************************************************************************
/usr/lib/python2.7/dist-packages/requests/__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.9) or chardet (3.0.4) doesn't match a supported version!
  RequestsDependencyWarning)
changed: [shashank-VM] => (item=c2310b76b005)

PLAY RECAP ***********************************************************************************************************************************
shashank-VM                : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

shashank@shashank-VM:~/ansible$ sudo docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

What am i doing wrong? Can someone help?


Solution

  • I don't think the docker_container module is designed to do what you want (i.e., restart an existing container). The module is designed to manage containers by name, not by id, and will check that the running container matches the options provided to docker_container.

    You're probably better off simply using the docker command to restart your containers:

    ---
    - name: restart app servers
      hosts: shashank-VM
      connection: local
      become: yes
      become_method: sudo
      tasks:
        - name: Get info on the Container
          shell: docker ps | awk '/{{ item }}/{print $1}'
          register: list_of_containers
          with_items:
            - ubuntu
    
        - name: Restart Docker Service
          command: docker restart {{ item }}
          with_items: "{{ list_of_containers.results | map(attribute='stdout_lines') | list }}"