Ansible循环与项提供了一种在任务中循环执行操作的方法。以下是一个包含代码示例的解决方法:
- name: Looping with items
hosts: localhost
gather_facts: false
vars:
fruits:
- apple
- orange
- banana
tasks:
- name: Print each fruit
debug:
msg: "Fruit: {{ item }}"
loop: "{{ fruits }}"
在上述示例中,我们定义了一个名为fruits
的变量,其中包含了三种水果。然后,使用loop
关键字在任务中循环遍历这个变量,每次迭代时将item
变量设为当前的水果。在循环体内部,我们使用debug
模块打印每个水果的信息。
运行以上代码时,输出将会是:
TASK [Print each fruit] **************************************************
ok: [localhost] => (item=apple) => {
"msg": "Fruit: apple"
}
ok: [localhost] => (item=orange) => {
"msg": "Fruit: orange"
}
ok: [localhost] => (item=banana) => {
"msg": "Fruit: banana"
}
通过这个示例,你可以了解到如何使用Ansible的循环与项来轻松地遍历列表,并对每个元素执行操作。你可以根据自己的需求,修改fruits
变量中的内容,以及在循环体内部执行其他操作。