Ruan Bekker's Blog

From a Curious mind to Posts on Github

Environment Variables With Ansible

This is a quick post on how to use environment variables in ansible

Inventory

Our inventory.ini file looks like this:

1
2
[localhost]
localhost

Across Tasks

You can set environment variables across tasks, and let your tasks inherit the variables:

1
2
3
4
5
6
7
8
9
10
11
- hosts: localhost
  vars:
    var_mysecret: secret123

  tasks:
    - name: echo my env var
      environment:
        MYNAME: ""
      shell: "echo hello $MYNAME > /tmp/bla.txt"
      args:
        creates: /tmp/bla.txt

When we run the task:

1
$ ansible-playbook -i inventory.ini -u ruan task.yml

Check the output:

1
2
$ cat /tmp/bla.txt
hello secret123

Environment Variables Per Task

You can set environment variables per task:

1
2
3
4
5
6
7
8
- hosts: dev
  tasks:
    - name: echo my env var
      environment:
        MYNAME: "RUAN"
      shell: "echo hello $MYNAME > /tmp/bla2.txt"
      args:
        creates: /tmp/bla2.txt

Running the task:

1
$ ansible-playbook -i inventory.ini -u ruan task.yml

Checking the output:

1
2
$ cat /tmp/bla2.txt
hello RUAN

Read More

Read more on environment variables in ansible in their documentation

-->

Comments