How to write an Ansible role task, which is executed only when any of the previous tasks in the task file has been modified?

I am working on the role in which I want one task to be executed at the end of the task file if and only if any previous tasks in this task file have been changed .

For example, I have:

- name: install package
  apt: name=mypackage state=latest

- name: modify a file
  lineinfile: do stuff

- name: modify a second file
  lineinfile: other stuff

- name: restart if anything changed
  service: name=mypackage state=restarted

... and I only want to restart the service if the update was installed or any configuration files were changed.

How can i do this?

+4
source share
1 answer

The best practice here is to use handlers .

In your role, create a file handlers/main.ymlwith the contents:

- name: restart mypackage
  service: name=mypackage state=restarted

. , (= )

- name: install package
  apt: name=mypackage state=latest
  notify: restart mypackage

- name: modify a file
  lineinfile: do stuff
  notify: restart mypackage

- name: modify a second file
  lineinfile: other stuff
  notify: restart mypackage

. , mypackage, :

- meta: flush_handlers

, force_handlers. , mypackge, . force_handlers=True ansible.cfg, . , , , , .


, . , , .

- name: install package
  apt: name=mypackage state=latest
  register: mypackage_1

- name: modify a file
  lineinfile: do stuff
  register: mypackage_2

- name: modify a second file
  lineinfile: other stuff
  register: mypackage_3

- name: restart if anything changed
  service: name=mypackage state=restarted
  when: mypackage_1 | changed or mypackage_2 | changed or mypackage_3 | changed

. Ansible Handler vs register.

+6

All Articles