Ansible uses the Jinja2 templating system to handle variables in YAML playbooks. As I explained in my previous article, filters 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.
저자 소개
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.
채널별 검색
오토메이션
기술, 팀, 인프라를 위한 IT 자동화 최신 동향
인공지능
고객이 어디서나 AI 워크로드를 실행할 수 있도록 지원하는 플랫폼 업데이트
오픈 하이브리드 클라우드
하이브리드 클라우드로 더욱 유연한 미래를 구축하는 방법을 알아보세요
보안
환경과 기술 전반에 걸쳐 리스크를 감소하는 방법에 대한 최신 정보
엣지 컴퓨팅
엣지에서의 운영을 단순화하는 플랫폼 업데이트
인프라
세계적으로 인정받은 기업용 Linux 플랫폼에 대한 최신 정보
애플리케이션
복잡한 애플리케이션에 대한 솔루션 더 보기
가상화
온프레미스와 클라우드 환경에서 워크로드를 유연하게 운영하기 위한 엔터프라이즈 가상화의 미래