Ansible: count the elements and use in conditional check

Viewed 115

I have a playbook, which I use for key: value definitions, like this:

x_interfaces:
  - eno1
  - eno2

And in another playbook (which includes that one, I would like to make a conditional check, like this:

- name: debug message
  debug:
    msg: There is more then 1 interface in the machine
  when: x_interfaces|length > '1'

But it does not work. I get this error message:

The error was: Unexpected templating type error occurred on ({% if x_interfaces|length > '1' %} True {% else %} False {% endif %}): '>' not supported between instances of 'int' and 'str'

What am I doing wrong? If I use x_interfaces|int > '1' it will also fails.

1 Answers

length returns a integer. '1' is a string. As the error message states the greater then comparison can't perform an operation between a string and an integer.

For this to work you simply need to change '1' to 1. You are now comparing an integer to an integer.

- name: debug message
  debug:
   msg: There is more then 1 interface in the machine
  when: x_interfaces|length > 1
Related