Search code examples
templatesansiblejinja2

Ansible Jinja templating check if multiple values are undefined before using default(omit)


I have this block

url_username: "{{ download.username | default(omit) }}"

I want to say if download.username is not defined, see if offline_download is defined. If both are not defined then use default(omit). Something like

url_username: "{{ download.username | offline_download | default(omit) }}"

Obviously my syntax above is wrong while pipe'ing. So what is the right way to do?

Basically check if multiple values are defined before doing the default(omit)


Solution

  • You can use default recursively

    url_username: "{{ username | d(offline | d(omit)) }}"
    

    Example of a complete playbook for testing

    shell> cat pb.yml
    - hosts: localhost
    
      vars:
    
        url_username: "{{ username | d(offline | d(omit)) }}"
    
      tasks:
    
        - debug:
            var: url_username
    

    gives (abridged)

    shell> ansible-playbook -e username=value_of_username pb.yml
    
      url_username: value_of_username
    
    shell> ansible-playbook -e offline=value_of_offline pb.yml
    
      url_username: value_of_offline
    
    shell> ansible-playbook pb.yml
    
      url_username: __omit_place_holder__eb8bf53eb654413fef765058f68f455d9e0a191e