Variables based on conditions

is there a way i can include only those variables which are defined in a task.
for example: in below task, i want to include disk_encryption_key only when its passed from the user. else i want to exclude.
basically i know we can include tasks based on the condition, looking for something similar for variables as well.

  • name: google disk configurations
    gcp_compute_disk:
    name: “{{ gcp_compute_disk_name }}”
    description: “{{ gcp_compute_disk_name }}”
    size_gb: “{{ disk_size }}”
    source_image: “{{ source_image }}”
    disk_encryption_key: “{{ disk_encryption_key }}”
    licenses: “{{ licenses }}”
    labels: “{{ labels }}”
    physical_block_size_bytes: “{{ physical_block_size_bytes }}”
    zone: “{{ zone }}”
    project: “{{ gcp_project }}”
    auth_kind: “{{ gcp_cred_kind }}”
    service_account_file: “{{ gcp_cred_file }}”
    scopes:
  • https://www.googleapis.com/auth/compute

state: “{{ gcp_compute_disk_lifecycle_event }}”

register: disk
tags:

  • always
  • gcp_compute_disk_info

Thanks in advance
Yantram

Read about defaulting values - https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#defaulting-undefined-variables
and omit - https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#omitting-parameters

is there a way i can include only those variables which are defined in a task.
for example: in below task, i want to include disk_encryption_key only when its passed from the user. else i want to
exclude.
basically i know we can include tasks based on the condition, looking for something similar for variables as well.

Hello Yantram,

use:

disk_encryption_key: "{{ disk_encryption_key | default(omit) }}"

That will prevent passing disk_encryption_key to the gcp_compute_disk module
when the value of that variable is undefined.

Regards
        Racke

Thanks for pointing me in the right direction. This works.
Also I would have liked to define default values as dictionaries and lists, not sure if we can achieve this in current implementation.
I will investigate this a little further.