Home » GeekSpeak » Ansible – perform an action ONLY if something changes

Ansible – perform an action ONLY if something changes

I found this article: “Ansible – Only do something if another action changed

Great article –

In my case I wanted to change the /etc/postfix/main.cf file on a lot of my servers. When the file changes, you have to restart the postfix service. I was able to use the “register” directive as described in the article.

---

– name: install and configure postfix
   hosts: test
   remote_user: ansprod
   become: yes

tasks:
– name: install postfix
   yum: pkg=postfix state=present

– name: install /etc/postfix/main.cf
   copy: src=main.cf dest=/etc/postfix/main.cf owner=root group=root mode=0644 backup=yes
   register: postfixchg

– name: restart posfix if /etc/postfix/main.cf has changed
   service: name=postfix state=restarted
   when: postfixchg.changed

– name: enable posfix
   service: name=postfix enabled=yes state=started

 

notice – in the copy task, I registered “posftixchg”. and in the following service task, I added the “when postfixchg.changed” –

On my first run, when I updated the file, the service was restarted. On all runs since then, the task was skipped (see below run).


[ansprod@emperor ~/PLAYS]$ ansible-playbook -i inv postfix/tasks/main.yml

PLAY [install and configure NTP] ***********************************************

TASK [setup] *******************************************************************
ok: [lnyctomtest]
ok: [mosman]
ok: [yarra]
ok: [lnjtomtest]

TASK [install postfix] *********************************************************
ok: [yarra]
ok: [lnyctomtest]
ok: [lnjtomtest]
ok: [mosman]

TASK [install /etc/postfix/main.cf] ********************************************
ok: [yarra]
ok: [lnyctomtest]
ok: [lnjtomtest]
ok: [mosman]

TASK [restart posfix if /etc/postfix/main.cf has changed] **********************
skipping: [lnjtomtest]
skipping: [lnyctomtest]
skipping: [mosman]
skipping: [yarra]

TASK [enable posfix] ***********************************************************
ok: [yarra]
ok: [lnyctomtest]
ok: [lnjtomtest]
ok: [mosman]

PLAY RECAP *********************************************************************
lnjtomtest : ok=4 changed=0 unreachable=0 failed=0
lnyctomtest : ok=4 changed=0 unreachable=0 failed=0
mosman : ok=4 changed=0 unreachable=0 failed=0
yarra : ok=4 changed=0 unreachable=0 failed=0

Leave a Reply