将项目添加到依赖于ansible中的条件的列表

Mik*_*lla 6 ansible

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

这不起作用:

  some_dictionary:
    app:
       - something
       - something else
       - something conditional # only want this item when some_condition == True
         when: some_condition
Run Code Online (Sandbox Code Playgroud)

我不确定执行此操作的正确方法。我可以创建一个新任务以某种方式增加app价值some_dictionary吗?

小智 5

有什么理由必须一次性完成所有事情吗?

如果您指定要添加到单独变量中的附加项,这将非常容易,因为您只需执行 list1 + list2。

---
- hosts: localhost
  gather_facts: False
  connection: local
  vars:
    mylist:
      - one
      - two
    mycondition: False
    myconditionalitem: foo
  tasks:
    - debug:
        msg: "{{ mylist + [myconditionalitem] if mycondition else mylist }}"
Run Code Online (Sandbox Code Playgroud)


Alv*_*ndo 5

您可以使用select()过滤掉所有的falsey值,但请记住之后应用list()过滤器。这对我来说似乎是一种更简单、更易读的方法:

- name: Test
  hosts: localhost
  gather_facts: no
  vars:
      mylist:
        - "{{ (true)  | ternary('a','') }}"
        - "{{ (false) | ternary('b','') }}"
        - "{{ (true)  | ternary('c','') }}"
 
  tasks:
  - debug:
      var: mylist|select|list
Run Code Online (Sandbox Code Playgroud)

结果:

TASK [debug] *****************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "mylist|select()|list": [
        "a", 
        "c"
    ]
}
Run Code Online (Sandbox Code Playgroud)

用你想要的任何测试替换(true)(false)


Kon*_*rov 4

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

---
- 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
Run Code Online (Sandbox Code Playgroud)

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