user159192121
user159192121

Reputation: 25

Ansible when condition always fails when a dictionary is there but it contains no elements

The problem that I am facing is the following: I have the following lines in my vars:

testparams:
  - { name: 'test' , test_type: 'test' }

What I need to do, from my tasks, is to include a file when this dictionary is defined. This is my code:

- include: test.yml
  when:  testparams is defined

It works when the whole definition of the dictionary is absent. But, when the dictionary definition is there but without any elements inside, this condition fails. I have tried with length, trying to get the type(just run it when it's Dictionary), but everything has failed so far.

Example of defined dictionary without elements:

testparams:

Any ideas?

Upvotes: 0

Views: 3021

Answers (1)

Zeitounator
Zeitounator

Reputation: 44635

The definition of an empty list is done with brackets like in the following example:

testparams: []

And in your case, I would use the following test to have it work in all conditions:

when: testparams | default([]) | length > 0

Be aware that you are still responsible to sanitize your testparams definition as this might break if:

  • you define a list of testparams that does not have the correct values
  • you define testparams as a non empty string (which also has a length > 0).

Upvotes: 1

Related Questions