This repository has been archived by the owner on Jul 17, 2020. It is now read-only.
/
resource_tc_cam_user.go
399 lines (359 loc) · 11.4 KB
/
resource_tc_cam_user.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
/*
Provides a resource to manage CAM user.
Example Usage
```hcl
resource "tencentcloud_cam_user" "foo" {
name = "cam-user-test"
remark = "test"
console_login = true
use_api = true
need_reset_password = true
password = "Gail@1234"
phone_num = "12345678910"
email = "hello@test.com"
country_code = "86"
force_delete = true
}
```
Import
CAM user can be imported using the user name, e.g.
```
$ terraform import tencentcloud_cam_user.foo cam-user-test
```
*/
package tencentcloud
import (
"context"
"fmt"
"log"
"strings"
"time"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
cam "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam/v20190116"
sdkErrors "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/errors"
"github.com/terraform-providers/terraform-provider-tencentcloud/tencentcloud/internal/helper"
)
func resourceTencentCloudCamUser() *schema.Resource {
return &schema.Resource{
Create: resourceTencentCloudCamUserCreate,
Read: resourceTencentCloudCamUserRead,
Update: resourceTencentCloudCamUserUpdate,
Delete: resourceTencentCloudCamUserDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"name": {
Type: schema.TypeString,
ForceNew: true,
Required: true,
Description: "Name of the CAM user.",
},
"remark": {
Type: schema.TypeString,
Optional: true,
Default: "",
Description: "Remark of the CAM user.",
},
"force_delete": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Indicate whether to force deletes the CAM user. If set false, the API secret key will be checked and failed when exists; otherwise the user will be deleted directly. Default is false.",
},
"use_api": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Indicate whether to generate the API secret key or not.",
},
"console_login": {
Type: schema.TypeBool,
Optional: true,
Default: false,
Description: "Indicate whether the CAM user can login to the web console or not.",
},
"password": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Sensitive: true,
ValidateFunc: validateAsConfigPassword,
Description: "The password of the CAM user. Password should be at least 8 characters and no more than 32 characters, includes uppercase letters, lowercase letters, numbers and special characters. Only required when `console_login` is true. If not set, a random password will be automatically generated.",
},
"need_reset_password": {
Type: schema.TypeBool,
Optional: true,
Default: true,
Description: "Indicate whether the CAM user need to reset the password when first logins.",
},
"phone_num": {
Type: schema.TypeString,
Optional: true,
Description: "Phone number of the CAM user.",
},
"country_code": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Country code of the phone number, for example: '86'.",
},
"email": {
Type: schema.TypeString,
Optional: true,
Description: "Email of the CAM user.",
},
"uin": {
Type: schema.TypeInt,
Computed: true,
Description: "Uin of the CAM User.",
},
"secret_key": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
Description: "Secret key of the CAM user.",
},
"secret_id": {
Type: schema.TypeString,
Computed: true,
Sensitive: true,
Description: "Secret ID of the CAM user.",
},
"uid": {
Type: schema.TypeInt,
Computed: true,
Description: "ID of the CAM user.",
},
},
}
}
func resourceTencentCloudCamUserCreate(d *schema.ResourceData, meta interface{}) error {
defer logElapsed("resource.tencentcloud_cam_user.create")()
logId := getLogId(contextNil)
request := cam.NewAddUserRequest()
request.Name = helper.String(d.Get("name").(string))
//optional
if v, ok := d.GetOk("remark"); ok {
request.Remark = helper.String(v.(string))
}
if v, ok := d.GetOkExists("use_api"); ok {
apiBool := v.(bool)
apiInt := uint64(1)
if !apiBool {
apiInt = uint64(0)
}
request.UseApi = &apiInt
}
if v, ok := d.GetOkExists("console_login"); ok {
loginBool := v.(bool)
loginInt := uint64(1)
if !loginBool {
loginInt = uint64(0)
}
request.ConsoleLogin = &loginInt
}
if v, ok := d.GetOkExists("need_reset_password"); ok {
resetBool := v.(bool)
resetInt := uint64(1)
if !resetBool {
resetInt = uint64(0)
}
request.NeedResetPassword = &resetInt
}
if v, ok := d.GetOk("phone_num"); ok {
request.PhoneNum = helper.String(v.(string))
}
if v, ok := d.GetOk("country_code"); ok {
request.CountryCode = helper.String(v.(string))
}
if v, ok := d.GetOk("email"); ok {
request.Email = helper.String(v.(string))
}
if v, ok := d.GetOk("password"); ok {
request.Password = helper.String(v.(string))
}
var response *cam.AddUserResponse
err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
result, e := meta.(*TencentCloudClient).apiV3Conn.UseCamClient().AddUser(request)
if e != nil {
log.Printf("[CRITAL]%s api[%s] fail, request body [%s], reason[%s]\n",
logId, request.GetAction(), request.ToJsonString(), e.Error())
if ee, ok := e.(*sdkErrors.TencentCloudSDKError); ok {
errCode := ee.GetCode()
if strings.Contains(errCode, "SubUserNameInUse") {
return resource.NonRetryableError(e)
}
}
return retryError(e)
} else {
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n",
logId, request.GetAction(), request.ToJsonString(), result.ToJsonString())
}
response = result
return nil
})
if err != nil {
log.Printf("[CRITAL]%s create user failed, reason:%s\n", logId, err.Error())
return err
}
if response.Response.Uid == nil {
return fmt.Errorf("[TECENT_TERRAFORM_CHECK][CAM user][Create] check: CAM user id returns nil")
}
d.SetId(*response.Response.Name)
_ = d.Set("secret_key", *response.Response.SecretKey)
_ = d.Set("password", *response.Response.Password)
_ = d.Set("secret_id", *response.Response.SecretId)
//get really instance then read
ctx := context.WithValue(context.TODO(), logIdKey, logId)
camService := CamService{
client: meta.(*TencentCloudClient).apiV3Conn,
}
err = resource.Retry(readRetryTimeout, func() *resource.RetryError {
instance, e := camService.DescribeUserById(ctx, *response.Response.Name)
if e != nil {
return retryError(e)
}
if instance == nil {
return resource.RetryableError(fmt.Errorf("creation not done"))
}
return nil
})
if err != nil {
log.Printf("[CRITAL]%s wait for CAM user ready failed, reason:%s\n", logId, err.Error())
return err
}
time.Sleep(10 * time.Second)
return resourceTencentCloudCamUserRead(d, meta)
}
func resourceTencentCloudCamUserRead(d *schema.ResourceData, meta interface{}) error {
defer logElapsed("resource.tencentcloud_cam_user.read")()
defer inconsistentCheck(d, meta)()
logId := getLogId(contextNil)
ctx := context.WithValue(context.TODO(), logIdKey, logId)
deleteForce := false
if v, ok := d.GetOkExists("force_delete"); ok {
deleteForce = v.(bool)
_ = d.Set("force_delete", deleteForce)
}
userId := d.Id()
camService := CamService{
client: meta.(*TencentCloudClient).apiV3Conn,
}
var instance *cam.GetUserResponse
err := resource.Retry(readRetryTimeout, func() *resource.RetryError {
result, e := camService.DescribeUserById(ctx, userId)
if e != nil {
return retryError(e)
}
instance = result
return nil
})
if err != nil {
log.Printf("[CRITAL]%s read CAM user failed, reason:%s\n", logId, err.Error())
return err
}
if instance == nil || instance.Response == nil || instance.Response.Uid == nil {
d.SetId("")
return nil
}
_ = d.Set("name", userId)
_ = d.Set("uin", int(*instance.Response.Uin))
_ = d.Set("uid", int(*instance.Response.Uid))
_ = d.Set("remark", instance.Response.Remark)
_ = d.Set("phone_num", instance.Response.PhoneNum)
_ = d.Set("country_code", instance.Response.CountryCode)
_ = d.Set("email", instance.Response.Email)
if int(*instance.Response.ConsoleLogin) == 0 {
_ = d.Set("console_login", false)
} else if int(*instance.Response.ConsoleLogin) == 1 {
_ = d.Set("console_login", true)
}
return nil
}
func resourceTencentCloudCamUserUpdate(d *schema.ResourceData, meta interface{}) error {
defer logElapsed("resource.tencentcloud_cam_user.update")()
logId := getLogId(contextNil)
userId := d.Id()
var updateAttrs []string
request := cam.NewUpdateUserRequest()
request.Name = &userId
if d.HasChange("remark") {
request.Remark = helper.String(d.Get("remark").(string))
updateAttrs = append(updateAttrs, "remark")
}
if d.HasChange("console_login") {
consoleLogin := d.Get("console_login").(bool)
consoleLogin64 := uint64(0)
if consoleLogin {
consoleLogin64 = uint64(1)
}
request.ConsoleLogin = &consoleLogin64
updateAttrs = append(updateAttrs, "console_login")
}
if d.HasChange("need_reset_password") {
resetBool := d.Get("need_reset_password").(bool)
resetBool64 := uint64(0)
if resetBool {
resetBool64 = uint64(1)
}
request.NeedResetPassword = &resetBool64
updateAttrs = append(updateAttrs, "need_reset_password")
}
if d.HasChange("phone_num") || d.HasChange("country_code") {
request.PhoneNum = helper.String(d.Get("phone_num").(string))
updateAttrs = append(updateAttrs, "phone_num")
request.CountryCode = helper.String(d.Get("country_code").(string))
updateAttrs = append(updateAttrs, "country_code")
}
if d.HasChange("email") {
request.Email = helper.String(d.Get("email").(string))
updateAttrs = append(updateAttrs, "email")
}
if len(updateAttrs) > 0 {
err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
response, e := meta.(*TencentCloudClient).apiV3Conn.UseCamClient().UpdateUser(request)
if e != nil {
log.Printf("[CRITAL]%s api[%s] fail, request body [%s], reason[%s]\n",
logId, request.GetAction(), request.ToJsonString(), e.Error())
return retryError(e)
} else {
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n",
logId, request.GetAction(), request.ToJsonString(), response.ToJsonString())
}
return nil
})
if err != nil {
log.Printf("[CRITAL]%s update CAM user description failed, reason:%s\n", logId, err.Error())
return err
}
}
return nil
}
func resourceTencentCloudCamUserDelete(d *schema.ResourceData, meta interface{}) error {
defer logElapsed("resource.tencentcloud_cam_user.delete")()
logId := getLogId(contextNil)
userId := d.Id()
request := cam.NewDeleteUserRequest()
request.Name = &userId
//check is force delete or not
deleteForce := false
if v, ok := d.GetOkExists("force_delete"); ok {
deleteForce = v.(bool)
}
request.Force = helper.BoolToInt64Pointer(deleteForce)
err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
_, e := meta.(*TencentCloudClient).apiV3Conn.UseCamClient().DeleteUser(request)
if e != nil {
log.Printf("[CRITAL]%s reason[%s]\n", logId, e.Error())
return retryError(e)
}
return nil
})
if err != nil {
log.Printf("[CRITAL]%s delete CAM user failed, reason:%s\n", logId, err.Error())
return err
}
return nil
}