with_items: expects a list or a set by using it with when:

I have the following two statements which have the same when part. The first one is skipped correctly but the second creates an error. It should be skipped also.

`

  • debug: var=“{{ sites[env].restricted_areas }}”
    when: sites[env].restricted_areas is defined

  • template: src=“apache/site_credentials” dest=“{{ apache_vhost_base_path }}/{{ sites[env].server_name }}/conf/{{ item.area.internal_name }}”
    with_items: sites[env].restricted_areas | list
    when: sites[env].restricted_areas is defined
    tags: create

`

result:

`
TASK: [website | debug var=“{{sites[env].restricted_areas}}”] *****************
skipping: [TSSDMZPORTAL002]

TASK: [website | template src=“apache/site_credentials” dest=“{{apache_vhost_base_path}}/{{sites[env].server_name}}/conf/{{item.area.internal_name}}”] ***
fatal: [TSSDMZPORTAL002] => with_items expects a list or a set
`

can someone help me?

The when is evaluated for each step in the loop, not before looping, which is the source of confusion here.

I’m having the same issue. How can we make this task check if the variable exists before looping ? If we can’t use when here, what can we do ?

you could put the tasks in a different yml file and do a conditional include based on your “when”.

first no moustaches in var, it just wants a variable name

- debug: var=sites[env].restricted_areas

you are putting several variables that can be undefined in your when
statement so to be safe you should check each step:

when: env is defined and env in sites and 'restricted_areas' in sites[env]

Now you can split them up and check each step to make sure what you
expect to be defined is there

Markus,

That’s exactly what I ended up doing. Thanks for your help.