anji
anji

Reputation: 103

How to set environment variables in ansible playbook

I am trying to set environment variables through ansible playbook to install gnucobol with vbisam. But that variables are not getting set while executing playbook.

 name: Setting variables for CPPFLAGS
 shell: "echo $CPPFLAGS"
 environment:
  CPPFLAGS: -I/opt/vbisam-2.0/include

 name: Setting variables for LDFLAGS
 shell: "echo $LDFLAGS"
 environment:
  LDFLAGS: -L/opt/vbisam-2.0/lib

 name: Setting variables for LD_LIBRARY_PATH
 shell: "echo $LD_LIBRARY_PATH"
 environment:
  LD_LIBRARY_PATH: /opt/vbisam-2.0/lib:${LD_LIBRARY_PATH}

Can some one help me to fix the issue.

Upvotes: 9

Views: 26802

Answers (1)

larsks
larsks

Reputation: 311238

Your environment variables are definitely getting set. Your existing tasks don't contain any attempt to verify this, so let's add one. For example, if we run this playbook:

- hosts: localhost
  tasks:
    -  name: Setting variables for CPPFLAGS
       shell: "echo $CPPFLAGS"
       environment:
         CPPFLAGS: -I/opt/vbisam-2.0/include
       register: cppflags

    - debug:
        var: cppflags.stdout

We see as output:

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

TASK [Gathering Facts] *************************************************************************************************************************
ok: [localhost]

TASK [Setting variables for CPPFLAGS] **********************************************************************************************************
changed: [localhost]

TASK [debug] ***********************************************************************************************************************************
ok: [localhost] => {
    "cppflags.stdout": "-I/opt/vbisam-2.0/include"
}

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

As @techraf hinted in a comment, it's important to understand that setting environment variables using the environment on a task sets them only for that task. That is, if you wanted CPPFLAGS, LDFLAGS, and LD_LIBRARY_PATH all set at the same time, you would need to do something like:

    -  name: Setting variables for CPPFLAGS
       shell: "echo $CPPFLAGS"
       environment:
         CPPFLAGS: -I/opt/vbisam-2.0/include
         LDFLAGS: -L/opt/vbisam-2.0/lib
         LD_LIBRARY_PATH: /opt/vbisam-2.0/include
       register: cppflags

If you need those variables set on multiple tasks, you would need to either apply the same environment keyword to each task, or set environment on the play instead of individual tasks.

Upvotes: 12

Related Questions