Search code examples
ansibleip-address

ansible - add 1 to ip address variable using ipmath


This seems like it should be fairly straightforward. I have a variable I defined in default.yml that I'd like to increment by one:

start_ip: 10.10.10.10

Then I set the fact and report it:

- set_fact:
    repo_ip:  "{{ start_ip|ipmath(1) }}"

- debug:
   msg: "repo_ip is {{ repo_ip }}"

I've also tried:

 - set_fact:
       repo_ip:  "{{ start_ip }}|ipmath(1)"

with the same result:

repo_ip is 10.10.10.10|ipmath(1)

Of course what I want is 10.10.10.11. What am I doing incorrectly?


Solution

  • Actually, it should work as written in your first example. The second one is wrong, obviously, as the filter only works if inside the curly braces.

        - hosts: localhost
      gather_facts: false
      connection: local
      vars:
        start_ip: 10.10.10.10
    
      tasks:
        - set_fact:
            next_ip: "{{ start_ip|ipmath(1) }}"
        - debug:
            msg: "Next ip of {{ start_ip }} is: {{ next_ip }}"
    

    This returns what you wanted.

    PLAY [localhost] ***************************************************************
    
    TASK [set_fact] ****************************************************************
    ok: [localhost]
    
    TASK [debug] *******************************************************************
    ok: [localhost] => {
        "msg": "Next ip of 10.10.10.10 is: 10.10.10.11"
    }