如何在include_tasks或许多任务上执行循环,并且在编写可写剧本时条件是变量

时间:2020-07-14 07:24:23

标签: ansible

我尝试过:

- name: set passed
  set_fact:
      i: 0
- name: test
  include_tasks: test2.yml
  until: i == 3

在test2.yml中:

- name: set i
  set_fact:
    i: '{{ i|int + 1 }}'

但是似乎“直到”不能在include_tasks上使用,只能在单个任务上使用,但是我需要循环一组任务。

然后我尝试了类似的事情:

 - name: test
   include_tasks: test2.yml
   loop: [1,2,3,4]
   when: i != 3

但是似乎“时间”条件仅被验证了一次,因此所有4个循环都运行。

这是解决方案吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

首先,在使您能够用Ansible编写循环之前,请先提个建议。请勿在程序中编写程序。每次尝试对大任务列表使用循环时,都会给剧本带来更微妙的复杂性,这会使您日后受苦。

您要对列表执行的大多数任务可以作为列表上的一系列操作来完成。例如。如果您有foo: [1,2,3,4],并且想要使用这些名称创建目录并将这些名称发送到远程服务器,则最好这样写:

- name: Creating dirs
  file:
    state: directory
    name: '{{ item }}'
  loop: '{{ foo }}'
  when: item != 3

- name: Sending to remote
  uri:
    url: 'http://example.com/{{ item }}'
  loop: '{{ foo }}'
  when: item != 3

此代码可以维护,并且相对容易调试。现在,我们要做的事情包括:

tasklist.yaml:

 - file:
     state: directory
     name: '{{ item }}'
 - uri:
     url: 'http://example.com/{{ item }}'

外部任务列表:

 - include_tasks: tasklist.yaml
   loop: '{{ foo }}'
   when: item != 3

何时在每次运行中进行评估,但您需要在其中放置一些不变的变量,例如item(用于产生循环的魔术变量)。