2

Is there a way while using templating in ansible to see if a value exists in an array without using a loop to go through the array?

eg.

vars file:

my_data_array: [ "valueA", "valueB", "valueC" ]

template section example:

{% if ("valueA" in my_data_array) %}
<templateinformation>
{% endif %}

I've also tried (both with and without brackets):

{% if ("valueA" in my_data_array) %}

and:

{% if {{ "valueA" in my_data_array }} %}

*(update) and:

{% "valueA" in my_data_array %}

and a couple of others now as well. Most come back with syntax errors. What I am looking for is something similar to PHP's in_array() function, or Python's in command where it returns a boolean if the value is in the array. The ansible jinja2 support seems to include it only if it is a string within a string.

Am I doing something wrong or is this unsupported and I'll have to setup a loop?

dcmbrown
  • 1,049
  • 9
  • 15
  • 6
    If you are going to mark this as duplicate I'd like some clarification on how asking about how asking how to use **in** in jinja2 is a duplicate of using the jinja2 template commands to include other files. – dcmbrown Sep 28 '18 at 21:03
  • I am going to close questions as duplicate according to how it is done on SO. If a question has an answer under another question, it is considered duplicate. And this question is a clear-cut duplicate. That you forgot `if` when writing your "updated" statement does not qualify this question for reopening as it is of no value to other users. – techraf Sep 28 '18 at 21:38
  • 5
    @techraf guys the linked answer marked as duplicated has nothing to do with this question; wrong link? – guido Feb 12 '21 at 11:01
  • i think techraf may have been trying to correct my syntax at the time rather than pointing at an actual duplicate question. That was essentially the main issue with what I was trying above. – dcmbrown Feb 12 '21 at 17:29
  • 1
    Really need it this question answered... – fared Jul 23 '21 at 22:30
  • I concur that this has been marked as a duplicate in error. The linked question does not contain an answer related to checking for the existence of a value in a Jinja array. – Nathan Griffiths Feb 23 '22 at 21:37
  • The duplicate is correct `{% if "valueA" in my_data_array %}` is what should be used in this particular case. – β.εηοιτ.βε Mar 13 '22 at 23:30

0 Answers0