ansible 列表变量、字典变量
ansible的变量不仅可以是单个的值,也可以为列表。
- hosts: localhost
gather_facts: no
vars:
- list: [1,2,3]
tasks:
- name: echo
debug: msg="{{ list }}"
输出为:
TASK [echo] ********************************************************************
ok: [localhost] => {
"msg": [
1,
2,
3
]
}
结合循环
结合循环,这个特性就变得很有用;以参数传递列表给playbook,不用在playbook中固定循环的次数与内容。
- hosts: localhost
gather_facts: no
vars:
- list: [1,2,3]
tasks:
- name: loop
debug: msg="{{ item }}"
with_items: '{{list}}'
输出为:
TASK [loop] ********************************************************************
ok: [localhost] => (item=1) => {
"item": 1,
"msg": 1
}
ok: [localhost] => (item=2) => {
"item": 2,
"msg": 2
}
ok: [localhost] => (item=3) => {
"item": 3,
"msg": 3
}
字典变量
变量也可以为字典:
- hosts: localhost
gather_facts: no
vars:
- lists:
list1: [1,2,3]
list2: [4,5]
tasks:
- name: loop
debug: msg="{{ item }}"
with_items: '{{lists["list1"]}}'
TASK [loop] ********************************************************************
ok: [localhost] => (item=1) => {
"item": 1,
"msg": 1
}
ok: [localhost] => (item=2) => {
"item": 2,
"msg": 2
}
ok: [localhost] => (item=3) => {
"item": 3,
"msg": 3
}