File: utils.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 (89 lines) | stat: -rw-r--r-- 2,188 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
83
84
85
86
87
88
89
package hyperone

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"strings"

	"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
	packersdk "github.com/hashicorp/packer/packer-plugin-sdk/packer"
	"github.com/hashicorp/packer/packer-plugin-sdk/template/interpolate"
	openapi "github.com/hyperonecom/h1-client-go"
)

func formatOpenAPIError(err error) string {
	openAPIError, ok := err.(openapi.GenericOpenAPIError)
	if !ok {
		return err.Error()
	}

	return fmt.Sprintf("%s (body: %s)", openAPIError.Error(), openAPIError.Body())
}

func runCommands(commands []string, ictx interpolate.Context, state multistep.StateBag) error {
	ctx := context.TODO()
	ui := state.Get("ui").(packersdk.Ui)
	wrappedCommand := state.Get("wrappedCommand").(CommandWrapper)
	comm := state.Get("communicator").(packersdk.Communicator)

	for _, rawCmd := range commands {
		intCmd, err := interpolate.Render(rawCmd, &ictx)
		if err != nil {
			return fmt.Errorf("error interpolating: %s", err)
		}

		command, err := wrappedCommand(intCmd)
		if err != nil {
			return fmt.Errorf("error wrapping command: %s", err)
		}

		remoteCmd := &packersdk.RemoteCmd{
			Command: command,
		}

		ui.Say(fmt.Sprintf("Executing command: %s", command))

		err = remoteCmd.RunWithUi(ctx, comm, ui)
		if err != nil {
			return fmt.Errorf("error running remote cmd: %s", err)
		}

		if remoteCmd.ExitStatus() != 0 {
			return fmt.Errorf(
				"received non-zero exit code %d from command: %s",
				remoteCmd.ExitStatus(),
				command)
		}
	}
	return nil
}

func captureOutput(command string, state multistep.StateBag) (string, error) {
	ctx := context.TODO()
	comm := state.Get("communicator").(packersdk.Communicator)

	var stdout bytes.Buffer
	remoteCmd := &packersdk.RemoteCmd{
		Command: command,
		Stdout:  &stdout,
	}

	log.Println(fmt.Sprintf("Executing command: %s", command))

	err := comm.Start(ctx, remoteCmd)
	if err != nil {
		return "", fmt.Errorf("error running remote cmd: %s", err)
	}

	remoteCmd.Wait()
	if remoteCmd.ExitStatus() != 0 {
		return "", fmt.Errorf(
			"received non-zero exit code %d from command: %s",
			remoteCmd.ExitStatus(),
			command)
	}

	return strings.TrimSpace(stdout.String()), nil
}