Using environment vars for variables

I thought

  • name: Clone repo
    git: repo=“{{ git_repo }}”
    dest=“{{ git_dest }}”
    version=“{{ git_version | lookup(‘env’,‘git_version’) | default(‘master’) }}”
    notify: reload apache

would work to use the git_version group_var, ENV if it was set and master otherwise.

I think I was thinking of | as or rather than a filter when I first wrote it but still can’t figure out how to do what I want, weirdly the error is

stderr: fatal: ‘{{git_repo}}’ does not appear to be a git repository

so I think the whole Jinja templating fails.

If I do
lookup(‘env’,‘git_version’) | default(‘master’)

It gets ‘’ if the env var is not set, rather then taking the default as I hoped

Thanks,
Tom

this is not a valid construct, lookup is not a filter.

Thanks. Feels like what I want to achieve should be possible: fetch from group_vars, override with ENV (for rollback perhaps), default to a branch. I could do it easily in python but we have jinja and yaml

Tom

version=“{{ ( lookup(‘env’,‘git_version’)|default(git_version)) | default(‘master’) }}”

That does not work,
msg: Could not determine remote revision for
(presumably the lookup returns the empty string?)

I dont have git_version set in my group_var's

Tom

Think that's the case as
lookup('env','git_version') | default('master')
has the same error.

I have a workaround, I can do
--extra-vars "git_version=HEAD~1"
to rollback

Tom

I just wanted to add a note that

lookup(‘env’, ‘ENV_VAR’) | default(‘foo’)

returns an empty string if ENV_VAR is not defined in the environment, but if you use

lookup(‘env’, ‘ENV_VAR’) | default(‘foo’, True)

then if ENV_VAR is not defined (in which case the env lookup plugin returns an empty string), the second parameter to the default filter tells it to treat any falsy value as undefined.