Skip to content

Commit 61b127f

Browse files
authored
Merge pull request #3628 from crosbymichael/ctr-env
Add --env-file to ctr
2 parents 2ddfc6d + fa11147 commit 61b127f

4 files changed

Lines changed: 32 additions & 0 deletions

File tree

cmd/ctr/commands/commands.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,10 @@ var (
7777
Name: "env",
7878
Usage: "specify additional container environment variables (i.e. FOO=bar)",
7979
},
80+
cli.StringFlag{
81+
Name: "env-file",
82+
Usage: "specify additional container environment variables in a file(i.e. FOO=bar, one per line)",
83+
},
8084
cli.StringSliceFlag{
8185
Name: "label",
8286
Usage: "specify additional labels (i.e. foo=bar)",

cmd/ctr/commands/run/run_unix.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,9 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
6464
args = context.Args()[2:]
6565
)
6666
opts = append(opts, oci.WithDefaultSpec(), oci.WithDefaultUnixDevices)
67+
if ef := context.String("env-file"); ef != "" {
68+
opts = append(opts, oci.WithEnvFile(ef))
69+
}
6770
opts = append(opts, oci.WithEnv(context.StringSlice("env")))
6871
opts = append(opts, withMounts(context))
6972

cmd/ctr/commands/run/run_windows.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ func NewContainer(ctx gocontext.Context, client *containerd.Client, context *cli
6767
opts = append(opts, oci.WithWindowNetworksAllowUnqualifiedDNSQuery())
6868
opts = append(opts, oci.WithWindowsIgnoreFlushesDuringBoot())
6969
}
70+
if ef := context.String("env-file"); ef != "" {
71+
opts = append(opts, oci.WithEnvFile(ef))
72+
}
7073
opts = append(opts, oci.WithEnv(context.StringSlice("env")))
7174
opts = append(opts, withMounts(context))
7275

oci/spec_opts.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package oci
1818

1919
import (
20+
"bufio"
2021
"context"
2122
"encoding/json"
2223
"fmt"
@@ -1200,3 +1201,24 @@ func WithLinuxDevice(path, permissions string) SpecOpts {
12001201
return nil
12011202
}
12021203
}
1204+
1205+
// WithEnvFile adds environment variables from a file to the container's spec
1206+
func WithEnvFile(path string) SpecOpts {
1207+
return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {
1208+
var vars []string
1209+
f, err := os.Open(path)
1210+
if err != nil {
1211+
return err
1212+
}
1213+
defer f.Close()
1214+
1215+
sc := bufio.NewScanner(f)
1216+
for sc.Scan() {
1217+
if sc.Err() != nil {
1218+
return sc.Err()
1219+
}
1220+
vars = append(vars, sc.Text())
1221+
}
1222+
return WithEnv(vars)(nil, nil, nil, s)
1223+
}
1224+
}

0 commit comments

Comments
 (0)