Skip to content

Instantly share code, notes, and snippets.

@cidrblock
Created April 12, 2022 20:17
Show Gist options
  • Save cidrblock/dbdfc963fb5d1c3da31b57624fd62f40 to your computer and use it in GitHub Desktop.
Save cidrblock/dbdfc963fb5d1c3da31b57624fd62f40 to your computer and use it in GitHub Desktop.
Validate IPv4 address in lists of interfaces
- hosts: localhost
gather_facts: false
tasks:
- name: Define some data
ansible.builtin.set_fact:
data:
wan:
- name: LAN3
ipv4-address: 100.100.100.1
subnet-mask: 255.255.255.248
gateway: 100.100.100.2
- name: LAN4
ipv4-address: 1.2.3.4
subnet-mask: 255.255.255.0
gateway: 1.2.3.4
ha:
- name: LAN10
ipv4-address: 169.254.9.1
subnet-mask: 255.255.255.252
vlan:
- id:
ipv4-address:
subnet-mask:
mgmt:
- name: Mgmt
ipv4-address:
subnet-mask:
invalid:
- name:
ipv4-address: 256.256.256.256
subnet-mask:
- name: Walk the interfaces of each group
ansible.builtin.include_tasks:
file: validate_interfaces.yml
loop: "{{ data|dict2items }}"
loop_control:
loop_var: group_tuple
vars:
group: "{{ group_tuple.key }}"
interfaces: "{{ group_tuple.value }}"
- name: >-
Validate an interface has a valid IPv4 address or none:
'{{ group }}/{{ name }}'
ansible.builtin.assert:
that: is_ipv4 or is_none
success_msg: >-
Interface '{{ name }}' in group '{{ group }}'
has a valid IPv4 address: {{ ip_address }}
fail_msg: >-
Interface '{{ name }}' in group '{{ group }}'
has an invalid IPv4 address: {{ ip_address }}
vars:
interface_name: "{{ interface['name']|default(none) }}"
interface_id: "{{ interface['id']|default(none) }}"
name: "{{ interface_name or interface_id or 'unknown' }}"
ip_address: "{{ interface['ipv4-address'] }}"
is_ipv4: "{{ interface['ipv4-address'] is ansible.utils.ipv4_address }}"
is_none: "{{ interface['ipv4-address'] is none }}"
- name: "Validate a group of interfaces: '{{ group }}'"
ansible.builtin.include_tasks:
file: validate_interface.yml
loop: "{{ interfaces }}"
loop_control:
loop_var: interface
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment