简体   繁体   中英

How to define an Ansible playbook environment with passed in environment dictionary

My problem is that I'm unable to set the environment for the entire playbook by passing in a dict to be set as the environment. Is that possible?

For example, here is my sample ansible playbook:

- hosts: localhost
  vars:
    env_vars: "{{ PLAY_ENVS }}"

  environment: "{{ env_vars }}"

  tasks:
    - name: Here is what you passed in
      debug: msg="env_vars == {{ env_vars }}"

    - name: What is FAKE_ENV
      debug: msg="FAKE_ENV == {{ lookup('env', 'FAKE_ENV') }}"

And I'm passing the command:

/bin/ansible-playbook sample_playbook.yml --extra-vars '{PLAY_ENVS: {"FAKE_ENV":"/path/to/fake/destination"}}'

The response I'm getting is the following:

PLAY [localhost] ***************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [Here is what you passed in] **********************************************
ok: [localhost] => {
    "msg": "env_vars == {u'FAKE_ENV': u'/path/to/fake/destination'}"
}

TASK [What is FAKE_ENV] ********************************************************
ok: [localhost] => {
    "msg": "FAKE_ENV == "
}

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

As you can see 'FAKE_ENV' is not being set in the environment. What am I doing wrong?

Lookups in Ansible are executed in a context of parent ansible process.

You should check your environment with a spawned process, like this:

- hosts: localhost
  vars:
    env_vars:
      FAKE_ENV: foobar
  environment: "{{ env_vars }}"
  tasks:
    - name: Test with spawned process
      shell: echo $FAKE_ENV

And get expected result: "stdout": "foobar",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM