Browse code

'docker run -e': set environment variables in a container

Solomon Hykes authored on 2013/03/23 12:36:34
Showing 3 changed files
... ...
@@ -766,6 +766,18 @@ func (p *ports) Set(value string) error {
766 766
 	return nil
767 767
 }
768 768
 
769
+// ListOpts type
770
+type ListOpts []string
771
+
772
+func (opts *ListOpts) String() string {
773
+	return fmt.Sprint(*opts)
774
+}
775
+
776
+func (opts *ListOpts) Set(value string) error {
777
+	*opts = append(*opts, value)
778
+	return nil
779
+}
780
+
769 781
 func (srv *Server) CmdTag(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
770 782
 	cmd := rcli.Subcmd(stdout, "tag", "[OPTIONS] IMAGE REPOSITORY [TAG]", "Tag an image into a repository")
771 783
 	force := cmd.Bool("f", false, "Force")
... ...
@@ -789,6 +801,8 @@ func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string)
789 789
 	var fl_ports ports
790 790
 
791 791
 	cmd.Var(&fl_ports, "p", "Map a network port to the container")
792
+	var fl_env ListOpts
793
+	cmd.Var(&fl_env, "e", "Set environment variables")
792 794
 	if err := cmd.Parse(args); err != nil {
793 795
 		return nil
794 796
 	}
... ...
@@ -819,6 +833,7 @@ func (srv *Server) CmdRun(stdin io.ReadCloser, stdout io.Writer, args ...string)
819 819
 			Tty:       *fl_tty,
820 820
 			OpenStdin: *fl_stdin,
821 821
 			Memory:    *fl_memory,
822
+			Env:       fl_env,
822 823
 		})
823 824
 	if err != nil {
824 825
 		return errors.New("Error creating container: " + err.Error())
... ...
@@ -53,6 +53,7 @@ type Config struct {
53 53
 	Ports      []int
54 54
 	Tty        bool // Attach standard streams to a tty, including stdin if it is not closed.
55 55
 	OpenStdin  bool // Open stdin
56
+	Env        []string
56 57
 }
57 58
 
58 59
 type NetworkSettings struct {
... ...
@@ -200,6 +201,15 @@ func (container *Container) Start() error {
200 200
 
201 201
 	container.cmd = exec.Command("/usr/bin/lxc-start", params...)
202 202
 
203
+	// Setup environment
204
+	container.cmd.Env = append(
205
+		[]string{
206
+			"HOME=/",
207
+			"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
208
+		},
209
+		container.Config.Env...,
210
+	)
211
+
203 212
 	var err error
204 213
 	if container.Config.Tty {
205 214
 		err = container.startPty()
... ...
@@ -52,13 +52,6 @@ func changeUser(u string) {
52 52
 	}
53 53
 }
54 54
 
55
-// Set the environment to a known, repeatable state
56
-func setupEnv() {
57
-	os.Clearenv()
58
-	os.Setenv("HOME", "/")
59
-	os.Setenv("PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin")
60
-}
61
-
62 55
 func executeProgram(name string, args []string) {
63 56
 	path, err := exec.LookPath(name)
64 57
 	if err != nil {
... ...
@@ -86,6 +79,5 @@ func SysInit() {
86 86
 
87 87
 	setupNetworking(*gw)
88 88
 	changeUser(*u)
89
-	setupEnv()
90 89
 	executeProgram(flag.Arg(0), flag.Args())
91 90
 }