ansible when condition examples with RC

Ansible When Condition Examples

Ansible when condition is used to execute the tasks if the conditions that you defined are true.
If the conditions are not true it will skip the executions of that particular task. In the following steps i will show you ansible when condition examples with rc return code.

Ansible Playbook When Condition Example

[root@ip-10-0-0-20 ~]# cat abc.yml
---
- hosts: localhost
  gather_facts: no

  tasks:
  - name: verify httpd version
    command: /usr/sbin/httpd -v
    register: version
    ignore_errors: True

  - name: print httpd version
    debug:
      msg: "{{ version }}"
    when: "version.rc == 0"

  - name: install httpd 
    yum: name=httpd state=present
    when: "version.rc != 0 "

In the first task we are verifying the httpd version. In the second task we are printing the httpd version if installed. In the third task we are installing httpd if not installed.

log-output:

PLAY [localhost] *******************************************************************************************************************************************************************************

TASK [verify httpd version] ********************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "cmd": "/usr/sbin/httpd -v", "msg": "[Errno 2] No such file or directory", "rc": 2}
...ignoring

TASK [print httpd version] ***************************************************************************************************************************************************************************
skipping: [localhost]

TASK [install httpd] ***************************************************************************************************************************************************************************
changed: [localhost]

PLAY RECAP *************************************************************************************************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0

Here rc is the return code of command /usr/sbin/httpd -v

If the return code is zero then the command executed and we got some output.

If the return code is non zero the command is failed and we didn't get any output.

if the return code is zero

If the return code is zero that means httpd is installed in that system. And we are printing that httpd version in second task. and third task will be skipped.

if the return code is non zero

If the return code is non zero then there is no httpd installed in that system. So the second task will be skipped
and  in the third task we are installing httpd.

 

Leave a Reply

Your email address will not be published. Required fields are marked *