websites/ewintr.nl/content/2020/shared-environment-variable...

48 lines
1.3 KiB
Markdown
Raw Normal View History

2025-01-07 20:01:55 +01:00
+++
title = "Shared environment variables for make, bash and docker"
date = 2020-01-07
+++
It is possible to define a set of variables and share them in Make, Bash and the Docker containers that are orchestrated by `docker-compose`.
Docker-compose can use an `.env` file to substitute variables in a `docker-compose.yml` file in the same directory. In this docker-compose.yml they can be exported to the containers.
Incuding this `.env` file in your `Makefile` makes hem available there as well, but they are not automatically exported to the Bash shells that are spawned by `make` to execute the targets. This can be changed by adding the `.EXPORTALLVARIABLES:` target to your `Makefile`.
2025-01-15 20:11:22 +01:00
`.env`:
{% code() %}
2025-01-07 20:01:55 +01:00
VAR1=this
VAR2=that
VAR3=those
2025-01-15 20:11:22 +01:00
{% end %}
`Makefile`:
2025-01-07 20:01:55 +01:00
2025-01-15 20:11:22 +01:00
{% code() %}
2025-01-07 20:01:55 +01:00
include .env
.EXPORT_ALL_VARIABLES:
task:
@echo "VAR1 is ${VAR1}"
2025-01-15 20:11:22 +01:00
@some_command # some_command can use $VAR1, $VAR2, $VAR3
2025-01-07 20:01:55 +01:00
@docker-compose up
2025-01-15 20:11:22 +01:00
{% end %}
`docker-compose.yml`:
2025-01-07 20:01:55 +01:00
2025-01-15 20:11:22 +01:00
{% code() %}
2025-01-07 20:01:55 +01:00
...
app:
image: "registry/the_app:${VAR2}"
environment:
- VAR3=${VAR3}
2025-01-15 20:11:22 +01:00
{% end %}
2025-01-07 20:01:55 +01:00
## Sources
- [vsupalov.com](https://vsupalov.com/docker-arg-env-variable-guide/#the-dot-env-file-env)
- [www.gnu.org](https://www.gnu.org/software/make/manual/html_node/Special-Targets.html#Special-Targets)