Add zero if the number of digits is less than three

Viewed 82

I have baremetal servers where I want to set a specific port for the serial console via proxying, and I decided to make the port from the last octet of the ip, but sometimes the servers have two digits in the last octet, and in such a situation I want zero added for them.

Example:

---
- name: Test
  hosts: test
  gather_facts: no
  tasks:
    - name: IPV4 address lookup for node
      set_fact:
        ip: "{{ lookup('community.general.dig', '{{ inventory_hostname }}-ipmi.mydomain.com') }}"
      delegate_to: localhost
    - name: Set port for serial console
      debug:
        msg: "Console port will set 48{{ ip.split('.')[3] }}"

Output:

TASK [IPV4 address lookup for node] ************************************************************************************************************************************************************************
ok: [hostA] => {
    "ansible_facts": {
        "ip": "10.100.100.25"
    },
    "changed": false
}
ok: [hostB] => {
    "ansible_facts": {
        "ip": "10.101.100.203"
    },
    "changed": false
}

TASK [Set port for serial console] *************************************************************************************************************************************************************************
ok: [hostA] => {
    "msg": "Console port will set 4825"
}
ok: [hostB] => {
    "msg": "Console port will set 48203"
}

The problem is that I also need to set the port after 48K for hostA. Can this be done with Ansible?

2 Answers

You can use a jinja if/else loop to set the value according to your desired logic. You will notice in one case we prefix the IP part with "48", while in the other with "480":

using a set_fact task to calculate the port value:

  - name: set the port with set_fact
    set_fact:
       console_port: "{% if ip.split('.')[3] | length == 3 %}48{{ ip.split('.')[3] }}{% elif ip.split('.')[3] | length == 2 %}480{{ ip.split('.')[3] }}{% endif %}"

Please note the current logic works only for 2 or 3 digits length, as you described it.

Use format. Fro example, the playbook

- hosts: localhost
  vars:
    ip:
      - 10.100.100.2
      - 10.100.100.25
      - 10.101.100.203
    prefix: 48
  tasks:
    - debug:
        msg: "{{ item }}:{{ prefix }}{{ console_port }}"
      loop: "{{ ip }}"
      vars:
        console_port: "{{ '%03d'|format(item.split('.')|last|int) }}"

gives (abridged)

  msg: 10.100.100.2:48002
  msg: 10.100.100.25:48025
  msg: 10.101.100.203:48203
Related