AnsiblePilot — Ansible Automation Platform and Enterprise Ansible

AnsiblePilot covers Red Hat Ansible Automation Platform (AAP) and enterprise Ansible: install and upgrade paths, Event-Driven Ansible, security and day-2 operations, plus Luca Berton's books, videos and training.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 9 technical books published by Apress and Leanpub, 4 of them on Ansible, including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible Read Environment Variable: lookup('env') Plugin Guide

By Luca Berton · Published 2022-02-18 · Category: installation

How to read environment variables in Ansible with the env lookup plugin. Access PATH, HOME, USER variables in playbooks.

Ansible Read Environment Variable: lookup('env') Plugin Guide

How to read an environment variable on Ansible Controller with Ansible?

See also: Create Custom Ansible Modules: Python Module Development Guide

Ansible read an environment variable

  • ansible.builtin.env
  • Read the value of environment variables
Let's deep dive into the Ansible lookup plugin env. Plugins are a way to expand the Ansible functionality. With lookup plugins specifically, you can load variables or templates with information from external sources. The full name is ansible.builtin.env, it's part of ansible-core and is included in all Ansible installations. The purpose of the env lookup plugin is to read the value of environment variables.

Parameters and Return Value

Parameters

  • \_terms string - Environment variable

Return Values

  • \_raw list - Values from the environment variables
The parameters of plugin env.

The only required parameter is the default "\_terms", with the name of the environment variable to read. The normal usage is to assign the lookup plugin to a variable name but you could use it in your Ansible task directly.

## Playbook

Read an environment variable with Ansible Playbook.

code

---
- name: environment Playbook
  hosts: all
  tasks:
    - name: display HOME
      ansible.builtin.debug:
        msg: "{{ lookup('env', 'HOME') }}"

execution

ansible-pilot $ printenv | grep HOME
HOME=/Users/lberton
ansible-pilot $ ansible-playbook -i virtualmachines/demo/inventory ansible\ statements/environment.yml
PLAY [environment Playbook] ***************************************************************************
TASK [Gathering Facts] ****************************************************************************
ok: [demo.example.com]
TASK [display HOME] *******************************************************************************
ok: [demo.example.com] => {
    "msg": "/Users/lberton"
}
PLAY RECAP ****************************************************************************************
demo.example.com           : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible-pilot $

idempotency

ansible-pilot $ printenv | grep HOME
HOME=/Users/lberton
ansible-pilot $ ansible-playbook -i virtualmachines/demo/inventory ansible\ statements/environment.yml
PLAY [environment Playbook] ***************************************************************************
TASK [Gathering Facts] ****************************************************************************
ok: [demo.example.com]
TASK [display HOME] *******************************************************************************
ok: [demo.example.com] => {
    "msg": "/Users/lberton"
}
PLAY RECAP ****************************************************************************************
demo.example.com           : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible-pilot $

See also: Executing Custom Lookup Plugins in the Ansible Automation Platform

Conclusion

Now you know how to read an environment variable with Ansible. You know how to use it based on your use case.

Reading Environment Variables

Basic usage

- name: Show HOME directory
  ansible.builtin.debug:
    msg: "Home is {{ lookup('env', 'HOME') }}"

- name: Show PATH
  ansible.builtin.debug:
    msg: "PATH is {{ lookup('env', 'PATH') }}"

Use in conditionals

- name: Skip in CI environments
  ansible.builtin.debug:
    msg: "Running manual deployment steps"
  when: lookup('env', 'CI') != 'true'

- name: Use CI-specific config
  ansible.builtin.template:
    src: "{{ 'ci' if lookup('env', 'CI') == 'true' else 'prod' }}-config.j2"
    dest: /etc/myapp/config.yml

Default value if not set

- name: Use env with fallback
  ansible.builtin.debug:
    msg: "Region is {{ lookup('env', 'AWS_REGION') | default('us-east-1') }}"

Read multiple environment variables

- name: Show deployment environment
  ansible.builtin.debug:
    msg:
      - "User: {{ lookup('env', 'USER') }}"
      - "Home: {{ lookup('env', 'HOME') }}"
      - "Shell: {{ lookup('env', 'SHELL') }}"
      - "Editor: {{ lookup('env', 'EDITOR') | default('vim') }}"

See also: Creating a Custom Ansible Lookup Plugin in Python for Reading a File

Setting Environment Variables for Tasks

The env lookup reads from the Ansible controller. To set environment variables on remote hosts, use the environment directive:

- name: Run command with custom environment
  ansible.builtin.command: ./deploy.sh
  environment:
    DATABASE_URL: "postgresql://db.example.com/myapp"
    API_KEY: "{{ vault_api_key }}"
    NODE_ENV: production

- name: Set environment for entire play
  hosts: all
  environment:
    http_proxy: http://proxy.example.com:3128
    https_proxy: http://proxy.example.com:3128
  tasks:
    - name: Install package (uses proxy)
      ansible.builtin.apt:
        name: curl
        state: present

env Lookup vs ansible.builtin.setup

MethodReads FromUse Case
lookup('env', 'VAR')Ansible controllerCI/CD vars, local config
ansible_env.VAR (from setup)Remote hostRemote host environment
# Read from remote host
- name: Gather facts (includes environment)
  ansible.builtin.setup:
    gather_subset: env

- name: Show remote PATH
  debug:
    var: ansible_env.PATH

FAQ

Why is my environment variable empty?

The env lookup reads from the controller process environment. If you set a variable in a different shell session, it won't be available. Ensure the variable is exported:

export MY_VAR="value"  # Must use export
ansible-playbook playbook.yml

Can I read .env files?

Not directly. Parse them with a task:

- name: Read .env file
  ansible.builtin.slurp:
    src: "{{ playbook_dir }}/.env"
  register: env_file
  delegate_to: localhost

- name: Parse .env variables
  ansible.builtin.set_fact:
    env_vars: "{{ (env_file.content | b64decode).split('\n') | select('match', '^[A-Z]') | map('split', '=', 1) | items2dict(key_name=0, value_name=1) }}"

Is the env lookup secure?

The lookup runs on the controller, so it's as secure as your controller environment. Avoid logging sensitive env vars — use no_log: true on tasks that display secrets.

Category: installation

Watch the video: Ansible Read Environment Variable: lookup('env') Plugin Guide — Video Tutorial

Browse all Ansible tutorials · AnsiblePilot Home