我的以下游戏按预期正常工作:
- name: Identify next available hostname
ansible.builtin.set_fact:
NEXT_HOSTNAME: "{{ HOSTNAME_CONVENTION }}{{ '{:02d}'.format(item) }}"
loop: "{{ range(1, 99) | reverse | list }}"
when: "'host-name{:02d}'.format(item) not in EXISTING_HOSTNAMES
其中 EXISTING_HOSTNAMES 是已分配的非连续主机名列表,并且 HOSTNAME_CONVENTION 设置为“主机名”。
我的目标是用 HOSTNAME_CONVENTION 变量替换 when 语句中的“主机名”文本,其方式类似于构建“NEXT_HOSTNAME”变量值的方式。
将“when”行替换为
when: "'HOSTNAME_CONVENTION{:02d}'.format(item) not in EXISTING_HOSTNAMES
允许游戏运行,但它无法正确评估,因为我希望它跳过主机名01、主机名02和主机名04,因为它们已经被分配,而静态“主机名”文本在当 line 时,它确实正确地跳过了 host-name01、host-name02 和 host-name04。
将“when”行替换为
when: "HOSTNAME_CONVENTION'{:02d}'.format(item) not in EXISTING_HOSTNAMES
完全失败,“模板化字符串时出现模板错误:预期标记‘语句块结束’,得到‘字符串’”
声明主机约定、开始、停止、格式和索引
hc: host-name
start: 1
stop: '20'
frmt: "%0{{ stop|length }}d"
index: |
{% for i in range(start, stop|int) %}
{{ frmt|format(i) }} {% endfor %}
给予
frmt: '%02d'
index: |-
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19
创建所有主机名
hn: "{{ [hc] | product(index|split) | map('join') }}"
给予
hn:
- host-name01
- host-name02
- host-name03
- host-name04
- host-name05
- host-name06
- host-name07
- host-name08
- host-name09
- host-name10
- host-name11
- host-name12
- host-name13
- host-name14
- host-name15
- host-name16
- host-name17
- host-name18
- host-name19
给定现有主机名的列表。例如,
existing_hostnames: [host-name01, host-name02, host-name04]
从所有主机名列表中删除它们
result: "{{ hn | difference(existing_hostnames) | sort }}"
提供您可能想要的
result:
- host-name03
- host-name05
- host-name06
- host-name07
- host-name08
- host-name09
- host-name10
- host-name11
- host-name12
- host-name13
- host-name14
- host-name15
- host-name16
- host-name17
- host-name18
- host-name19
用于测试的完整剧本示例
- hosts: all
vars:
hc: host-name
start: 1
stop: '20'
frmt: "%0{{ stop|length }}d"
index: |
{% for i in range(start, stop|int) %}
{{ frmt|format(i) }} {% endfor %}
hn: "{{ [hc] | product(index|split) | map('join') }}"
existing_hostnames: [host-name01, host-name02, host-name04]
result: "{{ hn | difference(existing_hostnames) | sort }}"
tasks:
- debug:
var: hc
- debug:
var: frmt
- debug:
var: index
- debug:
var: hn
- debug:
var: result