Conditional evaluation of lists

I want to install some packages on a server. Additionally, if a certain condition is true, I want to add an extra package to the list of packages to be installed. What I would love is have this:

  • name: install packages
    yum: name={{ item }}
    with_items:
  • package1
  • package2
    {% if condition %}
  • package3
    {% endif %}

Now, I know that ansible doesn’t parse playbooks with the full Jinja engine (though that would be so cool). I could of course achieve this with 2 tasks:

  • name: install packages
    yum: name={{ item }}
    with_items:

  • package1

  • package2

  • name: install packages
    yum: name=package3

when: condition

But my question is: how can I achieve this with just one task?

try:

with_items:
  - p1
  - p2
  - "{{ condition|ternary(p3,'') }}"

or

with_items: "{{ ['p1','p2'] |union(condition|ternary(['p3'],)) }}"

Hi Brian,

with_items:

  • p1
  • p2
  • “{{ condition|ternary(p3,‘’) }}”

This yields an empty list item, and the yum module doesn’t like it.

or

with_items: “{{ [‘p1’,‘p2’] |union(condition|ternary([‘p3’],)) }}”

Using ansible 1.9.0.1, this fails with:

fatal: [10.0.0.63] => an unexpected type error occurred. Error was can only concatenate list (not “bool”) to list