一个循环遍历多个 Ansible 任务
One loop over multiple Ansible tasks
我创建了一个 Ansible 剧本,它创建了一个云实例,然后在该实例上安装了一些程序。我想多次 运行 这个剧本(不使用 bash 脚本)。是否可以使用循环将这两个任务一起循环(即两个任务的一个循环?)。到目前为止,我所能找到的只是每个任务的一个循环
不,目前不可能。 with_items
曾经在以前版本的 Ansible 中使用 include
语句,但不幸的是被删除了。
尽管它将在 Ansible 2.0 中恢复,请参阅 What's New in v2 - AnsibleFest London 2015
的幻灯片 14/15
您可以尝试使用 v2 branch from github,该功能应该在那里可用。
您可以使用 1.9.1 做的是将您的任务转移到一个角色中,并在您的剧本中多次引用该角色。
一个更新:
In 2.0 you are able to use with_
loops and task includes (but not playbook includes), this adds the ability to loop over the set of tasks in one shot. There are a couple of things that you need to keep in mind, a included task that has it’s own with_
loop will overwrite the value of the special item variable. So if you want access to both the include’s item and the current task’s item you should use set_fact
to create a alias to the outer one.:
- include_tasks: test.yml
with_items:
- 1
- 2
- 3
in test.yml:
- set_fact: outer_loop="{{item}}"
- debug: msg="outer item={{outer_loop}} inner item={{item}}"
with_items:
- a
- b
- c
来源:Ansible Docs
我设法通过基于条件递归包含相同的 yaml 文件来做到这一点。这是要点:https://gist.github.com/ParagDoke/5ddfc3d5647ce9b0110d1b9790090092。实际上,在您的剧本中,包含一个带有一些变量的文件:
- name: Invoke poller
vars:
some_condition: '"failed" not in response.content and response.json.status=="running"'
include_tasks: status-poller.yml
然后在status-poller.yml
中包含自己:
- include_tasks: includes/status-poller.yml
when: some_condition
我创建了一个 Ansible 剧本,它创建了一个云实例,然后在该实例上安装了一些程序。我想多次 运行 这个剧本(不使用 bash 脚本)。是否可以使用循环将这两个任务一起循环(即两个任务的一个循环?)。到目前为止,我所能找到的只是每个任务的一个循环
不,目前不可能。 with_items
曾经在以前版本的 Ansible 中使用 include
语句,但不幸的是被删除了。
尽管它将在 Ansible 2.0 中恢复,请参阅 What's New in v2 - AnsibleFest London 2015
的幻灯片 14/15您可以尝试使用 v2 branch from github,该功能应该在那里可用。
您可以使用 1.9.1 做的是将您的任务转移到一个角色中,并在您的剧本中多次引用该角色。
一个更新:
In 2.0 you are able to use
with_
loops and task includes (but not playbook includes), this adds the ability to loop over the set of tasks in one shot. There are a couple of things that you need to keep in mind, a included task that has it’s ownwith_
loop will overwrite the value of the special item variable. So if you want access to both the include’s item and the current task’s item you should useset_fact
to create a alias to the outer one.:
- include_tasks: test.yml
with_items:
- 1
- 2
- 3
in test.yml:
- set_fact: outer_loop="{{item}}" - debug: msg="outer item={{outer_loop}} inner item={{item}}"
with_items:
- a
- b
- c
来源:Ansible Docs
我设法通过基于条件递归包含相同的 yaml 文件来做到这一点。这是要点:https://gist.github.com/ParagDoke/5ddfc3d5647ce9b0110d1b9790090092。实际上,在您的剧本中,包含一个带有一些变量的文件:
- name: Invoke poller
vars:
some_condition: '"failed" not in response.content and response.json.status=="running"'
include_tasks: status-poller.yml
然后在status-poller.yml
中包含自己:
- include_tasks: includes/status-poller.yml
when: some_condition