ansible主机名替换为三位IP

ansible hostname replace with three digit IP

如何用 IP 地址的最后三位数字替换主机名:

示例:

IP: 192.168.0.1
Hostname: webserver001

我希望根据 IP 地址的最后三位替换我的主机名,但我得到的是 webserver1 而不是 webserver001,如何填充前导零。

下面是我使用的代码。

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

我想你想要的是

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

使用 format 过滤器以及 int 过滤器,允许用零填充数字。

例如test.yml

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

当运行时,给出

$ 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

对于具有 IP 127.0.0.1 的本地主机。