PlayBooks are a great thing, but how are we going to handle exceptions, what about errors during the tasks? what if we want to specify a condition before executing the task? How are we going to declare variables? This post is for those things.
When a task fails, all the subsequent tasks will not be executed on the host. In that case, we may have to troubleshoot and rerun the tasks that failed. We cannot rerun the entire playbook for this and in some cases this is also not recommended. So to achieve this we have something called Play Recap which has the information of the failed hosts.
Notice, Ansible has created a retry file for us. Going through the contents of the retry file, it has the name of the server that failed to execute the tasks. So to rerun the task, we just need to use the ‘limit’ parameter and use the command given by recap.
$ ansible-playbook -i my_inventory my_playbook.yml --limit @/home/vagrant/my_playbook.retry
Consider a situation where you have different OS families in an inventory file which is the case most of the times and you want to run specific tasks only on certain OS family machines. We need to make use of when module for this. In our case, we have centos based machine named web which uses the package manager yum, so we want to validate this before running the yum task. Modify the playbook as below for this.
Note: To use any filters from the setup module to check the condition, gather_facts must be set to true.
We can also make use of variable declaration in YAML to avoid changes in multiple locations in the file and also for specifying the dynamic content. use the vars keywork for this. I am declaring a variable dest_file which stores the path of the destination used in the copy module. Below is the usage
Notify and Handlers
Often times, we come across requests to update the configuration file and restart the respective service for the new configuration to take effect. In such cases, we use the notify module to mention the name of the task to be done and in the handler section we mention the task itself. Bringing them all together, the playbook looks as below. The name mentioned in the notify section is case sensitive and respective handler has to be mentioned with the same name.
Hope this was informative. Thanks!