How would you do IP address calculations in a template?
AdvancedConceptJinja2, Conditionals and Loops
Answer
Use the ansible.utils.ipaddr and ipmath-style filters, which depend on the netaddr Python package on the controller.
network: "{{ '10.20.30.40/24' | ansible.utils.ipaddr('network') }}" # 10.20.30.0
prefix: "{{ '10.20.30.40/24' | ansible.utils.ipaddr('prefix') }}" # 24
valid: "{{ addr | ansible.utils.ipaddr | bool }}"
nth: "{{ '10.20.30.0/24' | ansible.utils.ipaddr('net') | ansible.utils.ipaddr('10') }}"
Alternatives are ansible.utils.cidr_merge and ipsubnet. Install with pip install netaddr and ansible-galaxy collection install ansible.utils.
More on Jinja2, Conditionals and Loops
What role does Jinja2 play in Ansible?BeginnerWhat are the three Jinja2 delimiters?BeginnerShow a template with a loop and a conditional, and how it is deployed.BeginnerWhich filters do you use every day?BeginnerHow do you transform lists and dicts with filters (`map`, `select`, `selectattr`, `unique`, `flatten`)?IntermediateHow does `when` work and which operators can you use?Beginner