File: step_temp_dir.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 (80 lines) | stat: -rw-r--r-- 1,969 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
package docker

import (
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"

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

// StepTempDir creates a temporary directory that we use in order to
// share data with the docker container over the communicator.
type StepTempDir struct {
	tempDir string
}

// ConfigTmpDir returns the configuration tmp directory for Docker
func ConfigTmpDir() (string, error) {
	configdir, err := pathing.ConfigDir()
	if err != nil {
		return "", err
	}
	if tmpdir := os.Getenv("PACKER_TMP_DIR"); tmpdir != "" {
		// override the config dir with tmp dir. Still stat it and mkdirall if
		// necessary.
		fp, err := filepath.Abs(tmpdir)
		log.Printf("found PACKER_TMP_DIR env variable; setting tmpdir to %s", fp)
		if err != nil {
			return "", err
		}
		configdir = fp
	}

	_, err = os.Stat(configdir)
	if os.IsNotExist(err) {
		log.Printf("Config dir %s does not exist; creating...", configdir)
		if err = os.MkdirAll(configdir, 0755); err != nil {
			return "", err
		}
	} else if err != nil {
		return "", err
	}

	td, err := ioutil.TempDir(configdir, "tmp")
	if err != nil {
		return "", fmt.Errorf("Error creating temp dir: %s", err)

	}
	log.Printf("Set Packer temp dir to %s", td)
	return td, nil
}

func (s *StepTempDir) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	ui := state.Get("ui").(packersdk.Ui)

	ui.Say("Creating a temporary directory for sharing data...")

	tempdir, err := ConfigTmpDir()
	if err != nil {
		err := fmt.Errorf("Error making temp dir: %s", err)
		state.Put("error", err)
		ui.Error(err.Error())
		return multistep.ActionHalt
	}

	s.tempDir = tempdir
	state.Put("temp_dir", s.tempDir)
	return multistep.ActionContinue
}

func (s *StepTempDir) Cleanup(state multistep.StateBag) {
	if s.tempDir != "" {
		os.RemoveAll(s.tempDir)
	}
}