I often write this patterns when I want to make a role for a service (I'm using Mongo for this example, but it's the same with any other service like Nginx, MySQL, Redis, Bind, ElasticSearch, etc etc). The logic that I want to implement is:
- If the service is not started, start it
- Else, if the service is already started
- If some configuration has changed since it started, restart
- Else, do nothing (the service is already running and current)
When I write this in Ansible, I do it like this:
roles/mongo/tasks/main.yml
---
- name: Install Mongo
yum:
name: mongodb-org
state: present
- name: Configure mongo
template:
src: mongod.conf.j2
dest: /etc/mongod.conf
notify:
- restart mongod
- name: Start Mongo
service:
name: mongod
state: started
roles/mongo/handlers/main.yml
---
- name: restart mongod
service:
name: mongod
state: restarted
However, this doesn't quite follow what I wrote above. The logic for the above code is
- If the service is not started, start it
- If any configuration changed, even if it changed before we started the service, then restart the service
The result is that the first time I run my playbook, I
- Install Mongo
- Configure Mongo
- Start Mongo
- Restart Mongo
I wish I could skip that last restart. In my head, I think that the "Start Mongo" task should clear the "restart mongod" handler.
Is there any way to cancel a handler notification?
Or, is there a better way to write my playbook to achieve the logic that I actually want?