Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible environment variable or default

Tags:

ansible

jinja2

How do I get a value from an environment variable, but use a default if the environment variable is unset?

This is an example that does not work

---
- name: a playbook
  hosts: all
  vars:
    build_dir: "{{ lookup('env','BUILD_DIR') | default('builds/1.0.0/LATEST') }}"
  tasks:
    - debug: msg="{{ build_dir }}"

Running this playbook returns an empty string instead of the default.

$ ansible-playbook build.yml

TASK [debug] ********************
ok: [amber] => {
    "msg": ""
}

However, it works as expected to obtain the environment variable.

$ BUILD_DIR=LOL ansible-playbook build.yml

TASK [debug] ****************
ok: [amber] => {
    "msg": "LOL"
}
like image 403
activedecay Avatar asked Jun 13 '18 14:06

activedecay


1 Answers

Discovered this that is more concise and easier to read than some other options I have seen

"{{ lookup('env','BUILD_DIR') or 'builds/1.0.0/LATEST' }}"
like image 187
Corey Avatar answered Sep 30 '22 18:09

Corey