From fa11147e5fcd85c958151b29404ae07787380893 Mon Sep 17 00:00:00 2001 From: Michael Crosby Date: Fri, 6 Sep 2019 16:25:02 -0400 Subject: [PATCH] Add --env-file to ctr Closes #3517 Signed-off-by: Michael Crosby --- cmd/ctr/commands/commands.go | 4 ++++ cmd/ctr/commands/run/run_unix.go | 3 +++ cmd/ctr/commands/run/run_windows.go | 3 +++ oci/spec_opts.go | 22 ++++++++++++++++++++++ 4 files changed, 32 insertions(+) diff --git a/cmd/ctr/commands/commands.go b/cmd/ctr/commands/commands.go index b1a2b853a..808ea37d7 100644 --- a/cmd/ctr/commands/commands.go +++ b/cmd/ctr/commands/commands.go @@ -77,6 +77,10 @@ var ( Name: "env", Usage: "specify additional container environment variables (i.e. FOO=bar)", }, + cli.StringFlag{ + Name: "env-file", + Usage: "specify additional container environment variables in a file(i.e. FOO=bar, one per line)", + }, cli.StringSliceFlag{ Name: "label", Usage: "specify additional labels (i.e. foo=bar)", diff --git a/cmd/ctr/commands/run/run_unix.go b/cmd/ctr/commands/run/run_unix.go index b3eaf926f..2ba015cd0 100644 --- a/cmd/ctr/commands/run/run_unix.go +++ b/cmd/ctr/commands/run/run_unix.go @@ -64,6 +64,9 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli args = context.Args()[2:] ) opts = append(opts, oci.WithDefaultSpec(), oci.WithDefaultUnixDevices) + if ef := context.String("env-file"); ef != "" { + opts = append(opts, oci.WithEnvFile(ef)) + } opts = append(opts, oci.WithEnv(context.StringSlice("env"))) opts = append(opts, withMounts(context)) diff --git a/cmd/ctr/commands/run/run_windows.go b/cmd/ctr/commands/run/run_windows.go index a2b860808..d0e4ad934 100644 --- a/cmd/ctr/commands/run/run_windows.go +++ b/cmd/ctr/commands/run/run_windows.go @@ -67,6 +67,9 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli opts = append(opts, oci.WithWindowNetworksAllowUnqualifiedDNSQuery()) opts = append(opts, oci.WithWindowsIgnoreFlushesDuringBoot()) } + if ef := context.String("env-file"); ef != "" { + opts = append(opts, oci.WithEnvFile(ef)) + } opts = append(opts, oci.WithEnv(context.StringSlice("env"))) opts = append(opts, withMounts(context)) diff --git a/oci/spec_opts.go b/oci/spec_opts.go index a18c6b214..33bbcf23c 100644 --- a/oci/spec_opts.go +++ b/oci/spec_opts.go @@ -17,6 +17,7 @@ package oci import ( + "bufio" "context" "encoding/json" "fmt" @@ -1200,3 +1201,24 @@ func WithLinuxDevice(path, permissions string) SpecOpts { return nil } } + +// WithEnvFile adds environment variables from a file to the container's spec +func WithEnvFile(path string) SpecOpts { + return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error { + var vars []string + f, err := os.Open(path) + if err != nil { + return err + } + defer f.Close() + + sc := bufio.NewScanner(f) + for sc.Scan() { + if sc.Err() != nil { + return sc.Err() + } + vars = append(vars, sc.Text()) + } + return WithEnv(vars)(nil, nil, nil, s) + } +}