Subscribe to the feed

Ansible uses the Jinja2 templating system to handle variables in YAML playbooks. As I explained in my previous articlefilters are a very powerful feature in Ansible that allow you to manipulate data in many different ways. One useful filtering example is network configuration.

There's a Jinja2 filter that's useful when working with a network and an IP address: ipaddr(). To use it, you need to make sure you have the netaddr Python package, which you can install using:

% python3 -m pip install netaddr

Depending on the version of Python and Ansible, you may need to use pip3 to install the module. Just make sure that the Python and pip you use match what Ansible is using:

$ ansible --version | grep python
  ansible python module location = /usr/lib/python3.10/site-packages/ansible
  python version = 3.10.6 (main, Aug  2 2022, 00:00:00) [GCC 12.1.1 20220507 (Red Hat 12.1.1-1)]

$ which python
/usr/bin/python3

One last step before you can play with netaddr. If you're running an Ansible version greater than 2.9, you must install a collection called named ansible.utils. You can install it from Ansible Galaxy:

$ ansible-galaxy collection install ansible.utils
Starting galaxy collection install process
Process install dependency map
Starting collection install process
Downloading https://galaxy.ansible.com/download/ansible-utils-2.6.1.tar.gz to /home/admin2/.ansible/tmp/ansible-local-9482ftgrtdax/tmpg_vgd4id/ansible-utils-2.6.1-o60tm43g
Installing 'ansible.utils:2.6.1' to '/home/admin2/.ansible/collections/ansible_collections/ansible/utils'
ansible.utils:2.6.1 was installed successfully

[ Learn how to manage your Linux environment for success. ]

Handle network and IP addresses

The following playbook showcases a mere fraction of the things you can do with this powerful plugin, but refer to the documentation here and here to see how much more is available.

---
- name: Handling network and IP addresses
  hosts: localhost
  gather_facts: false
  vars:
    my_ips:
      - "10.0.0.72/24"
      - "10.0.300" 
      - "192.168.15.15"
      - "fe80::100/10"
      - "192.168.32.0/24"
  tasks:
    - name: Show information for network and ip
      ansible.builtin.debug:
        msg:
          - "IP................: {{ item }}"
          - "Is it a valid IP?.: {{ item | ansible.utils.ipaddr }}"
          - "Just the IP.......: {{ item | ansible.utils.ipaddr('address') }}"
          - "Is this a network?: {{ item | ansible.utils.ipaddr('net') }}"
      loop: "{{ my_ips }}"
...

Here is the resulting output:

$ ansible-playbook 04_ipaddr.yml 
[WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'

PLAY [Handling network and IP addresses] **************************************************************

TASK [Show information for network and ip] **************************************************************
ok: [localhost] => (item=10.0.0.72/24) => {
    "msg": [
        "IP................: 10.0.0.72/24",
        "Is it a valid IP?.: 10.0.0.72/24",
        "Just the IP.......: 10.0.0.72",
        "Is this a network?: "
    ]
}
ok: [localhost] => (item=10.0.300) => {
    "msg": [
        "IP................: 10.0.300",
        "Is it a valid IP?.: False",
        "Just the IP.......: False",
        "Is this a network?: False"
    ]
}
ok: [localhost] => (item=192.168.15.15) => {
    "msg": [
        "IP................: 192.168.15.15",
        "Is it a valid IP?.: 192.168.15.15",
        "Just the IP.......: 192.168.15.15",
        "Is this a network?: "
    ]
}
ok: [localhost] => (item=fe80::100/10) => {
    "msg": [
        "IP................: fe80::100/10",
        "Is it a valid IP?.: fe80::100/10",
        "Just the IP.......: fe80::100",
        "Is this a network?: "
    ]
}
ok: [localhost] => (item=192.168.32.0/24) => {
    "msg": [
        "IP................: 192.168.32.0/24",
        "Is it a valid IP?.: 192.168.32.0/24",
        "Just the IP.......: ",
        "Is this a network?: 192.168.32.0/24"
    ]
}

PLAY RECAP ********************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

The playbook and output deserve some additional explanation.

First, I defined the list my_ips to contain some valid IPv4 and IPv6 addresses, one invalid address, and a network address.

Next, I used that information in a loop to show what the ipaddr plugin can tell about each item:

  • "IP" — This is just the original IP from my list.
  • "Is it a valid IP?" — If it is, the plugin shows the IP itself. Otherwise, it shows False.
  • "Just the IP" — Gives only the address without the subnet mask.
  • "Is this a network?" — If it is, it shows the network address. Otherwise, it is empty.

In this example, my goal is to display the results. If I use this filter to configure network devices, I could do something similar or assign the content to variables and use it in subsequent tasks, roles, or even Ansible templates.

Wrap up

The ipaddr plugin is very handy for network configurations in server-provisioning playbooks. It is even more necessary for configuring network devices, and as you can see in the full documentation, the plugin is prepared for IPv6.

[ Download now: Advanced Linux commands cheat sheet. ]


Note: An earlier version of this article referred to ansible.netcommon and it has been updated to use ansible.utils instead.


About the author

Roberto Nozaki (RHCSA/RHCE/RHCA) is an Automation Principal Consultant at Red Hat Canada where he specializes in IT automation with Ansible. He has experience in the financial, retail, and telecommunications sectors, having performed different roles in his career, from programming in mainframe environments to delivering IBM/Tivoli and Netcool products as a pre-sales and post-sales consultant.

Roberto has been a computer and software programming enthusiast for over 35 years. He is currently interested in hacking what he considers to be the ultimate hardware and software: our bodies and our minds.

Roberto lives in Toronto, and when he is not studying and working with Linux and Ansible, he likes to meditate, play the electric guitar, and research neuroscience, altered states of consciousness, biohacking, and spirituality.

Read full bio
UI_Icon-Red_Hat-Close-A-Black-RGB

Browse by channel

automation icon

Automation

The latest on IT automation for tech, teams, and environments

AI icon

Artificial intelligence

Updates on the platforms that free customers to run AI workloads anywhere

open hybrid cloud icon

Open hybrid cloud

Explore how we build a more flexible future with hybrid cloud

security icon

Security

The latest on how we reduce risks across environments and technologies

edge icon

Edge computing

Updates on the platforms that simplify operations at the edge

Infrastructure icon

Infrastructure

The latest on the world’s leading enterprise Linux platform

application development icon

Applications

Inside our solutions to the toughest application challenges

Original series icon

Original shows

Entertaining stories from the makers and leaders in enterprise tech