Search code examples
pythonansiblejinja2ansible-inventory

Increment MAC address in ansible


I have a mac address with me. Let's suppose

00:ae:cd:09:db:4f

I need to create a loop in which each time this mac address is incremented by value 1. Let's say the loop will be iterated 2 times.

Expected output:

00:ae:cd:09:db:50
00:ae:cd:09:db:51

I need to create a list of the output.

I tried ipmath(1), tried converting to different format using hwdaddr() and other lib. But did not got any luck. Please help !!


Solution

  • Use with_sequence. For example,

    - hosts: localhost
    
      vars:
    
        mac: 00:ae:cd:09:db:4f
        count: 2
        macs: []
    
      tasks:
    
        - set_fact:
            macs: "{{ macs + [new|join(':')] }}"
          with_sequence: count="{{ count }}"
          vars:
            arr: "{{ mac.split(':') }}"
            ar5: "{{ '%02x' % (arr.5|int(base=16) + item|int) }}"
            new: "{{ arr[:5] + [ar5] }}"
    
        - debug:
            var: macs
    

    gives (abridged)

      macs:
      - 00:ae:cd:09:db:50
      - 00:ae:cd:09:db:51