Venu S
Venu S

Reputation: 3691

Ansible conditional omit filter with looped items

I am passing these values to module parameter docker_container

    volumes:
     - "/opt/projects/logs/{{ Appname }}-{{ item }}:/logs"
     - "/opt/projects/config/{{ Appname }}-{{ item }}/config:/config"

...
..
.

     with_items: "{{ exposedPorts }}"

However, second volume binding is conditional on when: push_config | default(false) | bool

Looking for something like :"/opt/projects/config/{{ Appname }}-{{ item }}/config:/config ---> when push_config is true else default(omit)" I am struggling to handle | default(omit) when there are looped items involved.

I tried below, but its not adding the volume mount and throwing an error, even when push_config is passed as true.

  volumes:
     - "/apps/projects/logs/{{ Appname }}-{{ item }}:/logs"
     - "{{ if  'push_config | default(false) | bool'  '/apps/projects/logs/{{ Appname }}-{{ item }}/.configmap:/tibco/config' else default(omit)  }}"


"msg": "The task includes an option with an undefined variable. The error was: 'item' is undefined

Upvotes: 2

Views: 2296

Answers (1)

Zeitounator
Zeitounator

Reputation: 44615

omit is a placeholder to totally skip an entire module parameter definition.

A typical usage in your case would be:

volumes: "{{ my_volume_list | default(omit) }}"

It cannot be used to replace an empty element of a list like you are trying to do above. You need to calculate the list of volumes for each items ans pass that as a parameter. Try something like the following (not tested, just to put you on track):

- name: Create my container
  vars:
    default_mount: ["/opt/projects/logs/{{ Appname }}-{{ item }}:/logs"]
    additional_mount_def: "/opt/projects/config/{{ Appname }}-{{ item }}/config:/config"
    additional_mount: >-
      {{ push_config | default(false) | bool | ternary ([additional_mount_def], []) }}
    all_mount: "{{ default_mount + additional_mount }}"
  docker_container:
    #....#
    volumes: "{{ all_mount }}"
  with_items: "{{ exposedPorts }}"

Upvotes: 2

Related Questions