Dani Major
Dani Major

Reputation: 27

Ansible when conditional is not skipping condition when false and giving error

Here is my ansible tasks within a role

- name: include tcrj01 variables from prefix_lists
  include_vars:
    file: "../collection-data/output/{{ market_input | lower }}tcrj01_prefix_lists.yml"
    name: prefix01
  delegate_to: localhost
  when: '"target1" in market_input or "target2" in market_input'

- name: include dsrj01 variables from prefix_lists
  include_vars:
    file: "../collection-data/output/{{ market_input | lower }}dsrj01_prefix_lists.yml"
    name: prefix01
  delegate_to: localhost
  when: '"target1" not in market_input or "target2" not in market_input'

market_input == "target1"

The error I'm getting is "Could not find or access '../collection-data/output/targetdsrj01_prefix_lists.yml'which is correct because that file does not and should not exist because the target string IS in/equal to the market_input variable. It should be looking for a tcrj file which does exist for that target string and not the dsrj file it is throwing the error about. I can not figure out why the dsrj task is not being skipped. It works for other target strings that but not the one I am currently running. I will provide more details or clarity if needd. Thanks so much!

Upvotes: 0

Views: 1372

Answers (2)

flowerysong
flowerysong

Reputation: 2939

  when: '"target1" not in market_input or "target2" not in market_input'

The second part of this condition is true ("target2" not in "target1"), so the task runs. You want to skip the task when either part is false, so you should be using and, not or.

  when: '"target1" not in market_input and "target2" not in market_input'

Upvotes: 0

seshadri_c
seshadri_c

Reputation: 7340

If you don't need the text in string comparison, and exact match is sufficient -- a better way to write the when conditions would be to actually match string item in list, i.e. market_input in ["target1", "target2"].

Going with this structure, the tasks would look like this:

- name: include tcrj01 variables from prefix_lists
  include_vars:
    file: "../collection-data/output/{{ market_input | lower }}tcrj01_prefix_lists.yml"
    name: prefix01
  delegate_to: localhost
  when: market_input | lower in ["target1", "target2"]

- name: include dsrj01 variables from prefix_lists
  include_vars:
    file: "../collection-data/output/{{ market_input | lower }}dsrj01_prefix_lists.yml"
    name: prefix01
  delegate_to: localhost
  when: market_input | lower not in ["target1", "target2"]

Now, when market_input=target1, the second task include dsrj01 variables... task will be skipped.

Upvotes: 1

Related Questions