From 4e9f76768c87affd2da6868c70cc554b8a646784 Mon Sep 17 00:00:00 2001 From: Genzer <732937+Genzer@users.noreply.github.com> Date: Wed, 5 Jun 2024 15:55:40 +0700 Subject: [PATCH] Load .env from Compose file's directory and cwd This commit loads dotenv `.env` (exactly that name) from the following location (the later takes precedence): - The `.env` file in the Compose file's directory. - The `.env` file in the current working directory (invoking podman-compose). This preserves the behavior prior to 1.1.0 and to match with Docker Compose CLI. Fix: https://github.com/containers/podman-compose/issues/937 Signed-off-by: Genzer <732937+Genzer@users.noreply.github.com> --- podman_compose.py | 8 +++++++- tests/env-file-tests/README.md | 10 ++++++++++ .../container-compose.load-.env-in-project.yaml | 11 +++++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/env-file-tests/project/container-compose.load-.env-in-project.yaml diff --git a/podman_compose.py b/podman_compose.py index 987ec48..250dbcd 100755 --- a/podman_compose.py +++ b/podman_compose.py @@ -1798,8 +1798,14 @@ class PodmanCompose: # env-file is relative to the CWD dotenv_dict = {} if args.env_file: + # Load .env from the Compose file's directory to preserve + # behavior prior to 1.1.0 and to match with Docker Compose (v2). + if ".env" == args.env_file: + project_dotenv_file = os.path.realpath(os.path.join(dirname, ".env")) + if os.path.exists(project_dotenv_file): + dotenv_dict.update(dotenv_to_dict(project_dotenv_file)) dotenv_path = os.path.realpath(args.env_file) - dotenv_dict = dotenv_to_dict(dotenv_path) + dotenv_dict.update(dotenv_to_dict(dotenv_path)) # TODO: remove next line os.chdir(dirname) diff --git a/tests/env-file-tests/README.md b/tests/env-file-tests/README.md index cfefd15..9de7018 100644 --- a/tests/env-file-tests/README.md +++ b/tests/env-file-tests/README.md @@ -25,3 +25,13 @@ based on environment variable precedent this command should give podman-rocks-32 ``` ZZVAR1=podman-rocks-321 podman-compose -f $(pwd)/project/container-compose.yaml --env-file $(pwd)/env-files/project-1.env up ``` + +_The below test should print three environment variables_ + +``` +podman-compose -f $(pwd)/project/container-compose.load-.env-in-project.yaml run --rm app + +ZZVAR1=This value is overwritten by env-file-tests/.env +ZZVAR2=This value is loaded from .env in project/ directory +ZZVAR3=This value is loaded from env-file-tests/.env +``` diff --git a/tests/env-file-tests/project/container-compose.load-.env-in-project.yaml b/tests/env-file-tests/project/container-compose.load-.env-in-project.yaml new file mode 100644 index 0000000..6cabc0b --- /dev/null +++ b/tests/env-file-tests/project/container-compose.load-.env-in-project.yaml @@ -0,0 +1,11 @@ +services: + app: + image: busybox + command: ["/bin/busybox", "sh", "-c", "env | grep ZZ"] + tmpfs: + - /run + - /tmp + environment: + ZZVAR1: $ZZVAR1 + ZZVAR2: $ZZVAR2 + ZZVAR3: $ZZVAR3