Add reading environment from Docker image (#771)
* fix: read envvars from image definition * fix: add test * fix: sort slices Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
This commit is contained in:
parent
4d552e65ce
commit
c2c8b525f8
2 changed files with 75 additions and 1 deletions
|
@ -294,8 +294,15 @@ func (cr *containerReference) create(capAdd []string, capDrop []string) common.E
|
|||
}
|
||||
logger := common.Logger(ctx)
|
||||
isTerminal := term.IsTerminal(int(os.Stdout.Fd()))
|
||||
|
||||
input := cr.input
|
||||
|
||||
insp, _, err := cr.cli.ImageInspectWithRaw(ctx, input.Image)
|
||||
if err != nil {
|
||||
logger.Error(err)
|
||||
}
|
||||
|
||||
input.Env = mergeEnvFromImage(input.Env, insp.Config.Env)
|
||||
|
||||
config := &container.Config{
|
||||
Image: input.Image,
|
||||
Cmd: input.Cmd,
|
||||
|
@ -348,6 +355,39 @@ func (cr *containerReference) create(capAdd []string, capDrop []string) common.E
|
|||
}
|
||||
}
|
||||
|
||||
func mergeEnvFromImage(inputEnv, imageEnv []string) []string {
|
||||
envMap := make(map[string]string)
|
||||
for _, v := range inputEnv {
|
||||
e := strings.Split(v, `=`)
|
||||
if e[1] == "" {
|
||||
envMap[e[0]] = ""
|
||||
} else {
|
||||
envMap[e[0]] = e[1]
|
||||
}
|
||||
}
|
||||
|
||||
for _, v := range imageEnv {
|
||||
e := strings.SplitN(v, `=`, 2)
|
||||
if env, ok := envMap[e[0]]; !ok {
|
||||
if e[1] != "" {
|
||||
envMap[e[0]] = e[1]
|
||||
}
|
||||
} else {
|
||||
if e[0] == "PATH" {
|
||||
if e[1] != "" {
|
||||
envMap[e[0]] = strings.Join([]string{env, e[1]}, `:`)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out := make([]string, 0)
|
||||
for k, v := range envMap {
|
||||
out = append(out, strings.Join([]string{k, v}, `=`))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
var singleLineEnvPattern, mulitiLineEnvPattern *regexp.Regexp
|
||||
|
||||
func (cr *containerReference) extractEnv(srcPath string, env *map[string]string) common.Executor {
|
||||
|
|
34
pkg/container/docker_run_test.go
Normal file
34
pkg/container/docker_run_test.go
Normal file
|
@ -0,0 +1,34 @@
|
|||
package container
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestMergeEnvFromImage(t *testing.T) {
|
||||
inputEnv := []string{
|
||||
"PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin",
|
||||
"GOPATH=/root/go",
|
||||
"GOOS=linux",
|
||||
}
|
||||
imageEnv := []string{
|
||||
"PATH=/root/go/bin",
|
||||
"GOPATH=/tmp",
|
||||
"GOARCH=amd64",
|
||||
}
|
||||
|
||||
merged := mergeEnvFromImage(inputEnv, imageEnv)
|
||||
sort.Strings(merged)
|
||||
|
||||
expected := []string{
|
||||
"PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin:/root/go/bin",
|
||||
"GOPATH=/root/go",
|
||||
"GOOS=linux",
|
||||
"GOARCH=amd64",
|
||||
}
|
||||
sort.Strings(expected)
|
||||
|
||||
assert.Equal(t, expected, merged)
|
||||
}
|
Loading…
Reference in a new issue