Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ansible如何在一系列任务上循环?_Ansible_Ansible Playbook - Fatal编程技术网

Ansible如何在一系列任务上循环?

Ansible如何在一系列任务上循环?,ansible,ansible-playbook,Ansible,Ansible Playbook,如何在一系列任务中完成剧本?我希望实现一个轮询循环,在任务成功之前执行任务序列。当它失败时,异常处理程序将尝试修复该条件,然后循环将重复该任务序列 考虑以下虚构的例子: - action: - block: - debug: msg='i execute normally' - command: /bin/foo rescue: - debug: msg='I caught an error' - command

如何在一系列任务中完成剧本?我希望实现一个轮询循环,在任务成功之前执行任务序列。当它失败时,异常处理程序将尝试修复该条件,然后循环将重复该任务序列

考虑以下虚构的例子:

- 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 1.x中,这根本无法实现。它不是那样设计的

Ansible 2.0支持循环包含文件,因此您可以将所有任务放在一个文件中,然后执行以下操作:

- include: test.yml
  with_items:
    - 1
    - 2
    - 3

但是,我不相信您提到的任何其他构造(
注册
直到
重试
延迟
,等等)都能解决这个问题。理论上,其中一些可以应用于include文件中的所有任务,而另一些任务,如
register
,直到
被显式绑定到单个任务。让多个任务尝试注册同一个输出变量是没有意义的。

基于URL的JSON响应,我需要类似的东西。以下是我的尝试:

其思想是递归地包含另一个任务列表yaml文件。如果包含的文件名为
foobar.yml

- task1
- task2
- task3
- include_tasks: foobar.yml
  until: "some condition"

从Ansible 2.5开始,建议将
循环
置于
和_项
之上。此外,由于您不想假定子任务没有任何循环,因此可以使用比“项”更具描述性的名称。下面是一个在循环中使用循环的示例,该循环稍微被截断,但如果您定义了适当的配置,则仍然有效:

# 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 }}"

但是,将until与include循环中设置的其他变量一起使用是有意义的。