packer-cn/builder/hyperone/utils.go

90 lines
2.1 KiB
Go
Raw Normal View History

2019-01-23 08:04:05 -05:00
package hyperone
import (
2019-02-05 10:20:42 -05:00
"bytes"
"context"
2019-01-23 08:04:05 -05:00
"fmt"
2019-02-05 10:20:42 -05:00
"log"
"strings"
2019-01-23 08:04:05 -05:00
2020-12-17 16:29:25 -05:00
"github.com/hashicorp/packer-plugin-sdk/multistep"
packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
"github.com/hashicorp/packer-plugin-sdk/template/interpolate"
openapi "github.com/hyperonecom/h1-client-go"
2019-01-23 08:04:05 -05:00
)
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())
}
2019-01-28 06:30:15 -05:00
func runCommands(commands []string, ictx interpolate.Context, state multistep.StateBag) error {
ctx := context.TODO()
ui := state.Get("ui").(packersdk.Ui)
2019-01-28 06:30:15 -05:00
wrappedCommand := state.Get("wrappedCommand").(CommandWrapper)
comm := state.Get("communicator").(packersdk.Communicator)
2019-01-28 06:30:15 -05:00
for _, rawCmd := range commands {
intCmd, err := interpolate.Render(rawCmd, &ictx)
2019-01-28 06:30:15 -05:00
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{
2019-01-28 06:30:15 -05:00
Command: command,
}
ui.Say(fmt.Sprintf("Executing command: %s", command))
err = remoteCmd.RunWithUi(ctx, comm, ui)
2019-01-28 06:30:15 -05:00
if err != nil {
return fmt.Errorf("error running remote cmd: %s", err)
}
if remoteCmd.ExitStatus() != 0 {
2019-01-28 06:30:15 -05:00
return fmt.Errorf(
"received non-zero exit code %d from command: %s",
remoteCmd.ExitStatus(),
2019-01-28 06:30:15 -05:00
command)
}
}
return nil
}
2019-02-05 10:20:42 -05:00
func captureOutput(command string, state multistep.StateBag) (string, error) {
ctx := context.TODO()
comm := state.Get("communicator").(packersdk.Communicator)
2019-02-05 10:20:42 -05:00
var stdout bytes.Buffer
remoteCmd := &packersdk.RemoteCmd{
2019-02-05 10:20:42 -05:00
Command: command,
Stdout: &stdout,
}
log.Println(fmt.Sprintf("Executing command: %s", command))
err := comm.Start(ctx, remoteCmd)
2019-02-05 10:20:42 -05:00
if err != nil {
return "", fmt.Errorf("error running remote cmd: %s", err)
}
remoteCmd.Wait()
if remoteCmd.ExitStatus() != 0 {
2019-02-05 10:20:42 -05:00
return "", fmt.Errorf(
"received non-zero exit code %d from command: %s",
remoteCmd.ExitStatus(),
2019-02-05 10:20:42 -05:00
command)
}
return strings.TrimSpace(stdout.String()), nil
}