Check if strings are equals and ternary operator in Ansible

In your example you are applying the ternary filter to the 'true' string. Effectively you are comparing the value of expose_service with the string 'NodePort' and always get false in result.

You need to enclose the equality operator-clause in parentheses:

 - include: deploy_new.yml
   vars:
     service_type: "{{ (expose_service == true) | ternary('NodePort', 'ClusterIP') }}"
   when: service_up|failed

The other other two points addressed in this answer:

  • you use the string 'true' instead of Boolean
  • when directive is on wrong indentation level (you effectively pass the variable called when)

I'll elaborate first point in techraf's answer. Two other points (when identation and 'true' as string instead of boolean true) still stand too.

So, the question was "What am I doing wrong?". Answer is: operator precedence.

In {{ expose_service == 'true' | ternary('NodePort', 'ClusterIP') }}, filter is applied to 'true' first. So, Ansible evaluates:

  • {{ expose_service == ('true' | ternary('NodePort', 'ClusterIP')) }}
  • 'true' | ternary('NodePort', 'ClusterIP') = 'NodePort' because quoted non-empty string is still boolean non-false.

    {{ expose_service == 'NodePort' }}

    which is apparently false.


Solved!

service_type: "{{ 'NodePort' if expose_service == 'true' else 'ClusterIP' }}"

Tags:

Jinja2

Ansible