File: utils.go

package info (click to toggle)
packer 1.6.6%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 32,016 kB
  • sloc: sh: 1,154; python: 619; makefile: 251; ruby: 205; xml: 97
file content (75 lines) | stat: -rw-r--r-- 1,578 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
package common

import (
	"fmt"
	"strings"

	"github.com/hashicorp/packer/packer-plugin-sdk/multistep"
	packersdk "github.com/hashicorp/packer/packer-plugin-sdk/packer"
	"github.com/ucloud/ucloud-sdk-go/services/uhost"
)

func CheckStringIn(val string, available []string) error {
	for _, choice := range available {
		if val == choice {
			return nil
		}
	}

	return fmt.Errorf("should be one of %q, got %q", strings.Join(available, ","), val)
}

func CheckIntIn(val int, available []int) error {
	for _, choice := range available {
		if val == choice {
			return nil
		}
	}

	return fmt.Errorf("should be one of %v, got %d", available, val)
}

func IsStringIn(val string, available []string) bool {
	for _, choice := range available {
		if val == choice {
			return true
		}
	}

	return false
}

// SSHHost returns a function that can be given to the SSH communicator
func SSHHost(usePrivateIp bool) func(multistep.StateBag) (string, error) {
	return func(state multistep.StateBag) (string, error) {

		instance := state.Get("instance").(*uhost.UHostInstanceSet)
		var privateIp, publicIp string

		for _, v := range instance.IPSet {
			if v.Type == IpTypePrivate {
				privateIp = v.IP
			} else {
				publicIp = v.IP
			}
		}

		if usePrivateIp {
			return privateIp, nil
		}

		return publicIp, nil
	}
}

func Halt(state multistep.StateBag, err error, prefix string) multistep.StepAction {
	ui := state.Get("ui").(packersdk.Ui)

	if prefix != "" {
		err = fmt.Errorf("%s: %s", prefix, err)
	}

	state.Put("error", err)
	ui.Error(err.Error())
	return multistep.ActionHalt
}