Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pythoninthegrass/2ffc20e15fef78c412420baf815cd2e8 to your computer and use it in GitHub Desktop.
Save pythoninthegrass/2ffc20e15fef78c412420baf815cd2e8 to your computer and use it in GitHub Desktop.
Loading variables from .env files in Ansible

Loading variables from .env files in Ansible

Ansible has various ways of looking up data from outside sources, including plain text password files, CSV files and INI files. But it doesn't seem to have a lookup for .env files, as used in Laravel projects, also available for PHP, Ruby, Node.js, Python and others.

One option is to launch Ansible with the Ruby dotenv command line script... But that requires Ruby, which seems like overkill to me.

So here is a simpler solution that I use. It consists of:

  1. The .env file itself
  2. A small shell script that loads the .env file into environment variables -
  3. The playbook, which reads from the environment variables into Ansible variables


  • Set ENV_FILE location within working directory (e.g., ENV_FILE="$(dirname "$0")/caddy/.env"
  • Set script to be executable chmod +x
  • Run script with arguments
    ./ caddy/caddy.yml --tags qa -vvv
SUDO_PASSWORD='correct battery horse staple'
# etc.
#!/usr/bin/env bash
ENV_FILE="$(dirname "$0")/.env"
set -o nounset -o pipefail -o errexit
# load all variables from .env and export them all for ansible to read
set -o allexport
source "$ENV_FILE"
set +o allexport
# run ansible w/args
exec ansible-playbook "$@"
- hosts: all
become: true # Need sudo for most tasks
# These variables are needed to bootstrap Ansible
ansible_sudo_password: '{{ lookup("env", "SUDO_PASSWORD") }}'
# etc.
# Use 'set_fact' not 'vars' for the rest of the variables to ensure they are are evaluated immediately, to avoid getting this warning later:
# "[WARNING]: when statements should not include jinja2 templating delimiters" (see
- name: Loading environment variables
tags: always
# I write the variables in uppercase so they match the .env file - but you don't have to
# For booleans I use the strings "true" and "false", and convert them to booleans at this point
HOSTNAME: '{{ lookup("env", "HOSTNAME") }}'
INSTALL_APACHE: '{{ lookup("env", "INSTALL_APACHE") == "true" }}'
# etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment