forked from aliyun/terraform-provider-alicloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_alicloud_kvstore_instance.go
344 lines (305 loc) · 11 KB
/
resource_alicloud_kvstore_instance.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
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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package alicloud
import (
"fmt"
"strings"
"time"
"strconv"
"github.com/aliyun/alibaba-cloud-sdk-go/services/r-kvstore"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-alicloud/alicloud/connectivity"
)
func resourceAlicloudKVStoreInstance() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudKVStoreInstanceCreate,
Read: resourceAlicloudKVStoreInstanceRead,
Update: resourceAlicloudKVStoreInstanceUpdate,
Delete: resourceAlicloudKVStoreInstanceDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_name": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ValidateFunc: validateRKVInstanceName,
},
"password": &schema.Schema{
Type: schema.TypeString,
Required: true,
Sensitive: true,
ValidateFunc: validateRKVPassword,
},
"instance_class": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"availability_zone": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Computed: true,
},
"instance_charge_type": &schema.Schema{
Type: schema.TypeString,
ValidateFunc: validateInstanceChargeType,
Optional: true,
ForceNew: true,
Default: PostPaid,
},
"period": &schema.Schema{
Type: schema.TypeInt,
ValidateFunc: validateAllowedIntValue([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 24, 36}),
Optional: true,
Default: 1,
DiffSuppressFunc: rkvPostPaidDiffSuppressFunc,
},
"instance_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
Default: "Redis",
ValidateFunc: validateAllowedStringValue([]string{
"Memcache",
"Redis",
}),
},
"vswitch_id": &schema.Schema{
Type: schema.TypeString,
ForceNew: true,
Optional: true,
},
"engine_version": &schema.Schema{
Type: schema.TypeString,
ForceNew: true,
Optional: true,
Default: "2.8",
ValidateFunc: validateAllowedStringValue([]string{
"2.8",
"4.0",
}),
},
"connection_domain": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"private_ip": &schema.Schema{
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"backup_id": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"security_ips": &schema.Schema{
Type: schema.TypeSet,
Elem: &schema.Schema{Type: schema.TypeString},
Computed: true,
Optional: true,
},
},
}
}
func resourceAlicloudKVStoreInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kvstoreService := KvstoreService{client}
request, err := buildKVStoreCreateRequest(d, meta)
if err != nil {
return err
}
raw, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.CreateInstance(request)
})
if err != nil {
return fmt.Errorf("Error creating Alicloud db instance: %#v", err)
}
resp, _ := raw.(*r_kvstore.CreateInstanceResponse)
d.SetId(resp.InstanceId)
// wait instance status change from Creating to Normal
if err := kvstoreService.WaitForRKVInstance(d.Id(), Normal, DefaultLongTimeout); err != nil {
return fmt.Errorf("WaitForInstance %s got error: %#v", Running, err)
}
return resourceAlicloudKVStoreInstanceUpdate(d, meta)
}
func resourceAlicloudKVStoreInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kvstoreService := KvstoreService{client}
d.Partial(true)
if d.HasChange("security_ips") {
request := r_kvstore.CreateModifySecurityIpsRequest()
request.SecurityIpGroupName = "default"
request.InstanceId = d.Id()
if len(d.Get("security_ips").(*schema.Set).List()) > 0 {
request.SecurityIps = strings.Join(expandStringList(d.Get("security_ips").(*schema.Set).List())[:], COMMA_SEPARATED)
} else {
return fmt.Errorf("Security ips cannot be empty")
}
// wait instance status is Normal before modifying
if err := kvstoreService.WaitForRKVInstance(d.Id(), Normal, DefaultLongTimeout); err != nil {
return fmt.Errorf("WaitForInstance %s got error: %#v", Running, err)
}
_, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.ModifySecurityIps(request)
})
if err != nil {
return fmt.Errorf("Create security whitelist ips got an error: %#v", err)
}
d.SetPartial("security_ips")
// wait instance status is Normal after modifying
if err := kvstoreService.WaitForRKVInstance(d.Id(), Normal, DefaultLongTimeout); err != nil {
return fmt.Errorf("WaitForInstance %s got error: %#v", Running, err)
}
}
if d.IsNewResource() {
d.Partial(false)
return resourceAlicloudKVStoreInstanceRead(d, meta)
}
if d.HasChange("instance_class") {
request := r_kvstore.CreateModifyInstanceSpecRequest()
request.InstanceId = d.Id()
request.InstanceClass = d.Get("instance_class").(string)
request.EffectiveTime = "Immediately"
_, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.ModifyInstanceSpec(request)
})
if err != nil {
return err
}
// wait instance status is Normal after modifying
if err := kvstoreService.WaitForRKVInstance(d.Id(), Normal, DefaultLongTimeout); err != nil {
return fmt.Errorf("WaitForInstance %s got error: %#v", Running, err)
}
d.SetPartial("instance_class")
}
request := r_kvstore.CreateModifyInstanceAttributeRequest()
request.InstanceId = d.Id()
update := false
if d.HasChange("instance_name") {
request.InstanceName = d.Get("instance_name").(string)
update = true
d.SetPartial("instance_name")
}
if d.HasChange("password") {
request.NewPassword = d.Get("password").(string)
update = true
d.SetPartial("password")
}
if update {
// wait instance status is Normal before modifying
if err := kvstoreService.WaitForRKVInstance(d.Id(), Normal, DefaultLongTimeout); err != nil {
return fmt.Errorf("WaitForInstance %s got error: %#v", Running, err)
}
_, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.ModifyInstanceAttribute(request)
})
if err != nil {
return fmt.Errorf("ModifyRKVInstanceDescription got an error: %#v", err)
}
// wait instance status is Normal after modifying
if err := kvstoreService.WaitForRKVInstance(d.Id(), Normal, DefaultLongTimeout); err != nil {
return fmt.Errorf("WaitForInstance %s got error: %#v", Running, err)
}
}
d.Partial(false)
return resourceAlicloudKVStoreInstanceRead(d, meta)
}
func resourceAlicloudKVStoreInstanceRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kvstoreService := KvstoreService{client}
instance, err := kvstoreService.DescribeRKVInstanceById(d.Id())
if err != nil {
if NotFoundError(err) {
d.SetId("")
return nil
}
return fmt.Errorf("Error Describe rKV InstanceAttribute: %#v", err)
}
d.Set("instance_name", instance.InstanceName)
d.Set("instance_class", instance.InstanceClass)
d.Set("availability_zone", instance.ZoneId)
d.Set("instance_charge_type", instance.ChargeType)
d.Set("instance_type", instance.InstanceType)
d.Set("vswitch_id", instance.VSwitchId)
d.Set("engine_version", instance.EngineVersion)
d.Set("connection_domain", instance.ConnectionDomain)
d.Set("private_ip", instance.PrivateIp)
d.Set("security_ips", strings.Split(instance.SecurityIPList, COMMA_SEPARATED))
return nil
}
func resourceAlicloudKVStoreInstanceDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
kvstoreService := KvstoreService{client}
instance, err := kvstoreService.DescribeRKVInstanceById(d.Id())
if err != nil {
if NotFoundError(err) {
return nil
}
return fmt.Errorf("Error Describe KVStore InstanceAttribute: %#v", err)
}
if PayType(instance.ChargeType) == Prepaid {
return fmt.Errorf("At present, 'Prepaid' instance cannot be deleted and must wait it to be expired and release it automatically")
}
request := r_kvstore.CreateDeleteInstanceRequest()
request.InstanceId = d.Id()
return resource.Retry(5*time.Minute, func() *resource.RetryError {
_, err := client.WithRkvClient(func(rkvClient *r_kvstore.Client) (interface{}, error) {
return rkvClient.DeleteInstance(request)
})
if err != nil {
if IsExceptedError(err, InvalidKVStoreInstanceIdNotFound) {
return nil
}
return resource.RetryableError(fmt.Errorf("Delete KVStore instance timeout and got an error: %#v", err))
}
if _, err := kvstoreService.DescribeRKVInstanceById(d.Id()); err != nil {
if NotFoundError(err) {
return nil
}
return resource.NonRetryableError(fmt.Errorf("Error Describe KVStore InstanceAttribute: %#v", err))
}
return resource.RetryableError(fmt.Errorf("Delete KVStore instance timeout and got an error: %#v", err))
})
}
func buildKVStoreCreateRequest(d *schema.ResourceData, meta interface{}) (*r_kvstore.CreateInstanceRequest, error) {
client := meta.(*connectivity.AliyunClient)
vpcService := VpcService{client}
request := r_kvstore.CreateCreateInstanceRequest()
request.InstanceName = Trim(d.Get("instance_name").(string))
request.RegionId = client.RegionId
request.EngineVersion = Trim(d.Get("engine_version").(string))
request.InstanceClass = Trim(d.Get("instance_class").(string))
request.ChargeType = Trim(d.Get("instance_charge_type").(string))
request.Password = Trim(d.Get("password").(string))
request.BackupId = Trim(d.Get("backup_id").(string))
if PayType(request.ChargeType) == PrePaid {
request.Period = strconv.Itoa(d.Get("period").(int))
}
if zone, ok := d.GetOk("availability_zone"); ok && Trim(zone.(string)) != "" {
request.ZoneId = Trim(zone.(string))
}
request.NetworkType = strings.ToUpper(string(Classic))
if vswitchId, ok := d.GetOk("vswitch_id"); ok && vswitchId.(string) != "" {
request.VSwitchId = vswitchId.(string)
request.NetworkType = strings.ToUpper(string(Vpc))
request.PrivateIpAddress = Trim(d.Get("private_ip").(string))
// check vswitchId in zone
vsw, err := vpcService.DescribeVswitch(vswitchId.(string))
if err != nil {
return nil, fmt.Errorf("DescribeVSwitch got an error: %#v", err)
}
if request.ZoneId == "" {
request.ZoneId = vsw.ZoneId
} else if strings.Contains(request.ZoneId, MULTI_IZ_SYMBOL) {
zonestr := strings.Split(strings.SplitAfter(request.ZoneId, "(")[1], ")")[0]
if !strings.Contains(zonestr, string([]byte(vsw.ZoneId)[len(vsw.ZoneId)-1])) {
return nil, fmt.Errorf("The specified vswitch %s isn't in the multi zone %s", vsw.VSwitchId, request.ZoneId)
}
} else if request.ZoneId != vsw.ZoneId {
return nil, fmt.Errorf("The specified vswitch %s isn't in the zone %s", vsw.VSwitchId, request.ZoneId)
}
request.VpcId = vsw.VpcId
}
request.Token = buildClientToken("TF-CreateKVStoreInstance")
return request, nil
}