Ansible conditions
Conditional statements are mostly used in Ansible playbooks where there is a mix of different variables, each representing different entities such as software packages, servers, networking devices, and so on. we can control which tasks/roles will be run or skipped on their targeted hosts/nodes with the help of when statement
Let's see an example for the condition in ansible playbook
#cat condition.yaml
---
- hosts: all
become: yes
tasks:
- name: install apache on ubuntu
apt: name=apache2 update_cache=yes state=latest
when: ansible_os_family == "Debian"
- name: start apache on ubuntu
service: name=apache2 enabled=yes state=started
when: ansible_os_family == "Debian"
- name: install apache on centos
yum: name=httpd update_cache=yes state=latest
when: ansible_os_family == "RedHat"
- name: start apache on centos
service: name=httpd enabled=yes state=started
when: ansible_os_family == "RedHat"
To run ansible-playbook on hosts
# ansible-playbook condition.yaml
PLAY [all] **************************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************
ok: [192.168.1.2]
TASK [install apache on ubuntu] *****************************************************************************************************************************
skipping: [192.168.1.2]
TASK [start apache on ubuntu] *******************************************************************************************************************************
skipping: [192.168.1.2]
TASK [install apache on centos] *****************************************************************************************************************************
changed: [192.168.1.2]
TASK [start apache on centos] *******************************************************************************************************************************
changed: [192.168.1.2]
PLAY RECAP **************************************************************************************************************************************************
192.168.1.2 : ok=3 changed=2 unreachable=0 failed=0 skipped=2 rescued=0 ignored=0
we can see that output above installing the apache package on the ubuntu node is skipped and for the centos node, it has been changed.
Recent Comments
No comments
Leave a Comment
We will be happy to hear what you think about this post