Conditions based on registered variables
Often in a playbook, you want to execute or skip a task based on the outcome of an earlier task. For example, you might want to configure a service after it is upgraded by an earlier task. To create a conditional based on a registered variable:
You create the name of the registered variable using theregisterkeyword. A registered variable always contains the status of the task that created it as well as any output that the task generated. You can use registered variables in templates and action lines as well as in conditionalwhenstatements. You can access the string contents of the registered variable usingvariable.stdout. For example:
You can use registered results in the loop of a task if the variable is a list. If the variable is not a list, you can convert it into a list, with eitherstdout_linesor withvariable.stdout.split(). You can also split the lines by other fields:
The string content of a registered variable can be empty. If you want to run another task only on hosts where the stdout of your registered variable is empty, check the registered variable’s string contents for emptiness:
Ansible always registers something in a registered variable for every host, even on hosts where a task fails or Ansible skips a task because a condition is not met. To run a follow-up task on these hosts, query the registered variable forisskipped(not for “undefined” or “default”). SeeRegistering variablesfor more information. Here are sample conditionals based on the success or failure of a task. Remember to ignore errors if you want Ansible to continue executing on a host when a failure occurs: