Ansible logic constructs are very simple. There are no for
loops, but there is with_sequence
. If we can make a list, we can iterate the list. This shows how to make a simple list of host addresses given a subnet (in CIDR notation).
---
- hosts: localhost
gather_facts: no
vars:
subnet: 192.168.1.20/28
tasks:
- name: Prime the list of hosts
set_fact:
iter_hosts: []
- name: Make list of hosts in subnet
no_log: true #It's a lot of unnecessary chatter.
# Start at 1 (with_sequence default) and
# stop at size-2 to avoid network and broadcast addresses.
with_sequence: end={{subnet|ipaddr('size')|int -2}}
set_fact:
iter_hosts: "{{ iter_hosts + [subnet|ipaddr(item)|ipaddr('address')] }}"
- debug: var=iter_hosts
With the list of hosts, ansible can try different things. It's a way to walk a LAN for discovery and testing, all within ansible.