คอนสแตนตินให้คำตอบที่ดี; นี่คือรสชาติเพิ่มเติมเกี่ยวกับมัน
ฉันมักจะกำหนดรายการเป็นตัวแปรและเพียงเขียนสองวงแยกกันมากกว่าตัวแปรเดียวกัน:
┌─[jamesph@geror] - [~/temp] - [Sat Jan 13, 10:06]
└─[$]> cat loops-1.yml
- hosts: localhost
gather_facts: no
vars:
menu:
- Egg and Spam
- Spam, bacon, sausage and Spam
- Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam
tasks:
- debug:
msg: "We have {{ item }}"
with_items: "{{ menu }}"
- debug:
msg: "I love {{ item }}!"
with_items: "{{ menu }}"
┌─[jamesph@geror] - [~/temp] - [Sat Jan 13, 10:06]
└─[$]> ansible-playbook loops-1.yml
[WARNING]: Unable to parse /etc/ansible/hosts as an inventory source
[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: Could not match supplied host pattern, ignoring: all
[WARNING]: provided hosts list is empty, only localhost is available
PLAY [localhost] **********************************************************************************************************************
TASK [debug] **************************************************************************************************************************
ok: [localhost] => (item=Egg and Spam) => {
"changed": false,
"item": "Egg and Spam",
"msg": "We have Egg and Spam"
}
ok: [localhost] => (item=Spam, bacon, sausage and Spam) => {
"changed": false,
"item": "Spam, bacon, sausage and Spam",
"msg": "We have Spam, bacon, sausage and Spam"
}
ok: [localhost] => (item=Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam) => {
"changed": false,
"item": "Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam",
"msg": "We have Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam"
}
TASK [debug] **************************************************************************************************************************
ok: [localhost] => (item=Egg and Spam) => {
"changed": false,
"item": "Egg and Spam",
"msg": "I love Egg and Spam!"
}
ok: [localhost] => (item=Spam, bacon, sausage and Spam) => {
"changed": false,
"item": "Spam, bacon, sausage and Spam",
"msg": "I love Spam, bacon, sausage and Spam!"
}
ok: [localhost] => (item=Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam) => {
"changed": false,
"item": "Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam",
"msg": "I love Spam, Spam, Spam, Spam, Spam, Spam, baked beans, Spam, Spam, Spam and Spam!"
}
PLAY RECAP ****************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0
สิ่งนี้ทำงานได้ดีกับตัวแปรที่มีความสำคัญเช่นโดยกำหนดชุดเซิร์ฟเวอร์ที่แตกต่างกันต่อสภาพแวดล้อม นอกจากนี้ยังใช้งานได้เมื่อคุณจำเป็นต้องทำงานอื่น ๆ ที่ไม่ใช่ลูปอื่น ๆ ระหว่างสองลูป
loop
ในblock
บล็อก ที่ดูเหมือนว่าจะได้รับการร้องขอ แต่ปฏิเสธผ่านเบิ้ล GH ปัญหา 13262:-(