首页 > 解决方案 > Add zero if the number of digits is less than three

问题描述

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?

标签: ansible

解决方案


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.


推荐阅读