Magnun Leno
Magnun Leno

Reputation: 2738

Environment variables from external file in Ansible

I have a file which contains some environment variables that will be used by Django and I need ansible to access some of those info.

Example env_vars file:

DB_USER='my_db_username'
DB_PASSWORD='my_db_password'

Example playbook.yml:

---
- name: Test playbook
  hosts: localhost
  connection: localhost

  tasks:
        - debug: msg="username {{ lookup('env', 'DB_USER') }} password {{ lookup('env', 'DB_PASSWORD') }}"

When I try calling it with -e option it fails with the following error:

$ ansible-playbook playbook.yml -e @env_vars

ERROR: failed to combine variables, expected dicts but got a 'dict' and a 'str'

I also tried to "source" the env_vars file. But ansible cant see the enviroment variables.

$ . env_vars; ansible-playbook playbook.yml

PLAY [Test playbook] ********************************************************** 

GATHERING FACTS *************************************************************** 
ok: [localhost]

TASK: [debug msg="username  password "] *************************************** 
ok: [localhost] => {
    "msg": "username  password "
}

PLAY RECAP ******************************************************************** 
localhost                  : ok=2    changed=0    unreachable=0    failed=0   

Is there a way to make ansible "see" or "load" those variables set in the file? I've seen many lookup options (ini, yml and others), but none of them load this kind of info.

Upvotes: 1

Views: 5571

Answers (2)

Jesse Quinn
Jesse Quinn

Reputation: 189

Just do the following:

--extra-vars "@env_vars.json" and within the env_vars.json have

{
  "db_user": "xxx",
  "db_password": "xxx"
}

no need to do a lookup.

Upvotes: 1

Hang
Hang

Reputation: 395

Change:

DB_USER='my_db_username'
DB_PASSWORD='my_db_password'

to:

export DB_USER='my_db_username'
export DB_PASSWORD='my_db_password'

Upvotes: 3

Related Questions