Ansible 如何在一系列任务上循环? [英] How can Ansible loop over a sequence of tasks?
问题描述
Ansible 剧本如何循环 一系列任务?我希望实现一个轮询循环,该循环执行任务序列直到任务成功.当它失败时,异常处理程序将尝试修复该条件,然后循环将重复任务序列.
How can an Ansible playbook loop over a sequence of tasks? I wish to implement a polling loop that executes a task sequence until the task is successful. When it fails, an exception handler will attempt to fix the condition and then the loop will repeat the task sequence.
考虑以下假想示例:
- action:
- block:
- debug: msg='i execute normally'
- command: /bin/foo
rescue:
- debug: msg='I caught an error'
- command: /bin/fixfoo
always:
- debug: msg="this always executes"
register: result
until: result
retries: 5
delay: 10
推荐答案
从 Ansible 2.5 开始,推荐 loop
而不是 with_items
.此外,由于您不想假设您的子任务没有任何循环,因此您可以使用比item"更具描述性的名称.这是一个在循环中使用循环的示例,稍微被截断但如果您定义适当的配置仍然可以工作:
As of Ansible 2.5, loop
is recommended over with_items
. Furthermore, since you don't want to assume your sub-task won't have any loops, you can use a more descriptive name than "item". Here's an example which uses a loop within a loop, slightly truncated but still working if you define the appropriate config:
# terminate-instances-main.yml:
---
- hosts: local
connection: local
vars:
regions:
- ap-southeast-1
- us-west-1
tasks:
- include_tasks: "terminate-instance-tasks.yml"
loop: "{{ regions }}"
loop_control:
loop_var: region
# terminate-instance-tasks.yml:
---
- name: Gather EC2 facts
ec2_instance_facts:
region: "{{ region }}"
filters:
"tag:temporary": "true"
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
register: ec2
- name: Terminate Temp EC2 Instance(s)
ec2:
instance_ids: '{{ item.instance_id }}'
state: absent
region: "{{ region }}"
aws_access_key: "{{ aws_access_key }}"
aws_secret_key: "{{ aws_secret_key }}"
loop: "{{ ec2.instances }}"
这篇关于Ansible 如何在一系列任务上循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!