generated from hashicorp/packer-plugin-scaffolding
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathstep_share_image.go
87 lines (72 loc) · 2.31 KB
/
step_share_image.go
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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package cvm
import (
"context"
"fmt"
"strings"
"github.com/hashicorp/packer-plugin-sdk/multistep"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
)
type stepShareImage struct {
ShareAccounts []string
}
func (s *stepShareImage) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
// Skip step if we don't have an image to share or no accounts to share to
_, ok := state.GetOk("image")
if !ok || len(s.ShareAccounts) == 0 {
return multistep.ActionContinue
}
client := state.Get("cvm_client").(*cvm.Client)
imageId := state.Get("image").(*cvm.Image).ImageId
Say(state, strings.Join(s.ShareAccounts, ","), "Trying to share image to")
req := cvm.NewModifyImageSharePermissionRequest()
req.ImageId = imageId
req.Permission = common.StringPtr("SHARE")
accounts := make([]*string, 0, len(s.ShareAccounts))
for _, account := range s.ShareAccounts {
accounts = append(accounts, common.StringPtr(account))
}
req.AccountIds = accounts
err := Retry(ctx, func(ctx context.Context) error {
_, e := client.ModifyImageSharePermission(req)
return e
})
if err != nil {
return Halt(state, err, "Failed to share image")
}
Message(state, "Image shared", "")
return multistep.ActionContinue
}
func (s *stepShareImage) Cleanup(state multistep.StateBag) {
_, cancelled := state.GetOk(multistep.StateCancelled)
_, halted := state.GetOk(multistep.StateHalted)
if !cancelled && !halted {
return
}
ctx := context.TODO()
client := state.Get("cvm_client").(*cvm.Client)
image, ok := state.GetOk("image")
if !ok {
return
}
imageId := image.(*cvm.Image).ImageId
SayClean(state, "image share")
req := cvm.NewModifyImageSharePermissionRequest()
req.ImageId = imageId
req.Permission = common.StringPtr("CANCEL")
accounts := make([]*string, 0, len(s.ShareAccounts))
for _, account := range s.ShareAccounts {
account := account
accounts = append(accounts, &account)
}
req.AccountIds = accounts
err := Retry(ctx, func(ctx context.Context) error {
_, e := client.ModifyImageSharePermission(req)
return e
})
if err != nil {
Error(state, err, fmt.Sprintf("Failed to cancel share image(%s), please delete it manually", *imageId))
}
}