Raxso
Raxso

Reputation: 35

ansible hostname replace with three digit IP

How can I replace the hostname with the last three digits of IP address:

Example:

IP: 192.168.0.1
Hostname: webserver001

I want my hostname to be replace based on the last three digits of the IP address but what I get is webserver1 instead of webserver001, how can I pad leading zeros.

below is the code I use.

- hostname: name={{ hostname.replace('*', ansible_all_ipv4_addresses[0].split('.')[3]) }}

Upvotes: 1

Views: 943

Answers (1)

damienfrancois
damienfrancois

Reputation: 59110

I think what you want is

name={{ "webserver%03d"|format(ansible_default_ipv4.address.split(".")[3]|int) }}

using the format filter, along with the int filter, allows padding numbers with zeros.

Exemple with test.yml:

- hosts: localhost
  tasks:
    - name: test jinja capabilities
      debug: msg={{ "webserver%03d"|format(ansible_default_ipv4.address.split(".")[2]|int) }}

When run, it gives

$ ansible-playbook -i localhost, test.yml    

PLAY     ***************************************************************************

TASK [setup]     *******************************************************************
ok: [localhost]

TASK [test jinja capabilities] *************************************************
ok: [localhost] => {
    "msg": "webserver001"
}

PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=0    unreachable=0        failed=0

for localhost having IP 127.0.0.1.

Upvotes: 1

Related Questions