根据 ansible 中的条件将项目添加到列表中 [英] Add an item to a list dependent on a conditional in ansible

查看:27
本文介绍了根据 ansible 中的条件将项目添加到列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据满足的某些条件将一个项目添加到 ansible 列表中.

I would like to add an item to a list in ansible dependent on some condition being met.

这不起作用:

  some_dictionary:
    app:
       - something
       - something else
       - something conditional # only want this item when some_condition == True
         when: some_condition

我不确定这样做的正确方法.我可以以某种方式创建一个新任务以添加到 some_dictionary 中的 app 值吗?

I am not sure of the correct way to do this. Can I create a new task to add to the app value in the some_dictionary somehow?

推荐答案

我会尽量避免这种情况,但如果条件列表是绝对必要的,你可以使用这个技巧:

I'd try to avoid this, but if conditional list is absolutely necessary, you can use this trick:

---
- hosts: localhost
  gather_facts: no
  vars:
    a: 1
    b: 1
    c: 2
    some_dictionary:
      app: "{{ '[\"something\", \"something else\"' + (a + b == c) | ternary(', \"something conditional\"',' ') + ']' }}"
  tasks:
    - debug: var=some_dictionary.app

它将形成一个类似数组的字符串 (["item1","item2","item3"]) 并且 ansible 变量模板器将在分配给 app<之前将其转换为列表/代码>.

It will form an array-like string (["item1","item2","item3"]) and ansible variable templator will convert it into list before assigning to app.

这篇关于根据 ansible 中的条件将项目添加到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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