diff --git a/docs/source/markdown/options/env-merge.md b/docs/source/markdown/options/env-merge.md index 4bc1c388da..20a35f666e 100644 --- a/docs/source/markdown/options/env-merge.md +++ b/docs/source/markdown/options/env-merge.md @@ -7,3 +7,7 @@ Preprocess default environment variables for the containers. For example if image contains environment variable `hello=world` user can preprocess it using `--env-merge hello=${hello}-some` so new value is `hello=world-some`. + +Please note that if the environment variable `hello` is not present in the image, +then it'll be replaced by an empty string and so using `--env-merge hello=${hello}-some` +would result in the new value of `hello=-some`, notice the leading `-` delimiter. diff --git a/pkg/specgen/generate/container.go b/pkg/specgen/generate/container.go index 7a3f479b19..c43d61f821 100644 --- a/pkg/specgen/generate/container.go +++ b/pkg/specgen/generate/container.go @@ -135,10 +135,16 @@ func CompleteSpec(ctx context.Context, r *libpod.Runtime, s *specgen.SpecGenerat if err != nil { return nil, fmt.Errorf("unable to process variables for --env-merge %s: %w", e, err) } - splitWord := strings.Split(processedWord, "=") - if _, ok := defaultEnvs[splitWord[0]]; ok { - defaultEnvs[splitWord[0]] = splitWord[1] + + key, val, found := strings.Cut(processedWord, "=") + if !found { + return nil, fmt.Errorf("missing `=` for --env-merge substitution %s", e) } + + // the env var passed via --env-merge + // need not be defined in the image + // continue with an empty string + defaultEnvs[key] = val } for _, e := range s.UnsetEnv { diff --git a/test/e2e/run_env_test.go b/test/e2e/run_env_test.go index 5ba6bbe98d..9006bff048 100644 --- a/test/e2e/run_env_test.go +++ b/test/e2e/run_env_test.go @@ -76,6 +76,11 @@ ENV hello=world session.WaitWithDefaultTimeout() Expect(session).Should(Exit(0)) Expect(session.OutputToString()).To(ContainSubstring("world-earth")) + + session = podmanTest.Podman([]string{"run", "--rm", "--env-merge", "foo=${bar}-earth", "test", "printenv", "foo"}) + session.WaitWithDefaultTimeout() + Expect(session).Should(Exit(0)) + Expect(session.OutputToString()).To(Equal("-earth")) }) It("podman run --env-host environment test", func() {