This is a only version

Found at: raymii.org:70/Ansible_-_Only-do-something-if-another-action-changed.txt

This is a text-only version of the following page on https://raymii.org:
Title       : 	Ansible - Only do something if another action changed
Author      : 	Remy van Elst
Date        : 	22-12-2013
Last update : 	15-12-2018
URL         : 	https://raymii.org/s/tutorials/Ansible_-_Only-do-something-if-another-action-changed.html
Format      : 	Markdown/HTML

This Ansible tutorial shows you how execute actions only if another action has
changed. For example, a playbook which downloads a remote key for package
signing but only executes the apt-add command if the key has changed. Or a
playbook which clones a git repository and only restarts a service if the git
repository has changed.

I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $100 credit for 60 days.

  * 15-12-2018: Updated ansible syntax to 2.5
  * 22-12-2013: initial article

Using the `register` option we can, suprisingly, registers the result of a
playbook action. In another action we can access this variable and use `when` to
only execute an action if the previous action changed the machines state. The
below example downloads the NGINX debian package signing key, but only adds it
if the key changed or did not exist yet:

    - name: Create folder for apt keys
        path: /var/keys 
        state: directory 
        owner: root
    - name: Download nginx apt key
        url: http://nginx.org/keys/nginx_signing.key 
        dest: /var/keys/nginx_signing.key
      register: aptkey
    - name: Add nginx apt key
      command: "apt-key add /var/keys/nginx_signing.key"
      when: aptkey.changed
    - name: Update apt cache
        update_cache: yes
      when: aptkey.changed

[This is an older article, there is an ansible module to add apt-keys now][2].

It is part of one of my playbooks which installs and configures NGINX. I want to
use the latest stable version provided by the NGINX project. They sign their
debian packages, so I need their key otherwise I cannot install their packages
from their repo. They provide their key online, the `get_url` module downloads
this key. If the key is not on the system or if the key has changed, the action
reports itself as changed. If the key already exists on the system and is the
same as the downloaded file, it does not report itself changed. We only want to
execute `apt-key add` if the key is new or changed. By using the `register:
aptkey` option and the `when: aptkey.changed` options, we make sure apt only
adds the key and updates the cache if the key was not there before. This helps
with idempotency and saves system resources.

Another example I use consists out of cloning a git repository, and based on if
the code in that repo has changed, restarting a service. I cannot go in much
detail because this setup runs at a client, therefore the values are stubs.
However, I can tell that this example runs via `ansible-pull` mode and makes
sure one of their products is always the latest version. See it as a form of
continuous deployment.

    - name: Clone git repository
        repo: https://gitlab.example.org/example-user/example-repo.git 
        dest: /opt/example 
        version: production 
        force: yes
      register: examplesoftware
    - name: restart service if new version is deployed
        name: example 
        state: restarted 
        enabled: yes
      when: examplesoftware.changed

The last example comes from my vnstat playbook. vnstat is a console based
network traffic analyzer and logger, it gives me nice overviews of the traffic
used. The below playbook installs vnstat but only executes the vnstat initialize
command when the configuration file changes. This file never changes except at
installation, so therefore I can be fairly sure the vnstat database is only
initialized once.

    - name: install vnstat
        name: vnstat 
        state: latest 
        update_cache: yes
    - name: Place vnstat config template
        src: vnstat.conf 
        dest: /etc/vnstat.conf 
        mode: 0644 
        owner: root 
        group: root
      notify: restart vnstat
      register: result
    - name: initialize vnstat database
      command: sudo vnstat -u -i {{ interface }}
      when: result.changed
      notify: restart vnstat

You can also go very advanced with error handling and defining when something
changes or fails. The [ansible documentation covers that fairly well][3].

   [1]: https://www.digitalocean.com/?refcode=7435ae6b8212
   [2]: https://raymii.org/s/tutorials/Ansible_-_Add_an_apt-repository_on_Debian_and_Ubuntu.html
   [3]: http://www.ansibleworks.com/docs/playbooks_error_handling.html


All the text on this website is free as in freedom unless stated otherwise. 
This means you can use it in any way you want, you can copy it, change it 
the way you like and republish it, as long as you release the (modified) 
content under the same license to give others the same freedoms you've got 
and place my name and a link to this site with the article as source.

This site uses Google Analytics for statistics and Google Adwords for 
advertisements. You are tracked and Google knows everything about you. 
Use an adblocker like ublock-origin if you don't want it.

All the code on this website is licensed under the GNU GPL v3 license 
unless already licensed under a license which does not allows this form 
of licensing or if another license is stated on that page / in that software:

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see .

Just to be clear, the information on this website is for meant for educational 
purposes and you use it at your own risk. I do not take responsibility if you 
screw something up. Use common sense, do not 'rm -rf /' as root for example. 
If you have any questions then do not hesitate to contact me.

See https://raymii.org/s/static/About.html for details.