Ansible Ifs and Loops

During my project for an Ansible Security Audit I needed to use loops and if statements. This for me is a weakness and so I have written this to be used a quick reference guide on how to use Ansible “when “and “with_items”.

Both of these have been used in my SNMP checking playbook. The post can be found here, and GitHub can be found here.

Base Playbook Example

When – If Like

The when is and if like statement in Python. My examples will be: When something, run task.
If the “when” condition is not met then the task will be skipped.

When there is output from the task named Show Running SNMP using the registered variable misconfigured_SNMP, then run the task below.

“When” conditions can also be a list of items that you want to match. Each item in a list is denoted with a hyphen – .

There are three conditions to be matched here.
When;
– There is output from the task named Show Running SNMP using the registered variable misconfigured_SNMP
– And the length of that list is greater than 1
– And the second element of that list is not “snmp-server community COM_STRING RO”

With_Items – Loop

In my opinion Ansible loops read upside down. You can reference the item in the loop in the lines above the loop. I’m used to Python so being out of order won’t work.

In the below task there is a single loop to remove the snmp-server configuration.

with_items can be a list of items denoted by a hyphen – .

with_items can also be a list containing multiple elements. In the example below I have a task that is using the output from a previous task which contains a list of SNMP community string configuration lines.
Just passing in the list to the loop Ansible will iterate over each element of that list and evaluate each element as if it were its own.

Putting When and With_items Together

This is the example from my SNMP Playbook. It combines “when” and “with_items”.
This doesn’t read from top to bottom.
So what is happening is;
– If there is a variable defined named misconfigured_SNMP then proceed.
– That variable is a list, for each item in that list, check if it does not match the snmp_string variable which is defined at the top of the playbook.
– If the list element does not match then execute the ios_config line to remove it.
– If the list element does match then skip that particular line.

Leave a Comment

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