DEV Community

loading...

Get Environment Variables From a File into Makefile

Serhat Teker
Uomo Universale | Software Engineer | Entrepreneur | builds systems | py:js:go |
Originally published at tech.serhatteker.com on ・1 min read

It is very easy to achive that in make:

# Makefile

include .$(PWD)/.env
Enter fullscreen mode Exit fullscreen mode

That's all. You can now access your env vars in make targets:

# Makefile

include .$(PWD)/.env

dummy-target:
    @echo $(SOME_ENV_VAR)
Enter fullscreen mode Exit fullscreen mode

Sub-make

If want to you pass all your environment variables into Sub-make you should export them:

# Makefile

ENV := $(PWD)/.env

# Environment variables for project
include $(ENV)

# Export all variable to sub-make
export
Enter fullscreen mode Exit fullscreen mode

Multiple Files

You can use multiple env files and their names can be anything:

# Variables
# -------------------------------------------------------------------------------------
VENV        := $(PWD)/.venv
ENV         := $(PWD)/.env
ENVS        := $(PWD)/.envs

# Environment variables for project
include $(ENV)
# Local environment variables for db
include $(ENVS)/.postgres
include $(ENVS)/.redis

# Export all variable to sub-make
export
Enter fullscreen mode Exit fullscreen mode

All done.

Discussion (0)