Pages

Thursday, February 11, 2016

Ansible – more Operators

Share it Please

In the previous article we have seen how we can use the with condition to check for things. Ansible also provides in and not Operators for additional validations. In this article we will see how in and not can be used in our playbooks.

Some times we need to check only a certain part of the string or the output. To perform such kinds of checks, Ansible provides the in and not operators.

[root@vx111a with-ansible]# cat with2.yml
---
- hosts: cent
  tasks:
    - name: Check HTTPD Packages
      shell: rpm -qa  | grep httpd
      register: rpm_status
      ignore_errors: yes

    - name: check If HTTPD Rpm is Installed
      debug: msg="Httpd is installed on the remote Machine"
      when: " 'httpd' in rpm_status.stdout"

    - name: Check if Httpd is installed
      debug: msg="Httpd is not installed on the remote machine"
      when: not 'httpd' in rpm_status.stdout

the above one is the basic example of using the in and not operators. The playbook defines a task using a shell module to check for the httpd package. The task is registered with a variable rpm_status from which we extract data.

We use the rpm_status variable stdout to check whether the httpd is in the output using the in Operator. In the next task we use the not operator to check that the string httpd is not in the variable ouput. When we run the playbook we see

[root@vx111a with-ansible]# ansible-playbook with2.yml

PLAY [cent] *******************************************************************

GATHERING FACTS ***************************************************************
ok: [172.16.202.96]

TASK: [Check HTTPD Packages] **************************************************
failed: [172.16.202.96] => {"changed": true, "cmd": "rpm -qa | grep httpd", "delta": "0:00:00.120259", "end": "2016-02-09 09:54:44.286588", "rc": 1, "start": "2016-02-09 09:54:44.166329", "warnings": ["Consider using yum module rather than running rpm"]}
...ignoring

TASK: [check If HTTPD Rpm is Installed] ***************************************
skipping: [172.16.202.96]

TASK: [Check if Httpd is installed] *******************************************
ok: [172.16.202.96] => {
    "msg": "Httpd is not installed on the remote machine"
}

PLAY RECAP ********************************************************************
172.16.202.96              : ok=3    changed=1    unreachable=0    failed=0  


More to Hope, Happy Learning J

No comments :

Post a Comment