1

I am calling ansible playbook from shell and in shell before calling playing book i am sourcing environment variables from file

config.ini:

IPC_IP=1.1.1.1

execute_playbook.sh

#!/bin/bash
set -o errexit
source /tmp/config.ini
ansible-playbook  myplaybook.yaml

myplaybook.yaml

---
- hosts: "localhost"
  become: yes
  gather_facts: yes

  tasks:
    - name: Add Entry to /etc/hosts
      become: yes
      lineinfile:
        dest: /etc/hosts
        line: "{{ lookup('env','IPC_IP') }}\t\t{{ lookup('env','HOSTNAME') }}"
        state: present

Now i can get value of HOSTNAME but not able to get IPC_IP value which i am sourcing from file.

3
  • i would try exporting the variable, in config.ini: export IPC_IP=1.1.1.1 Commented Nov 17, 2020 at 17:44
  • I have 10 variables in file Commented Nov 17, 2020 at 17:44
  • Then you need to export them all. Commented Nov 17, 2020 at 17:46

1 Answer 1

2

After the source command, IPC_IP is a shell variable, but it is not an environment variable. You need to export it first.

source /tmp/config.ini
export IPC_IP
ansible-playbook myplaybook.yaml

Note that export applies to names, so you can call export before source as well; once a name is exported, its value can be changed any number of times; the value seen by the child process is the value of the variable at the time the child process begins.

If there are many variables defined in config.ini to export, you can temporarily set an option to automatically export any variable that is created or changed while the option is set. For example,

set -a
source /tmp/config.ini
set +a
ansible-playbook myplaybook.yaml

Finally, be aware that an INI-style file isn't necessarily a shell script, and simply sourcing it may not produce the result you expect.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the shell vs env var concept, this was driving me crazy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.