ansible的變量不只能夠是單個的值,也能夠爲列表。shell
- hosts: localhost gather_facts: no vars: - list: [1,2,3] tasks: - name: echo debug: msg="{{ list }}"
輸出爲:oop
TASK [echo] ******************************************************************** ok: [localhost] => { "msg": [ 1, 2, 3 ] }
結合循環,這個特性就變得頗有用;以參數傳遞列表給playbook,不用在playbook中固定循環的次數與內容。debug
- hosts: localhost gather_facts: no vars: - list: [1,2,3] tasks: - name: loop debug: msg="{{ item }}" with_items: '{{list}}'
輸出爲:code
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 }
變量也能夠爲字典:it
- 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 }