[英]Ansible workflow for building Docker image and recreating Docker container if image was changed?
I've been struggling with figuring out what the proper Ansible workflow is for deploying a Docker image and recreating a Docker container if the image has changed. 我一直在努力弄清楚正确的Ansible工作流程是什么,用于部署Docker映像,如果映像已更改,则重新创建Docker容器。
Here's the task list of a role I initially thought would work: 这是我最初认为可以工作的角色的任务列表:
- name: Deploy Source
synchronize:
archive: yes
checksum: yes
compress: yes
dest: '/tmp/{{ app_name }}'
src: ./
- name: Build Docker Image
docker_image:
name: '{{ docker_image_name }}'
path: '/tmp/{{ app_name }}'
rm: yes
state: present
register: build_docker_image
- name: Create Docker Container
docker_container:
image: '{{ docker_image_name }}'
keep_volumes: yes
name: '{{ docker_container_name }}'
recreate: '{{ true if build_docker_image.changed else omit }}'
state: started
This does not work because the Ansible docker_image
module does not offer a state: latest
option. 这不起作用,因为Ansible
docker_image
模块未提供state: latest
docker_image
选项。 state: present
only checks if the image exists and not if it's up to date. state: present
仅检查图像是否存在,而不检查图像是否最新。 This means that even if the Dockerfile
has changed, the image will not be rebuilt. 这意味着即使
Dockerfile
已更改,该映像也不会重建。 docker_image
does offer a force: yes
option, but this will always recreate the image regardless of whether there was a change to the Dockerfile
. docker_image
确实提供了force: yes
选项,但这将始终重新创建映像,而不管Dockerfile
是否发生了变化。 When force: yes
is used, it makes sense to me that it's better to always recreate containers running the image to prevent them from pointing to dangling Docker images. 当使用
force: yes
,对我来说有意义的是,总是重新创建运行该映像的容器,以防止它们指向悬空的Docker映像,这是更好的选择。
What am I missing? 我想念什么? Is there a better alternative?
有更好的选择吗?
User viggeh provided a workaround on the Ansible GitHub which I've adapted to my needs as follows: viggeh用户在Ansible GitHub上提供了一种变通方法 ,我已根据需要对其进行了调整,如下所示:
- name: Deploy Source
synchronize:
archive: yes
checksum: yes
compress: yes
dest: '/tmp/{{ app_name }}'
src: ./
- name: Get Existing Image ID
command: 'docker images --format {% raw %}"{{.ID}}"{% endraw %} --no-trunc {{ docker_image_name }}:{{ docker_image_tag }}'
register: image_id
changed_when: image_id.rc != 0
- name: Build Docker Image
docker_image:
force: yes
name: '{{ docker_image_name }}'
path: '/tmp/{{ app_name }}'
rm: yes
state: present
tag: '{{ docker_image_tag }}'
register: image_build
changed_when: image_id.stdout != image_build.image.Id
- name: Create Docker Container
docker_container:
image: '{{ docker_image_name }}'
keep_volumes: yes
name: '{{ docker_container_name }}'
recreate: '{{ True if image_build.changed else omit }}'
state: started
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.