运行可执行任务的循环列表



我有一个别人写的任务。它的目标是使用单个变量进行一次性使用。我希望避免用列表而不是简单的变量来重写它。

然后我想在host_vars:中为每个主机设置一个列表

list:
- value_1
- ...
- value_n

在剧本中,为每个值重用任务:

loop the list, and for each value:
reset the main variable used in task with the value_n
run the task

有可能吗
这在shell中很基本,但在Ansible中似乎很复杂。

好吧——我知道你在这方面是新手,但你应该发布你尝试过的代码,并发布你得到的错误。无论如何,这里有一个在localhost上运行的简单循环示例(如果localhost不在您的库存中,您可能需要使用不同的主机(:

---
- hosts: localhost
connection: local
gather_facts: no
vars:
list:
- value_1
- value_2
- value_n
tasks:
- name: Loop with default variable (item)
debug:
msg: "item is {{ item }}"
loop: "{{ list }}"

- name: Loop with named variable (main_variable)
debug:
msg: "main_variable is {{ main_variable }}"
loop: "{{ list }}"
loop_control:
loop_var: main_variable

以下是ansible-playbook ./simple_loop.yml:的结果

$ ansible-playbook ./simple_loop.yml 
PLAY [localhost] *******************************************************************************
TASK [Loop with default variable (item)] *******************************************************
ok: [localhost] => (item=value_1) => {
"msg": "item is value_1"
}
ok: [localhost] => (item=value_2) => {
"msg": "item is value_2"
}
ok: [localhost] => (item=value_n) => {
"msg": "item is value_n"
}
TASK [Loop with named variable (main_variable)] ************************************************
ok: [localhost] => (item=value_1) => {
"msg": "main_variable is value_1"
}
ok: [localhost] => (item=value_2) => {
"msg": "main_variable is value_2"
}
ok: [localhost] => (item=value_n) => {
"msg": "main_variable is value_n"
}
PLAY RECAP *************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

相关内容

  • 没有找到相关文章

最新更新