From b5eaf314adeb8fe1c4a70218d2504850c94c653e Mon Sep 17 00:00:00 2001 From: Songmin Li Date: Sat, 20 Jul 2024 01:16:38 +0800 Subject: [PATCH] Support variable substitution with service's environment This commit introduces the ability to substitute environment variables within the 'environment' section of the service definition. This allows for more dynamic configuration of services. Signed-off-by: Songmin Li --- .../substitution-with-service-environment.feature | 1 + podman_compose.py | 15 +++++++++++++++ tests/integration/env-tests/container-compose.yml | 7 ++++--- 3 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 newsfragments/substitution-with-service-environment.feature diff --git a/newsfragments/substitution-with-service-environment.feature b/newsfragments/substitution-with-service-environment.feature new file mode 100644 index 0000000..205d3f6 --- /dev/null +++ b/newsfragments/substitution-with-service-environment.feature @@ -0,0 +1 @@ +Add ability to substitute variables with the environment of the service. diff --git a/podman_compose.py b/podman_compose.py index 35c4aa5..7a063ef 100755 --- a/podman_compose.py +++ b/podman_compose.py @@ -264,6 +264,16 @@ def rec_subs(value, subs_dict): do bash-like substitution in value and if list of dictionary do that recursively """ if is_dict(value): + if 'environment' in value and is_dict(value['environment']): + # Load service's environment variables + subs_dict = subs_dict.copy() + svc_envs = {k: v for k, v in value['environment'].items() if k not in subs_dict} + # we need to add `svc_envs` to the `subs_dict` so that it can evaluate the + # service environment that reference to another service environment. + subs_dict.update(svc_envs) + svc_envs = rec_subs(svc_envs, subs_dict) + subs_dict.update(svc_envs) + value = {k: rec_subs(v, subs_dict) for k, v in value.items()} elif is_str(value): @@ -1823,6 +1833,11 @@ class PodmanCompose: "COMPOSE_FILE": pathsep.join(relative_files), "COMPOSE_PATH_SEPARATOR": pathsep, }) + + if args and 'env' in args and args.env: + env_vars = norm_as_dict(args.env) + self.environ.update(env_vars) + compose = {} # Iterate over files primitively to allow appending to files in-loop files_iter = iter(files) diff --git a/tests/integration/env-tests/container-compose.yml b/tests/integration/env-tests/container-compose.yml index ba39c3f..3a8b28e 100644 --- a/tests/integration/env-tests/container-compose.yml +++ b/tests/integration/env-tests/container-compose.yml @@ -1,9 +1,10 @@ -version: '3' +version: "3" services: env-test: image: busybox command: sh -c "export | grep ZZ" environment: - - ZZVAR1=myval1 - + ZZVAR1: myval1 + ZZVAR2: 2-$ZZVAR1 + ZZVAR3: 3-$ZZVAR2