In this tutorial, we will learn about when condition in ansible playbook
We don’t have If condition here. Instead of that we can use when condition
Syntax
when: {condition}
when: inventory_hostname == "local"
In below example we are using when condition based on host
Example
---
- hosts: 127.0.0.1
tasks:
- name: Make a directory
shell: "mkdir sample"
when: inventory_hostname == "127.0.0.1"
- name: make directory
shell: "mkdir sample"
when: inventory_hostname == "10.118.226.25" or inventory_hostname == "10.118.225.65"
Execute Command
ansible-playbook whenexample.yml
Output
PLAY [127.0.0.1] *************************************************************************************************************************************
TASK [Gathering Facts] *******************************************************************************************************************************
ok: [127.0.0.1]
TASK [Make a directory] ******************************************************************************************************************************
[WARNING]: Consider using the file module with state=directory rather than running 'mkdir'. If you need to use command because file is insufficient
you can add 'warn: false' to this command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.
changed: [127.0.0.1]
TASK [make directory] ********************************************************************************************************************************
skipping: [127.0.0.1]
PLAY RECAP *******************************************************************************************************************************************
127.0.0.1 : ok=2 changed=1 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
when condition matches you can see the changed: [127.0.0.1]
in result.
Else it will skip the task skipping: [127.0.0.1]
in result
Reference
Below is Ansible documentation for conditions https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html
Related Articles
ignore warning message in ansible
Ignore Error in Ansible playbook