Defining a change

Similar to defining a task failure, it is also possible to define what constitutes a changed task result. This capability is particularly useful with the command family of modules (command, shell, raw, and script). Unlike most other modules, the modules of this family do not have an inherent idea of what a change may be. In fact, unless otherwise directed, these modules only result in failed, changed, or skipped. There is simply no way for these modules to assume a changed condition versus unchanged.

The changed_when condition allows a playbook author to instruct a module on how to interpret a change. Just like failed_when, changed_when performs a test to generate a Boolean result. Frequently, the tasks used with changed_when are commands that will exit nonzero to indicate that no work is needed to be done, so, often, authors will combine changed_when and failed_when to fine-tune the task result evaluation.

In our previous example, the failed_when condition caught the case where there was no work to be done but the task still showed a change. We want to register a change on the exit code 0, but not on any other exit code. Let's expand our example task to accomplish this:

  - name: delete branch bad
command: git branch -D badfeature
args:
chdir: /srv/app
register: gitout
failed_when:
- gitout.rc != 0
- not gitout.stderr is search('branch.*not found')
changed_when: gitout.rc == 0

Now, if we run our task when the branch still does not exist, we'll see the following output:

Note how the changed key now has the value false.

Just for the sake of completeness, we'll change the scenario so that the branch does exist and run it again. To create the branch, simply run git branch badfeature from the /srv/app directory. Now, we can execute our playbook once again to see the output, which is as follows:

This time, our output is different; it's registering a change, and the stdout data shows the branch being deleted.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.31.209