[英]Restart multiple Docker containers using Ansible
how do i dynamically restart all my docker containers from Ansible?如何从 Ansible 动态重启所有 docker 容器? I mean i know a way where i can define my containers in a variable and loop through them but what i want to achieve is this -我的意思是我知道一种方法,我可以在变量中定义我的容器并循环它们,但我想要实现的是 -
Fetch the currently running containers and restart all or some of them one by one through some loop.获取当前正在运行的容器,并通过某个循环一一重启所有或部分容器。
How to achieve this using Ansible?如何使用 Ansible 实现这一目标?
Retrieve name/image for all the running container:检索所有正在运行的容器的名称/图像:
docker container ls -a --format '{{.Names}} {{.Image}}'
You could also filter the output of the docket container
command to a specific image name, thanks to the --filter ancestor=image_name
option:您还可以将docket container
命令的 output 过滤为特定的图像名称,这要归功于--filter ancestor=image_name
选项:
docker container ls -a --filter ancestor=alpine --format '{{.Names}} {{.Image}}'
First I would define some filters as Ansible variables:首先,我将一些过滤器定义为 Ansible 变量:
vars:
- image_v1: '--filter ancestor=my_image:v1'
- image_v2: '--filter ancestor=my_image:v2'
Them I will execute the docker container
command in a dedicated task and save the command output to an Ansible variable:他们我将在专用任务中执行docker container
命令并将命令 output 保存到 Ansible 变量中:
- name: Get images name
command: docker container ls -a {{ image_v1 }} {{ image_v2 }} --format "{{ '{{' }}.Names {{ '}}' }} {{ '{{' }}.Image {{ '}}' }}"
register: docker_images
Finally I will iterate over it and use it into the docker_container
ansible module:最后,我将对其进行迭代并将其用于docker_container
ansible 模块:
- name: Restart images
docker_container:
name: "{{ item.split(' ')[0]}}"
image: "{{ item.split(' ')[1]}}"
state: started
restart: yes
loop: "{{ docker_images.stdout_lines}}"
final playbook.yml最终剧本.yml
---
- hosts: localhost
gather_facts: no
vars:
- image_v1: '--filter ancestor=my_image:v1'
- image_v2: '--filter ancestor=my_image:v2'
tasks:
- name: Get images name
command: docker container ls -a {{ image_v1 }} {{ image_v2 }} --format "{{ '{{' }}.Names {{ '}}' }} {{ '{{' }}.Image {{ '}}' }}"
register: docker_images
- name: Restart images
docker_container:
name: "{{ item.split(' ')[0]}}"
image: "{{ item.split(' ')[1]}}"
state: started
restart: yes
loop: "{{ docker_images.stdout_lines}}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.