我的目的是生成一个包含从 1 到 22 的数字的列表,为此我在下面编写了 Ansible 脚本。
- hosts: localhost
gather_facts: no
tasks:
- name: Generate sequance
set_fact:
mysequence: "{{ item | list }}"
with_sequence: start=1 end=22
- debug: var=mysequence
当我运行代码时我得到了这个奇怪的结果
$ ansible-playbook test.yml
PLAY [localhost] **************************************************************************************************************************
TASK [Generate sequance] ******************************************************************************************************************
ok: [localhost] => (item=1)
ok: [localhost] => (item=2)
ok: [localhost] => (item=3)
ok: [localhost] => (item=4)
ok: [localhost] => (item=5)
ok: [localhost] => (item=6)
ok: [localhost] => (item=7)
ok: [localhost] => (item=8)
ok: [localhost] => (item=9)
ok: [localhost] => (item=10)
ok: [localhost] => (item=11)
ok: [localhost] => (item=12)
ok: [localhost] => (item=13)
ok: [localhost] => (item=14)
ok: [localhost] => (item=15)
ok: [localhost] => (item=16)
ok: [localhost] => (item=17)
ok: [localhost] => (item=18)
ok: [localhost] => (item=19)
ok: [localhost] => (item=20)
ok: [localhost] => (item=21)
ok: [localhost] => (item=22)
TASK [debug] ******************************************************************************************************************************
ok: [localhost] => {
"mysequence": [
"2",
"2"
]
}
PLAY RECAP ********************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
我正在使用最新版本的 Ansible。任何帮助都非常感谢!
我需要此列表来完成另一项任务。以下是片段:
- name: Reboot 22 VMs
vmware_guest:
validate_certs: false
hostname: x.x.x.x
username: [email protected]
password: PASSS
datacenter: DC1
folder: "DC1/vm/Pod-{{item[1]}}"
name: "{{item[0]}}-Pod-{{item[1]}}"
state: restarted
delegate_to: localhost
with_nested:
- "{{myVarList}}"
- [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]
答案1
没有什么是诡异的在您的结果中:您设置了mysequence
22 次,前 21 次迭代的值被覆盖,最后一个值是一个22
转换为带过滤器的列表的字符串list
。结果您得到了包含2
和的双元素列表2
。
您希望任务看起来像这样:
- name: Generate sequance
set_fact:
mysequence: "{{ mysequence | default([]) + [item | int] }}"
with_sequence: start=1 end=22
但您真正想要的是一种在 Jinja2 模板中生成整数列表的方法:
- set_fact:
mysequence: "{{ range(1, 22 + 1) | list }}"