'Skip a specifc iteration of an Ansible loop given a condition

I'm attempting to skip an Ansible loop iteration when a specific variable is passed onto the playbook.

I have the following with_items: on an ansible task:

...
...

with_items:
        - "item1"
        - "{{ 'item2' if my_env != 'my_env_1' }}" 

I want the playbook to skip that second item completely and do nothing when my_env == 'my_env_1'

The above snippet seemed to make sense to me, however when I run the playbook I get the following error:

fatal: [...]: FAILED! => {"msg": "the inline if-expression on line 1 evaluated to false and no else section was defined."}

My else statement would be wanting the playbook to skip it. Is there any way to specify that?

Thank you.



Solution 1:[1]

Q: "Skip second item in the loop when my_env == 'my_env_1'"

A: For example, use ternary and flatten the list

shell> cat pb.yml
- hosts: localhost
  tasks:
    - debug:
        var: item
      loop: "{{ my_list|flatten }}"
      vars:
        my_list:
          - item1
          - "{{ (my_env == 'my_env_1')|ternary([], 'item2') }}"
          - item3

gives (abridged)

shell> ansible-playbook pb.yml -e my_env=my_env_1

...

TASK [debug] **************************************************
ok: [localhost] => (item=item1) => 
  ansible_loop_var: item
  item: item1
ok: [localhost] => (item=item3) => 
  ansible_loop_var: item
  item: item3
shell> ansible-playbook pb.yml -e my_env=my_env_X

...

TASK [debug] **************************************************
ok: [localhost] => (item=item1) => 
  ansible_loop_var: item
  item: item1
ok: [localhost] => (item=item2) => 
  ansible_loop_var: item
  item: item2
ok: [localhost] => (item=item3) => 
  ansible_loop_var: item
  item: item3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1