-
Notifications
You must be signed in to change notification settings - Fork 154
/
resource_huaweicloud_gaussdb_mysql_account.go
483 lines (421 loc) · 15.8 KB
/
resource_huaweicloud_gaussdb_mysql_account.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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// ---------------------------------------------------------------
// *** AUTO GENERATED CODE ***
// @Product GaussDB
// ---------------------------------------------------------------
package gaussdb
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/jmespath/go-jmespath"
"github.com/chnsz/golangsdk"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/common"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)
// @API GaussDBforMySQL POST /v3/{project_id}/instances/{instance_id}/db-users
// @API GaussDBforMySQL GET /v3/{project_id}/jobs
// @API GaussDBforMySQL PUT /v3/{project_id}/instances/{instance_id}/db-users/comment
// @API GaussDBforMySQL PUT /v3/{project_id}/instances/{instance_id}/db-users/password
// @API GaussDBforMySQL GET /v3/{project_id}/instances/{instance_id}/db-users
// @API GaussDBforMySQL DELETE /v3/{project_id}/instances/{instance_id}/db-users
func ResourceGaussDBAccount() *schema.Resource {
return &schema.Resource{
CreateContext: resourceGaussDBAccountCreate,
UpdateContext: resourceGaussDBAccountUpdate,
ReadContext: resourceGaussDBAccountRead,
DeleteContext: resourceGaussDBAccountDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(10 * time.Minute),
Update: schema.DefaultTimeout(10 * time.Minute),
Delete: schema.DefaultTimeout(10 * time.Minute),
},
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Specifies the ID of the GaussDB MySQL instance.`,
},
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: `Specifies the database username.`,
},
"password": {
Type: schema.TypeString,
Required: true,
Sensitive: true,
Description: `Specifies the password of the database user.`,
},
"host": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
Description: `Specifies the host IP address.`,
},
"description": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: `Specifies the database user remarks.`,
},
},
}
}
func resourceGaussDBAccountCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
// createGaussDBAccount: create a GaussDB MySQL account
var (
createGaussDBAccountHttpUrl = "v3/{project_id}/instances/{instance_id}/db-users"
createGaussDBAccountProduct = "gaussdb"
)
createGaussDBAccountClient, err := cfg.NewServiceClient(createGaussDBAccountProduct, region)
if err != nil {
return diag.Errorf("error creating GaussDB Client: %s", err)
}
instanceID := d.Get("instance_id").(string)
createGaussDBAccountPath := createGaussDBAccountClient.Endpoint + createGaussDBAccountHttpUrl
createGaussDBAccountPath = strings.ReplaceAll(createGaussDBAccountPath, "{project_id}",
createGaussDBAccountClient.ProjectID)
createGaussDBAccountPath = strings.ReplaceAll(createGaussDBAccountPath, "{instance_id}", instanceID)
createGaussDBAccountOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
201,
},
}
host := "%"
if h := d.Get("host").(string); h != "" {
host = h
}
createGaussDBAccountOpt.JSONBody = utils.RemoveNil(buildCreateGaussDBAccountBodyParams(d, host))
var createGaussDBAccountResp *http.Response
err = resource.RetryContext(ctx, d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
createGaussDBAccountResp, err = createGaussDBAccountClient.Request("POST", createGaussDBAccountPath,
&createGaussDBAccountOpt)
isRetry, err := handleGaussDBMysqlOperationError(err)
if isRetry {
return resource.RetryableError(err)
}
if err != nil {
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return diag.Errorf("error creating GaussDB MySQL account: %s", err)
}
createGaussDBAccountRespBody, err := utils.FlattenResponse(createGaussDBAccountResp)
if err != nil {
return diag.FromErr(err)
}
jobId, err := jmespath.Search("job_id", createGaussDBAccountRespBody)
if err != nil {
return diag.Errorf("error creating GaussDB MySQL account: job_id is not found in API response")
}
err = waitForJobComplete(ctx, createGaussDBAccountClient, d.Timeout(schema.TimeoutCreate), instanceID,
jobId.(string))
if err != nil {
return diag.FromErr(err)
}
accountName := d.Get("name").(string)
d.SetId(instanceID + "/" + accountName + "/" + host)
return resourceGaussDBAccountRead(ctx, d, meta)
}
func buildCreateGaussDBAccountBodyParams(d *schema.ResourceData, host string) map[string]interface{} {
bodyParams := map[string]interface{}{
"name": utils.ValueIngoreEmpty(d.Get("name")),
"comment": utils.ValueIngoreEmpty(d.Get("description")),
"password": utils.ValueIngoreEmpty(d.Get("password")),
"hosts": []interface{}{host},
}
param := map[string]interface{}{
"users": []interface{}{bodyParams},
}
return param
}
func resourceGaussDBAccountRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
var mErr *multierror.Error
// getGaussDBAccount: Query the GaussDB MySQL account
var (
getGaussDBAccountHttpUrl = "v3/{project_id}/instances/{instance_id}/db-users"
getGaussDBAccountProduct = "gaussdb"
)
getGaussDBAccountClient, err := cfg.NewServiceClient(getGaussDBAccountProduct, region)
if err != nil {
return diag.Errorf("error creating GaussDB Client: %s", err)
}
parts := strings.SplitN(d.Id(), "/", 3)
if len(parts) != 3 {
return diag.Errorf("invalid id format, must be <instance_id>/<name>/<host>")
}
instanceID := parts[0]
accountName := parts[1]
host := parts[2]
getGaussDBAccountBasePath := getGaussDBAccountClient.Endpoint + getGaussDBAccountHttpUrl
getGaussDBAccountBasePath = strings.ReplaceAll(getGaussDBAccountBasePath, "{project_id}",
getGaussDBAccountClient.ProjectID)
getGaussDBAccountBasePath = strings.ReplaceAll(getGaussDBAccountBasePath, "{instance_id}", instanceID)
getGaussDBAccountOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
MoreHeaders: map[string]string{
"Content-Type": "application/json",
},
}
var currentTotal int
var account interface{}
getGaussDBAccountPath := getGaussDBAccountBasePath + buildGaussDBMysqlQueryParams(currentTotal)
for {
getGaussDBAccountResp, err := getGaussDBAccountClient.Request("GET", getGaussDBAccountPath,
&getGaussDBAccountOpt)
if err != nil {
return common.CheckDeletedDiag(d, golangsdk.ErrDefault404{}, "error retrieving GaussDB MySQL account")
}
getGaussDBAccountRespBody, err := utils.FlattenResponse(getGaussDBAccountResp)
if err != nil {
return diag.FromErr(err)
}
res, pageNum := flattenGetGaussDBAccountResponseBody(getGaussDBAccountRespBody, accountName, host)
if res != nil {
account = res
break
}
total := utils.PathSearch("total_count", getGaussDBAccountRespBody, float64(0)).(float64)
currentTotal += pageNum
if currentTotal == int(total) {
break
}
getGaussDBAccountPath = getGaussDBAccountBasePath + buildGaussDBMysqlQueryParams(currentTotal)
}
if account == nil {
return common.CheckDeletedDiag(d, golangsdk.ErrDefault404{}, "")
}
mErr = multierror.Append(
mErr,
d.Set("region", region),
d.Set("instance_id", instanceID),
d.Set("name", utils.PathSearch("name", account, nil)),
d.Set("description", utils.PathSearch("comment", account, nil)),
d.Set("host", utils.PathSearch("host", account, nil)),
)
return diag.FromErr(mErr.ErrorOrNil())
}
func flattenGetGaussDBAccountResponseBody(resp interface{}, accountName, address string) (interface{}, int) {
if resp == nil {
return nil, 0
}
curJson := utils.PathSearch("users", resp, make([]interface{}, 0))
curArray := curJson.([]interface{})
for _, v := range curArray {
name := utils.PathSearch("name", v, "").(string)
host := utils.PathSearch("host", v, "").(string)
if accountName == name && address == host {
return v, len(curArray)
}
}
return nil, len(curArray)
}
func resourceGaussDBAccountUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
// updateGaussDBAccount: update the GaussDB MySQL account
var (
updateGaussDBAccountProduct = "gaussdb"
)
updateGaussDBAccountClient, err := cfg.NewServiceClient(updateGaussDBAccountProduct, region)
if err != nil {
return diag.Errorf("error creating GaussDB Client: %s", err)
}
instanceID := d.Get("instance_id").(string)
if d.HasChange("description") {
if err = updateGaussDBAccountDescription(ctx, d, updateGaussDBAccountClient, instanceID); err != nil {
return diag.FromErr(err)
}
}
if d.HasChange("password") {
if err = updateGaussDBAccountPassword(ctx, d, updateGaussDBAccountClient, instanceID); err != nil {
return diag.FromErr(err)
}
}
return resourceGaussDBAccountRead(ctx, d, meta)
}
func updateGaussDBAccountDescription(ctx context.Context, d *schema.ResourceData, client *golangsdk.ServiceClient,
instanceID string) error {
// updateGaussDBAccountDescription: update the GaussDB MySQL account description
var (
updateGaussDBAccountHttpUrl = "v3/{project_id}/instances/{instance_id}/db-users/comment"
)
updateGaussDBAccountPath := client.Endpoint + updateGaussDBAccountHttpUrl
updateGaussDBAccountPath = strings.ReplaceAll(updateGaussDBAccountPath, "{project_id}", client.ProjectID)
updateGaussDBAccountPath = strings.ReplaceAll(updateGaussDBAccountPath, "{instance_id}", instanceID)
updateGaussDBAccountOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
202,
},
}
updateGaussDBAccountOpt.JSONBody = utils.RemoveNil(buildUpdateGaussDBAccountDescriptionBodyParams(d))
updateGaussDBAccountResp, err := client.Request("PUT", updateGaussDBAccountPath, &updateGaussDBAccountOpt)
if err != nil {
return fmt.Errorf("error updating GaussDB MySQL account description: %s", err)
}
updateGaussDBAccountRespBody, err := utils.FlattenResponse(updateGaussDBAccountResp)
if err != nil {
return err
}
jobId, err := jmespath.Search("job_id", updateGaussDBAccountRespBody)
if err != nil {
return fmt.Errorf("error updating GaussDB account description: job_id is not found in API response")
}
return waitForJobComplete(ctx, client, d.Timeout(schema.TimeoutUpdate), instanceID, jobId.(string))
}
func updateGaussDBAccountPassword(ctx context.Context, d *schema.ResourceData, client *golangsdk.ServiceClient,
instanceID string) error {
// updateGaussDBAccountPassword: update the GaussDB MySQL account password
var (
updateGaussDBAccountHttpUrl = "v3/{project_id}/instances/{instance_id}/db-users/password"
)
updateGaussDBAccountPath := client.Endpoint + updateGaussDBAccountHttpUrl
updateGaussDBAccountPath = strings.ReplaceAll(updateGaussDBAccountPath, "{project_id}", client.ProjectID)
updateGaussDBAccountPath = strings.ReplaceAll(updateGaussDBAccountPath, "{instance_id}", instanceID)
updateGaussDBAccountOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
202,
},
}
updateGaussDBAccountOpt.JSONBody = utils.RemoveNil(buildUpdateGaussDBAccountPasswordBodyParams(d))
var updateGaussDBAccountResp *http.Response
var err error
err = resource.RetryContext(ctx, d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
updateGaussDBAccountResp, err = client.Request("PUT", updateGaussDBAccountPath, &updateGaussDBAccountOpt)
isRetry, err := handleGaussDBMysqlOperationError(err)
if isRetry {
return resource.RetryableError(err)
}
if err != nil {
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("error updating GaussDB account password: %s", err)
}
updateGaussDBAccountRespBody, err := utils.FlattenResponse(updateGaussDBAccountResp)
if err != nil {
return err
}
jobId, err := jmespath.Search("job_id", updateGaussDBAccountRespBody)
if err != nil {
return fmt.Errorf("error updating GaussDB account password: job_id is not found in API response")
}
return waitForJobComplete(ctx, client, d.Timeout(schema.TimeoutUpdate), instanceID, jobId.(string))
}
func buildUpdateGaussDBAccountDescriptionBodyParams(d *schema.ResourceData) map[string]interface{} {
bodyParams := map[string]interface{}{
"name": utils.ValueIngoreEmpty(d.Get("name")),
"host": utils.ValueIngoreEmpty(d.Get("host")),
"comment": utils.ValueIngoreEmpty(d.Get("description")),
}
param := map[string]interface{}{
"users": []interface{}{bodyParams},
}
return param
}
func buildUpdateGaussDBAccountPasswordBodyParams(d *schema.ResourceData) map[string]interface{} {
bodyParams := map[string]interface{}{
"name": utils.ValueIngoreEmpty(d.Get("name")),
"host": utils.ValueIngoreEmpty(d.Get("host")),
"password": utils.ValueIngoreEmpty(d.Get("password")),
}
param := map[string]interface{}{
"users": []interface{}{bodyParams},
}
return param
}
func resourceGaussDBAccountDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
cfg := meta.(*config.Config)
region := cfg.GetRegion(d)
// deleteGaussDBAccount: delete the GaussDB MySQL account
var (
deleteGaussDBAccountHttpUrl = "v3/{project_id}/instances/{instance_id}/db-users"
deleteGaussDBAccountProduct = "gaussdb"
)
deleteGaussDBAccountClient, err := cfg.NewServiceClient(deleteGaussDBAccountProduct, region)
if err != nil {
return diag.Errorf("error creating GaussDB Client: %s", err)
}
instanceID := d.Get("instance_id").(string)
deleteGaussDBAccountPath := deleteGaussDBAccountClient.Endpoint + deleteGaussDBAccountHttpUrl
deleteGaussDBAccountPath = strings.ReplaceAll(deleteGaussDBAccountPath, "{project_id}",
deleteGaussDBAccountClient.ProjectID)
deleteGaussDBAccountPath = strings.ReplaceAll(deleteGaussDBAccountPath, "{instance_id}", instanceID)
deleteGaussDBAccountOpt := golangsdk.RequestOpts{
KeepResponseBody: true,
OkCodes: []int{
202,
},
}
deleteGaussDBAccountOpt.JSONBody = utils.RemoveNil(buildDeleteGaussDBAccountBodyParams(d))
var deleteGaussDBAccountResp *http.Response
err = resource.RetryContext(ctx, d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
deleteGaussDBAccountResp, err = deleteGaussDBAccountClient.Request("DELETE",
deleteGaussDBAccountPath, &deleteGaussDBAccountOpt)
isRetry, err := handleGaussDBMysqlOperationError(err)
if isRetry {
return resource.RetryableError(err)
}
if err != nil {
return resource.NonRetryableError(err)
}
return nil
})
if err != nil {
return diag.Errorf("error deleting GaussDB MySQL account: %s", err)
}
deleteGaussDBAccountRespBody, err := utils.FlattenResponse(deleteGaussDBAccountResp)
if err != nil {
return diag.FromErr(err)
}
jobId, err := jmespath.Search("job_id", deleteGaussDBAccountRespBody)
if err != nil {
return diag.Errorf("error deleting GaussDB MySQL account: job_id is not found in API response")
}
err = waitForJobComplete(ctx, deleteGaussDBAccountClient, d.Timeout(schema.TimeoutDelete), instanceID, jobId.(string))
return nil
}
func buildDeleteGaussDBAccountBodyParams(d *schema.ResourceData) map[string]interface{} {
host := "%"
if h := d.Get("host").(string); h != "" {
host = h
}
bodyParams := map[string]interface{}{
"name": utils.ValueIngoreEmpty(d.Get("name")),
"host": host,
}
param := map[string]interface{}{
"users": []interface{}{bodyParams},
}
return param
}