antonbormotov
antonbormotov

Reputation: 1987

Ansible handler runs only if changed: true

Installing ntp with Ansible, I notify handler in order to start ntpd service:
Task:

---
# roles/common/tasks/ntp.yml
  - name: ntp | installing
    yum: name=ntp state=latest
    notify: start ntp

Handler:

---
# roles/common/handlers/main.yml

- name: start ntp
  service: name=ntpd state=started

If service has not been installed, ansible installs and starts it.
If service has been installed already, but is not running, it does not notify handler:
status of task is changed: false
That means, I cannot start it, if it has been already presented in OS.

Is there any good practice that helps to be sure that service has been installed and is in running state?

PS: I may do so:

---
# roles/common/tasks/ntp.yml
  - name: ntp | installing
    yum: name=ntp state=latest
    notify: start ntp
    changed: true

but I am not sure that it is good practice.

Upvotes: 8

Views: 21290

Answers (2)

MillerGeek
MillerGeek

Reputation: 3137

From the Intro to Playbooks guide:

As we’ve mentioned, modules are written to be ‘idempotent’ and can relay when they have made a change on the remote system. Playbooks recognize this and have a basic event system that can be used to respond to change.

These ‘notify’ actions are triggered at the end of each block of tasks in a playbook, and will only be triggered once even if notified by multiple different tasks.

Handlers only run on change by design. If you change a configuration you often need to restart a service, but don't want to if nothing has changed.

What you want is to start a service if it is not already running. To do this you should use a regular task as described by @udondan :

- name: ntp | installing
  yum:
    name: ntp
    state: latest

- name: ntp | starting
  service:
    name: ntpd
    state: started
    enabled: yes

Ansible is idempotent by design, so this second task will only run if ntp is not already running. The enabled line will set the service to start on boot. Remove this line if that is not desired behavior.

Upvotes: 12

udondan
udondan

Reputation: 60079

Why don't you just add a service task then? A handler usually is for restarting a service after configuration has changed. To ensure a service is running not matter what, just add at task like that:

- name: Ensure ntp is running
  service:
    name: ntpd
    state: started

Upvotes: 6

Related Questions