File: step_connect_docker.go

package info (click to toggle)
packer 1.6.6%2Bds2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 33,156 kB
  • sloc: sh: 1,154; python: 619; makefile: 251; ruby: 205; xml: 97
file content (82 lines) | stat: -rw-r--r-- 2,211 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package docker

import (
	"context"
	"fmt"
	"os/exec"
	"strings"

	"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
)

type StepConnectDocker struct{}

func (s *StepConnectDocker) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	config, ok := state.Get("config").(*Config)
	if !ok {
		err := fmt.Errorf("error encountered obtaining docker config")
		state.Put("error", err)
		return multistep.ActionHalt
	}

	containerId := state.Get("container_id").(string)
	driver := state.Get("driver").(Driver)
	tempDir := state.Get("temp_dir").(string)

	// Get the version so we can pass it to the communicator
	version, err := driver.Version()
	if err != nil {
		state.Put("error", err)
		return multistep.ActionHalt
	}

	containerUser, err := getContainerUser(containerId)
	if err != nil {
		state.Put("error", err)
		return multistep.ActionHalt
	}

	// Create the communicator that talks to Docker via various
	// os/exec tricks.
	if config.WindowsContainer {
		comm := &WindowsContainerCommunicator{Communicator{
			ContainerID:   containerId,
			HostDir:       tempDir,
			ContainerDir:  config.ContainerDir,
			Version:       version,
			Config:        config,
			ContainerUser: containerUser,
			EntryPoint:    []string{"powershell"},
		},
		}
		state.Put("communicator", comm)

	} else {
		comm := &Communicator{
			ContainerID:   containerId,
			HostDir:       tempDir,
			ContainerDir:  config.ContainerDir,
			Version:       version,
			Config:        config,
			ContainerUser: containerUser,
			EntryPoint:    []string{"/bin/sh", "-c"},
		}
		state.Put("communicator", comm)
	}
	return multistep.ActionContinue
}

func (s *StepConnectDocker) Cleanup(state multistep.StateBag) {}

func getContainerUser(containerId string) (string, error) {
	inspectArgs := []string{"docker", "inspect", "--format", "{{.Config.User}}", containerId}
	stdout, err := exec.Command(inspectArgs[0], inspectArgs[1:]...).Output()
	if err != nil {
		errStr := fmt.Sprintf("Failed to inspect the container: %s", err)
		if ee, ok := err.(*exec.ExitError); ok {
			errStr = fmt.Sprintf("%s, %s", errStr, ee.Stderr)
		}
		return "", fmt.Errorf(errStr)
	}
	return strings.TrimSpace(string(stdout)), nil
}