Ansible:应用于何时完成循环 [英] Ansible: apply when to complete loop

查看:67
本文介绍了Ansible:应用于何时完成循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将ansible中的循环与应用了when语句的循环结合起来.但是,何时将语句应用于每个循环迭代,这消除了将一个语句应用于完整循环的可能性.有人知道该怎么做吗?

I want to combine a loop in ansible with a when-statement applied to it. When-statements are applied to each loop iteration however, which takes away the possibility to apply one to the complete loop. Does anyone know how to do this?

我以前曾遇到过这个问题,但是在这种特定情况下,它涉及一个可能存在或可能不存在的变量.我想做的是这样的:

I've run into this problem before, but in this specific case it concerns a variable that might or might not exist. What I would want to do is something like:

- name: Loop
  debug:
    msg: "{{ item }}"
  with_items: x.y|default([])
  but-only-run-this-loop-when: x is defined

默认过滤器处理未定义y的那些实例.因为在我的情况下x可能还没有定义,所以我只需要在运行此循环时运行.显然,这不是一个真实的声明.我应该代替使用什么?

The default-filter takes care of those instances where y is not defined. Since in my case x might als be not defined, I need the but-only-run-this-loop-when. Obviously, this is not a real ansible statement. What should I use in stead?

目前,我使用的是类似以下的东西:

Currently, I use something horrible like:

- name: kludge1
  set_fact:
    fake_y : "{{ [] }}"

- name: kludge2
  set_fact:
    fake_y : "{{ x.y|default([]) }}"
  when: x is defined

- name: Loop
  debug:
    msg: "{{ item }}"
  with_items: '{{ fake_y }}'

例如在host_vars中:

With for example in host_vars:

x:
  y:
    - "foo"
    - "bar"

但是我敢肯定那不是要走的路.

But I'm sure that's not the way to go.

推荐答案

有类似的答案

There's similar answer here. You can use several defaults in a row:

- name: Loop
  debug:
    msg: "{{ item }}"
  with_items: (x | default({})).y | default([])

并且没有办法将when语句绑定到整个循环任务(至少在当前的Ansible 2.2中如此).

And there is no way to bound when statement to looped task as a whole (at least in current Ansible 2.2).

这篇关于Ansible:应用于何时完成循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆