I want to check if the following is the correct/acceptable way of reading environment variables from .env
in a Makefile.
Makefile:
export DB_HOST=$(shell grep DB_HOST .env | cut -d '=' -f2)
export DB_PORT=$(shell grep DB_PORT .env | cut -d '=' -f2)
export DB_NAME=$(shell grep DB_NAME .env | cut -d '=' -f2)
export DB_PASSWORD=$(shell grep DB_PASSWORD .env | cut -d '=' -f2)
export DB_CONTAINER_NAME=$(shell grep DB_CONTAINER_NAME .env | cut -d '=' -f2)
.PHONY: run-mysql-database
run-mysql-database:
@docker run --name $(DB_CONTAINER_NAME) -p $(DB_PORT):3306 -e MYSQL_ROOT_PASSWORD=$(DB_PASSWORD) -e MYSQL_DATABASE=$(DB_NAME) -d mysql
Content of .env
:
DB_HOST=localhost
DB_PORT=13306
DB_NAME="spring-boot-todo"
DB_PASSWORD="password"
DB_CONTAINER_NAME="spring-boot-todo-db"
I also tried to use another approach — introduce init
target and call it before executing run-mysql-database
. But this approach does not work:
init:
source .env
export DB_HOST
export DB_PORT
export DB_NAME
export DB_PASSWORD
export DB_CONTAINER_NAME
Error: make: source: No such file or directory
Another option is to use source .env
before executing a command:
# run Spring Boot application
.PHONY: run
run: run-mysql-database
# set environment variables from .env file and run Spring Boot application
@echo "Running Spring Boot application..."
@source .env && ./mvnw spring-boot:run
This works. But sometimes, I need to access a specific environment variable (e.g., for printing) and wonder if there is a better approach.
CodePudding user response:
As @Beta mentioned in his comment, you just need to write include .env
at top of your Makefile
and it should include the variables declared in .env
file.
Showing a very simple and working example (Files and example taken from https://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/):
Contents of your .env
file:
Makefile-Test$ cat .env
DB_HOST=localhost
DB_PORT=13306
DB_NAME="spring-boot-todo"
DB_PASSWORD="password"
DB_CONTAINER_NAME="spring-boot-todo-db"
And Contents of Makefile
:
include .env
hellomake: hellomake.c hellofunc.c
@echo ${DB_HOST}
gcc -o hellomake hellomake.c hellofunc.c -I.
clean:
@echo ${DB_NAME}
rm -f hellomake
all: clean hellomake
Running make all
should first print the contents of variable DB_NAME
and then DB_HOST
.