sorin
sorin

Reputation: 170508

How to make Ansible Jinja2 lookup loop a list?

In Ansible, I am trying to get the first defined value from a list of environment variables: BUILD_USER_EMAIL, GERRIT_CHANGE_OWNER_EMAIL, GERRIT_EVENT_ACCOUNT_EMAIL, GERRIT_PATCHSET_UPLOADER_EMAIL

The code for getting one looks like

- email: "{{ lookup('env', 'BUILD_USER_EMAIL')}}"

When the variable is not defined this this resolves to empty string which is ok.

Now the question is how to do implement this as loop of fallbacks so I would try to find the first defined value.

Upvotes: 0

Views: 1593

Answers (2)

techraf
techraf

Reputation: 68509

An answer improved based on OP’s own research.

tasks:
  - debug:
      msg: "{{ envcandidates | reject('equalto', '') | first }}"
    vars:
      envcandidates: “{{ lookup('env', 'BUILD_USER_EMAIL', 'GERRIT_CHANGE_OWNER_EMAIL', 'GERRIT_EVENT_ACCOUNT_EMAIL', 'GERRIT_EVENT_ACCOUNT_EMAIL', wantlist=True) }}”

You might want to add | default filter if you don't want it to fail if neither of the variables were set, or just add a default value to the end of envcandidates list.

Upvotes: 2

zigarn
zigarn

Reputation: 11595

I can see this as a solution:

- email: "{{ lookup('env', 'BUILD_USER_EMAIL') |
             default(lookup('env', 'GERRIT_CHANGE_OWNER_EMAIL'), True) |
             default(lookup('env', 'GERRIT_EVENT_ACCOUNT_EMAIL'), True) |
             default(lookup('env', 'GERRIT_PATCHSET_UPLOADER_EMAIL'), True) |
             default('UNDEFINED', True) }}"

The True are here to force jinja2 to evaluate empty string as None.

Upvotes: 1

Related Questions