'Ansible: Reload container if previous tasks resulted in changed==true?
How do I configure a docker_container task to restart a container if specific prior tasks resulted in changed==true?
Say I have three copy tasks(A,B,C) and then a docker_container task with state=started.
How do I have a docker_container task perform a restart if copy task A or copy task C resulted in changed==true?
If task A and task C both result in changed==false and the docker_container would otherwise not restart the container, then ansible should NOT restart the container.
Solution 1:[1]
You can simply use a handler for this.
---
- name: Testplaybook
hosts: ...
handlers:
- name: restart docker
...
tasks:
- name: Copy A
copy:
...
notify: restart docker
- name: Copy B
copy:
...
- name: Copy C
copy:
...
notify: restart docker
This will restart your docker container if copy A and/or copy C changes. The handlers will be run at the end of the playbook (or when a task see below asks for it) and multiple notify events of the same category will only restart the container once.
If you want your restart right after the copy tasks you can add a task:
- name: Flush handlers
meta: flush_handlers
Solution 2:[2]
There's an easier way which doesn't require you to duplicate the container parameters in the handler - use the restart parameter:
- name: Create config file
ansible.builtin.template:
src: config.yml.j2
dest: /etc/config.yml
register: foobar_config
- community.general.docker_container:
name: foobar
image: "{{ foobar_image }}"
restart_policy: always
restart: "{{ foobar_config.changed | default(false) }}"
volumes:
- "/etc/config.yml:/etc/conf.yml"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | β.εηοιτ.βε |
| Solution 2 | weakcamel |
