Skip to content

Commit 276c79b

Browse files
fix: pebble exec inherits environment from daemon
Currently, the environment variables from the pebble daemon are not inherited while executing ``pebble exec`` commands. Change this behavior and inherit all enviroment variables available to the pebble daemon, in pebble exec. Addresses ROCKS-684 on Jira.
1 parent 48d20dc commit 276c79b

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

internals/daemon/api_exec.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ import (
1818
"encoding/json"
1919
"fmt"
2020
"net/http"
21+
"os"
2122
"os/exec"
23+
"strings"
2224
"time"
2325

2426
"github.com/canonical/pebble/internals/osutil"
@@ -73,13 +75,30 @@ func v1PostExec(c *Command, req *http.Request, _ *userState) Response {
7375
return statusBadRequest("%v", err)
7476
}
7577

78+
// Inherit the pebble daemon environment.
79+
environment := make(map[string]string)
80+
for key, val := range payload.Environment {
81+
environment[key] = val
82+
}
83+
for _, kv := range os.Environ() {
84+
parts := strings.SplitN(kv, "=", 2)
85+
key := parts[0]
86+
val := ""
87+
if len(parts) == 2 {
88+
val = parts[1]
89+
}
90+
if _, ok := environment[key]; !ok {
91+
environment[key] = val
92+
}
93+
}
94+
7695
st := c.d.overlord.State()
7796
st.Lock()
7897
defer st.Unlock()
7998

8099
args := &cmdstate.ExecArgs{
81100
Command: payload.Command,
82-
Environment: payload.Environment,
101+
Environment: environment,
83102
WorkingDir: payload.WorkingDir,
84103
Timeout: timeout,
85104
UserID: uid,

internals/daemon/api_exec_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,28 @@ func (s *execSuite) TestEnvironment(c *C) {
108108
c.Check(stderr, Equals, "")
109109
}
110110

111+
func (s *execSuite) TestEnvironmentInheritedFromDaemon(c *C) {
112+
oldEnv, envWasSet := os.LookupEnv("FOO")
113+
err := os.Setenv("FOO", "bar")
114+
c.Check(err, IsNil)
115+
defer func() {
116+
var err error
117+
if envWasSet {
118+
err = os.Setenv("FOO", oldEnv)
119+
} else {
120+
err = os.Unsetenv("FOO")
121+
}
122+
c.Check(err, IsNil)
123+
}()
124+
125+
stdout, stderr, waitErr := s.exec(c, "", &client.ExecOptions{
126+
Command: []string{"/bin/sh", "-c", "echo FOO=$FOO"},
127+
})
128+
c.Check(waitErr, IsNil)
129+
c.Check(stdout, Equals, "FOO=bar\n")
130+
c.Check(stderr, Equals, "")
131+
}
132+
111133
func (s *execSuite) TestWorkingDir(c *C) {
112134
workingDir := c.MkDir()
113135
stdout, stderr, waitErr := s.exec(c, "", &client.ExecOptions{

0 commit comments

Comments
 (0)