André Fernandes
André Fernandes

Reputation: 2585

Generate list of IP addresses from start and end values with Ansible

Is there a way to generate a list of IP addresses between two arbitrary IPs (not from a subnet/range) with Ansible (v2.9)?

I've searched and the ipaddr filter looks like a good candidate, but from the documentation I couldn't figure out if it supports this.

I'm looking for a solution that allows me to get a list like

[ '10.0.0.123', '10.0.0.124', ... , '10.0.1.23' ]

from a task like

- name: generate IP list
  set_fact:
    ip_list: "{{ '10.0.0.123' | ipaddr_something('10.0.1.23') }}"

Upvotes: 0

Views: 801

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 67984

Create a filter plugin. For example

shell> cat filter_plugins/netaddr.py
import netaddr

def netaddr_iter_iprange(ip_start, ip_end):
    return [str(ip) for ip in netaddr.iter_iprange(ip_start, ip_end)]

class FilterModule(object):
        ''' Ansible filters. Interface to netaddr methods.
            https://pypi.org/project/netaddr/
        '''

        def filters(self):
            return {
                'netaddr_iter_iprange' : netaddr_iter_iprange,
                }

Then, the task below shall create the list

    - set_fact:
        ip_list: "{{ '10.0.0.123'|netaddr_iter_iprange('10.0.1.23') }}"

Upvotes: 1

Related Questions