forked from hashicorp/packer-plugin-tencentcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstep_run_instance.go
More file actions
250 lines (223 loc) · 7.27 KB
/
step_run_instance.go
File metadata and controls
250 lines (223 loc) · 7.27 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package cvm
import (
"context"
"encoding/base64"
"fmt"
"io/ioutil"
"log"
"github.com/hashicorp/packer-plugin-sdk/multistep"
"github.com/hashicorp/packer-plugin-sdk/uuid"
cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
)
type stepRunInstance struct {
InstanceType string
InstanceChargeType string
UserData string
UserDataFile string
instanceId string
ZoneId string
InstanceName string
DiskType string
DiskSize int64
HostName string
InternetChargeType string
InternetMaxBandwidthOut int64
BandwidthPackageId string
CamRoleName string
AssociatePublicIpAddress bool
Tags map[string]string
DataDisks []tencentCloudDataDisk
CdcId string
}
func (s *stepRunInstance) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
client := state.Get("cvm_client").(*cvm.Client)
config := state.Get("config").(*Config)
source_image := state.Get("source_image").(*cvm.Image)
vpc_id := state.Get("vpc_id").(string)
subnet_id := state.Get("subnet_id").(string)
security_group_id := state.Get("security_group_id").(string)
password := config.Comm.SSHPassword
if password == "" && config.Comm.WinRMPassword != "" {
password = config.Comm.WinRMPassword
}
userData, err := s.getUserData(state)
if err != nil {
return Halt(state, err, "Failed to get user_data")
}
Say(state, *source_image.ImageId, "Try to create a new instance based on image")
// config RunInstances parameters
req := cvm.NewRunInstancesRequest()
if s.ZoneId != "" {
req.Placement = &cvm.Placement{
Zone: &s.ZoneId,
}
}
instanceChargeType := s.InstanceChargeType
if instanceChargeType == "" {
instanceChargeType = "POSTPAID_BY_HOUR"
}
if s.CdcId != "" {
instanceChargeType = "CDCPAID"
req.DedicatedClusterId = &s.CdcId
}
req.InstanceChargeType = &instanceChargeType
req.ImageId = source_image.ImageId
req.InstanceType = &s.InstanceType
// TODO: Add check for system disk size, it should be larger than image system disk size.
req.SystemDisk = &cvm.SystemDisk{
DiskType: &s.DiskType,
DiskSize: &s.DiskSize,
}
// System disk snapshot is mandatory, so if there are additional data disks,
// length will be larger than 1.
if source_image.SnapshotSet != nil && len(source_image.SnapshotSet) > 1 {
Message(state, "Use source image snapshot data disks, ignore user data disk settings", "")
var dataDisks []*cvm.DataDisk
for _, snapshot := range source_image.SnapshotSet {
if *snapshot.DiskUsage == "DATA_DISK" {
var dataDisk cvm.DataDisk
// FIXME: Currently we have no way to get original disk type
// from data disk snapshots, and we don't allow user to overwrite
// snapshot settings, and we cannot guarantee a certain hard-coded type
// is not sold out, so here we use system disk type as a workaround.
//
// Eventually, we need to allow user to overwrite snapshot disk
// settings.
dataDisk.DiskType = &s.DiskType
dataDisk.DiskSize = snapshot.DiskSize
dataDisk.SnapshotId = snapshot.SnapshotId
dataDisks = append(dataDisks, &dataDisk)
}
}
req.DataDisks = dataDisks
} else {
var dataDisks []*cvm.DataDisk
for _, disk := range s.DataDisks {
var dataDisk cvm.DataDisk
dataDisk.DiskType = &disk.DiskType
dataDisk.DiskSize = &disk.DiskSize
if disk.SnapshotId != "" {
dataDisk.SnapshotId = &disk.SnapshotId
}
dataDisks = append(dataDisks, &dataDisk)
}
req.DataDisks = dataDisks
}
req.VirtualPrivateCloud = &cvm.VirtualPrivateCloud{
VpcId: &vpc_id,
SubnetId: &subnet_id,
}
if s.AssociatePublicIpAddress {
req.InternetAccessible = &cvm.InternetAccessible{
PublicIpAssigned: &s.AssociatePublicIpAddress,
InternetMaxBandwidthOut: &s.InternetMaxBandwidthOut,
}
if s.InternetChargeType != "" {
req.InternetAccessible.InternetChargeType = &s.InternetChargeType
}
if s.BandwidthPackageId != "" {
req.InternetAccessible.BandwidthPackageId = &s.BandwidthPackageId
}
}
// Generate a unique ClientToken for each RunInstances request
clientToken := uuid.TimeOrderedUUID()
req.ClientToken = &clientToken
loginSettings := cvm.LoginSettings{}
if password != "" {
loginSettings.Password = &password
}
if config.Comm.SSHKeyPairName != "" {
loginSettings.KeyIds = []*string{&config.Comm.SSHKeyPairName}
}
req.LoginSettings = &loginSettings
req.SecurityGroupIds = []*string{&security_group_id}
req.InstanceName = &s.InstanceName
req.HostName = &s.HostName
req.UserData = &userData
req.CamRoleName = &s.CamRoleName
var tags []*cvm.Tag
for k, v := range s.Tags {
k := k
v := v
tags = append(tags, &cvm.Tag{
Key: &k,
Value: &v,
})
}
resourceType := "instance"
if len(tags) > 0 {
req.TagSpecification = []*cvm.TagSpecification{
{
ResourceType: &resourceType,
Tags: tags,
},
}
}
var resp *cvm.RunInstancesResponse
err = Retry(ctx, func(ctx context.Context) error {
var e error
resp, e = client.RunInstances(req)
return e
})
if err != nil {
return Halt(state, err, "Failed to run instance")
}
if len(resp.Response.InstanceIdSet) != 1 {
return Halt(state, fmt.Errorf("No instance return"), "Failed to run instance")
}
s.instanceId = *resp.Response.InstanceIdSet[0]
Message(state, fmt.Sprintf("Instance %s created, waiting for instance ready", s.instanceId), "")
err = WaitForInstance(ctx, client, s.instanceId, "RUNNING", 1800)
if err != nil {
return Halt(state, err, "Failed to wait for instance ready")
}
describeReq := cvm.NewDescribeInstancesRequest()
describeReq.InstanceIds = []*string{&s.instanceId}
var describeResp *cvm.DescribeInstancesResponse
err = Retry(ctx, func(ctx context.Context) error {
var e error
describeResp, e = client.DescribeInstances(describeReq)
return e
})
if err != nil {
return Halt(state, err, "Failed to wait for instance ready")
}
state.Put("instance", describeResp.Response.InstanceSet[0])
// instance_id is the generic term used so that users can have access to the
// instance id inside of the provisioners, used in step_provision.
state.Put("instance_id", s.instanceId)
Message(state, s.instanceId, "Instance created")
return multistep.ActionContinue
}
func (s *stepRunInstance) getUserData(state multistep.StateBag) (string, error) {
userData := s.UserData
if userData == "" && s.UserDataFile != "" {
data, err := ioutil.ReadFile(s.UserDataFile)
if err != nil {
return "", err
}
userData = string(data)
}
userData = base64.StdEncoding.EncodeToString([]byte(userData))
log.Printf(fmt.Sprintf("[DEBUG]getUserData: user_data: %s", userData))
return userData, nil
}
func (s *stepRunInstance) Cleanup(state multistep.StateBag) {
if s.instanceId == "" {
return
}
ctx := context.TODO()
client := state.Get("cvm_client").(*cvm.Client)
SayClean(state, "instance")
req := cvm.NewTerminateInstancesRequest()
req.InstanceIds = []*string{&s.instanceId}
err := Retry(ctx, func(ctx context.Context) error {
_, e := client.TerminateInstances(req)
return e
})
if err != nil {
Error(state, err, fmt.Sprintf("Failed to terminate instance(%s), please delete it manually", s.instanceId))
}
}