Yashwanth Veeranki
Yashwanth Veeranki

Reputation: 31

Ansible not in condition

I have a variable called var1 which has an output like

[this is an apple, this is a banana, this is a pineapple]

And var2 as

[this is an apple, this is a banana, this is a mango, this is a watermelon, this is a pineapple] 

I want to check if all the values in var1 are there in var2 I am trying to do a when condition and it is not the correct output.

 - name: check condition 
   Shell: "echo all values are there" 
   When: var1 in var2 

Upvotes: 0

Views: 836

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68179

Q: "Check if all items in var1 are also in var2"

A: Use filter difference. For example,

    - debug:
        msg: var1 is a subset of var2
      when: _diff|length == 0
      vars:
        _diff: "{{ var1|difference(var2) }}"

gives

  msg: var1 is a subset of var2

To test the negative case add elements 'x' and 'y' to var1. For example,

    - debug:
        msg: "Items {{ _diff }} of var1 are missing in var2"
      when: _diff|length != 0
      vars:
        var1: [x, y, this is an apple, this is a banana, this is a pineapple]
        _diff: "{{ var1|difference(var2) }}"

gives

  msg: Items ['x', 'y'] of var1 are missing in var2

Upvotes: 1

Related Questions