forked from hashicorp/packer-plugin-tencentcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstep_check_source_image.go
More file actions
76 lines (65 loc) · 2.09 KB
/
step_check_source_image.go
File metadata and controls
76 lines (65 loc) · 2.09 KB
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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package cvm
import (
"context"
"fmt"
"regexp"
"github.com/hashicorp/packer-plugin-sdk/multistep"
cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
)
type stepCheckSourceImage struct {
sourceImageId string
}
func (s *stepCheckSourceImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
var (
imageNameRegex *regexp.Regexp
err error
)
config := state.Get("config").(*Config)
client := state.Get("cvm_client").(*cvm.Client)
var source_image *cvm.Image
if state.Get("source_image") != nil {
source_image = state.Get("source_image").(*cvm.Image)
}
Say(state, config.SourceImageId, "Trying to check source image")
req := cvm.NewDescribeImagesRequest()
req.InstanceType = &config.InstanceType
if config.SourceImageId != "" {
req.ImageIds = []*string{&config.SourceImageId}
} else if source_image != nil && *source_image.ImageId != "" {
req.ImageIds = []*string{source_image.ImageId}
} else {
imageNameRegex, err = regexp.Compile(config.SourceImageName)
if err != nil {
return Halt(state, fmt.Errorf("regex compilation error"), "Bad input")
}
}
var resp *cvm.DescribeImagesResponse
err = Retry(ctx, func(ctx context.Context) error {
var err error
resp, err = client.DescribeImages(req)
return err
})
if err != nil {
return Halt(state, err, "Failed to get source image info")
}
if *resp.Response.TotalCount > 0 {
images := resp.Response.ImageSet
if imageNameRegex != nil {
for _, image := range images {
if imageNameRegex.MatchString(*image.ImageName) {
state.Put("source_image", image)
Message(state, *image.ImageName, "Image found")
return multistep.ActionContinue
}
}
} else {
state.Put("source_image", images[0])
Message(state, *resp.Response.ImageSet[0].ImageName, "Image found")
return multistep.ActionContinue
}
}
return Halt(state, fmt.Errorf("No image found under current instance_type(%s) restriction", config.InstanceType), "")
}
func (s *stepCheckSourceImage) Cleanup(bag multistep.StateBag) {}