使用Ansible重启多个Docker容器

时间:2020-04-23 12:05:47

标签: docker docker-compose ansible ansible-inventory

我正在尝试使用Ansible逐一重新启动我的docker容器以获取特定映像,但这似乎没有发生。以下是我的yml,它正在退出当前正在运行的容器。

---
- 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 }}"

如果我在运行docker ps时看到以下输出,则没有正在运行的容器。

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

我在做什么错?有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

我不认为docker_container模块是按照您想要的方式设计的(例如,重新启动现有的容器)。该模块旨在按名称(而不是按ID)管理容器,并将检查正在运行的容器是否与提供给docker_container的选项相匹配。

使用docker命令重新启动容器可能会更好:

---
- 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 }}"