Skip to content

Commit 5df2a6d

Browse files
authored
add mongo account (#1673)
* add mongo account * add changelog * update golangci
1 parent 50fc6ff commit 5df2a6d

File tree

15 files changed

+848
-142
lines changed

15 files changed

+848
-142
lines changed

.changelog/1673.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
```release-note:new-resource
2+
tencentcloud_mongodb_instance_account
3+
```

go.mod

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ require (
3838
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/clb v1.0.599
3939
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cloudaudit v1.0.544
4040
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cls v1.0.412
41-
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.634
41+
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.638
4242
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm v1.0.624
4343
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cwp v1.0.589
4444
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cynosdb v1.0.572
@@ -56,7 +56,7 @@ require (
5656
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lighthouse v1.0.413
5757
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/live v1.0.535
5858
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mariadb v1.0.532
59-
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mongodb v1.0.606
59+
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mongodb v1.0.638
6060
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/monitor v1.0.616
6161
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mps v1.0.584
6262
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/organization v1.0.540

go.sum

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,8 @@ github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.633 h1:Yj8s
538538
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.633/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
539539
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.634 h1:xSW5zhVEl+Lp7gJ9Bah1XUAzpGdLB1JrcFmJ+r16RJw=
540540
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.634/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
541+
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.638 h1:fm0Wczqg03WmgW2RKyxjV4wKin72vr/nusNbn+B6yiw=
542+
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common v1.0.638/go.mod h1:7sCQWVkxcsR38nffDW057DRGk8mUjK1Ing/EFOK8s8Y=
541543
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm v1.0.624 h1:nEZqsoqt1pEoaP9JjkHQy3/H00suCfzlHW1qOm2nYD8=
542544
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm v1.0.624/go.mod h1:+TXSVyeKwt1IhZRqKPbTREteBcP+K07Q846/ilNzLWA=
543545
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cwp v1.0.589 h1:LZihgirMH0vsaGScYexxwY0fTss9vHaSZs/YOQUVESg=
@@ -581,6 +583,8 @@ github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mariadb v1.0.532 h1:3PC
581583
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mariadb v1.0.532/go.mod h1:lb1pdGQn9dzyXmq6+NkpN4avTVRvG+ziqFtOeL5D7y4=
582584
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mongodb v1.0.606 h1:Fs1WyS5uw0MMVdKufxNSOEBe4DkybSiBkMAy1131/gg=
583585
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mongodb v1.0.606/go.mod h1:XrotKKNeP8jLqt4I9LSoIGpLt1UPd2MnLpxFNrJrts4=
586+
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mongodb v1.0.638 h1:hsR/IxB6db8s326qjF63vt2ASwP3NE5YjAqzI9tgA+8=
587+
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mongodb v1.0.638/go.mod h1:Rw+wjXNneaoEEelRqBgwQE3HDVL4lz7BHGvsP4hPv2Q=
584588
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/monitor v1.0.616 h1:+4NM1Repe514qc4H9qFuDS0IEe0TBmC5snea//YL7Kk=
585589
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/monitor v1.0.616/go.mod h1:n7vl5IwlMQS/XzBzj3UEkp1dvQorzuAMq6RYNgl/MjM=
586590
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mps v1.0.584 h1:FJxYOAolkBhXjQMWoiTek9Ag0bslcKFHyrM7w2Jsxos=

tencentcloud/provider.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,7 @@ TencentDB for MongoDB(mongodb)
435435
tencentcloud_mongodb_instance
436436
tencentcloud_mongodb_sharding_instance
437437
tencentcloud_mongodb_standby_instance
438+
tencentcloud_mongodb_instance_account
438439
439440
TencentDB for MySQL(cdb)
440441
Data Source
@@ -1558,6 +1559,7 @@ func Provider() terraform.ResourceProvider {
15581559
"tencentcloud_as_stop_instances": resourceTencentCloudAsStopInstances(),
15591560
"tencentcloud_mongodb_instance": resourceTencentCloudMongodbInstance(),
15601561
"tencentcloud_mongodb_sharding_instance": resourceTencentCloudMongodbShardingInstance(),
1562+
"tencentcloud_mongodb_instance_account": resourceTencentCloudMongodbInstanceAccount(),
15611563
"tencentcloud_dayu_cc_http_policy": resourceTencentCloudDayuCCHttpPolicy(),
15621564
"tencentcloud_dayu_cc_https_policy": resourceTencentCloudDayuCCHttpsPolicy(),
15631565
"tencentcloud_dayu_ddos_policy": resourceTencentCloudDayuDdosPolicy(),
Lines changed: 342 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,342 @@
1+
/*
2+
Provides a resource to create a mongodb instance_account
3+
4+
Example Usage
5+
6+
```hcl
7+
resource "tencentcloud_mongodb_instance_account" "instance_account" {
8+
instance_id = "cmgo-lxaz2c9b"
9+
user_name = "test_account"
10+
password = "xxxxxxxx"
11+
mongo_user_password = "xxxxxxxxx"
12+
user_desc = "test account"
13+
auth_role {
14+
mask = 0
15+
namespace = "*"
16+
}
17+
}
18+
```
19+
*/
20+
package tencentcloud
21+
22+
import (
23+
"context"
24+
"fmt"
25+
"log"
26+
"strings"
27+
28+
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
29+
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
30+
mongodb "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/mongodb/v20190725"
31+
"github.com/tencentcloudstack/terraform-provider-tencentcloud/tencentcloud/internal/helper"
32+
)
33+
34+
func resourceTencentCloudMongodbInstanceAccount() *schema.Resource {
35+
return &schema.Resource{
36+
Create: resourceTencentCloudMongodbInstanceAccountCreate,
37+
Read: resourceTencentCloudMongodbInstanceAccountRead,
38+
Update: resourceTencentCloudMongodbInstanceAccountUpdate,
39+
Delete: resourceTencentCloudMongodbInstanceAccountDelete,
40+
Schema: map[string]*schema.Schema{
41+
"instance_id": {
42+
Required: true,
43+
Type: schema.TypeString,
44+
ForceNew: true,
45+
Description: "Instance ID, the format is: cmgo-9d0p6umb.Same as the instance ID displayed in the cloud database console page.",
46+
},
47+
48+
"user_name": {
49+
Required: true,
50+
Type: schema.TypeString,
51+
ForceNew: true,
52+
Description: "The new account name. Its format requirements are as follows: character range [1,32]. Characters in the range of [A,Z], [a,z], [1,9] as well as underscore _ and dash - can be input.",
53+
},
54+
55+
"password": {
56+
Required: true,
57+
Type: schema.TypeString,
58+
Description: "New account password. Password complexity requirements are as follows: character length range [8,32]. Contains at least letters, numbers and special characters (exclamation point!, at@, pound sign #, percent sign %, caret ^, asterisk *, parentheses (), underscore _).",
59+
},
60+
61+
"mongo_user_password": {
62+
Required: true,
63+
Type: schema.TypeString,
64+
ForceNew: true,
65+
Description: "The password corresponding to the mongouser account. mongouser is the system default account, which is the password set when creating an instance.",
66+
},
67+
68+
"user_desc": {
69+
Optional: true,
70+
Type: schema.TypeString,
71+
Description: "Account remarks.",
72+
},
73+
74+
"auth_role": {
75+
Optional: true,
76+
Type: schema.TypeList,
77+
Description: "The read and write permission information of the account.",
78+
Elem: &schema.Resource{
79+
Schema: map[string]*schema.Schema{
80+
"mask": {
81+
Type: schema.TypeInt,
82+
Required: true,
83+
Description: "Permission information of the current account. 0: No permission. 1: read-only. 2: Write only. 3: Read and write.",
84+
},
85+
"namespace": {
86+
Type: schema.TypeString,
87+
Required: true,
88+
Description: "Refers to the name of the database with the current account permissions.*: Indicates all databases. db.name: Indicates the database of a specific name.",
89+
},
90+
},
91+
},
92+
},
93+
},
94+
}
95+
}
96+
97+
func resourceTencentCloudMongodbInstanceAccountCreate(d *schema.ResourceData, meta interface{}) error {
98+
defer logElapsed("resource.tencentcloud_mongodb_instance_account.create")()
99+
defer inconsistentCheck(d, meta)()
100+
101+
logId := getLogId(contextNil)
102+
103+
var (
104+
request = mongodb.NewCreateAccountUserRequest()
105+
response = mongodb.NewCreateAccountUserResponse()
106+
instanceId string
107+
userName string
108+
)
109+
if v, ok := d.GetOk("instance_id"); ok {
110+
instanceId = v.(string)
111+
request.InstanceId = helper.String(v.(string))
112+
}
113+
114+
if v, ok := d.GetOk("user_name"); ok {
115+
userName = v.(string)
116+
request.UserName = helper.String(v.(string))
117+
}
118+
119+
if v, ok := d.GetOk("password"); ok {
120+
request.Password = helper.String(v.(string))
121+
}
122+
123+
if v, ok := d.GetOk("mongo_user_password"); ok {
124+
request.MongoUserPassword = helper.String(v.(string))
125+
}
126+
127+
if v, ok := d.GetOk("user_desc"); ok {
128+
request.UserDesc = helper.String(v.(string))
129+
}
130+
131+
if v, ok := d.GetOk("auth_role"); ok {
132+
for _, item := range v.([]interface{}) {
133+
dMap := item.(map[string]interface{})
134+
auth := mongodb.Auth{}
135+
if v, ok := dMap["mask"]; ok {
136+
auth.Mask = helper.IntInt64(v.(int))
137+
}
138+
if v, ok := dMap["namespace"]; ok {
139+
auth.NameSpace = helper.String(v.(string))
140+
}
141+
request.AuthRole = append(request.AuthRole, &auth)
142+
}
143+
}
144+
145+
err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
146+
result, e := meta.(*TencentCloudClient).apiV3Conn.UseMongodbClient().CreateAccountUser(request)
147+
if e != nil {
148+
return retryError(e)
149+
} else {
150+
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n", logId, request.GetAction(), request.ToJsonString(), result.ToJsonString())
151+
}
152+
response = result
153+
return nil
154+
})
155+
if err != nil {
156+
log.Printf("[CRITAL]%s create mongodb instanceAccount failed, reason:%+v", logId, err)
157+
return err
158+
}
159+
160+
d.SetId(instanceId + FILED_SP + userName)
161+
162+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
163+
service := MongodbService{client: meta.(*TencentCloudClient).apiV3Conn}
164+
165+
if response != nil && response.Response != nil {
166+
if err = service.DescribeAsyncRequestInfo(ctx, helper.UInt64ToStr(*response.Response.FlowId)); err != nil {
167+
return err
168+
}
169+
}
170+
171+
return resourceTencentCloudMongodbInstanceAccountRead(d, meta)
172+
}
173+
174+
func resourceTencentCloudMongodbInstanceAccountRead(d *schema.ResourceData, meta interface{}) error {
175+
defer logElapsed("resource.tencentcloud_mongodb_instance_account.read")()
176+
defer inconsistentCheck(d, meta)()
177+
178+
logId := getLogId(contextNil)
179+
180+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
181+
182+
service := MongodbService{client: meta.(*TencentCloudClient).apiV3Conn}
183+
184+
idSplit := strings.Split(d.Id(), FILED_SP)
185+
if len(idSplit) != 2 {
186+
return fmt.Errorf("id is broken,%s", d.Id())
187+
}
188+
instanceId := idSplit[0]
189+
userName := idSplit[1]
190+
191+
instanceAccount, err := service.DescribeMongodbInstanceAccountById(ctx, instanceId, userName)
192+
if err != nil {
193+
return err
194+
}
195+
196+
if instanceAccount == nil {
197+
d.SetId("")
198+
log.Printf("[WARN]%s resource `MongodbInstanceAccount` [%s] not found, please check if it has been deleted.\n", logId, d.Id())
199+
return nil
200+
}
201+
202+
_ = d.Set("instance_id", instanceId)
203+
204+
if instanceAccount.UserName != nil {
205+
_ = d.Set("user_name", instanceAccount.UserName)
206+
}
207+
208+
if instanceAccount.UserDesc != nil {
209+
_ = d.Set("user_desc", instanceAccount.UserDesc)
210+
}
211+
212+
if instanceAccount.AuthRole != nil {
213+
authRoleList := []interface{}{}
214+
for _, authRole := range instanceAccount.AuthRole {
215+
authRoleMap := map[string]interface{}{}
216+
217+
if authRole.Mask != nil {
218+
authRoleMap["mask"] = authRole.Mask
219+
}
220+
221+
if authRole.NameSpace != nil {
222+
authRoleMap["namespace"] = authRole.NameSpace
223+
}
224+
225+
authRoleList = append(authRoleList, authRoleMap)
226+
}
227+
228+
_ = d.Set("auth_role", authRoleList)
229+
230+
}
231+
232+
return nil
233+
}
234+
235+
func resourceTencentCloudMongodbInstanceAccountUpdate(d *schema.ResourceData, meta interface{}) error {
236+
defer logElapsed("resource.tencentcloud_mongodb_instance_account.update")()
237+
defer inconsistentCheck(d, meta)()
238+
239+
logId := getLogId(contextNil)
240+
241+
request := mongodb.NewSetAccountUserPrivilegeRequest()
242+
243+
idSplit := strings.Split(d.Id(), FILED_SP)
244+
if len(idSplit) != 2 {
245+
return fmt.Errorf("id is broken,%s", d.Id())
246+
}
247+
instanceId := idSplit[0]
248+
userName := idSplit[1]
249+
250+
request.InstanceId = &instanceId
251+
request.UserName = &userName
252+
253+
immutableArgs := []string{"user_desc"}
254+
255+
for _, v := range immutableArgs {
256+
if d.HasChange(v) {
257+
return fmt.Errorf("argument `%s` cannot be changed", v)
258+
}
259+
}
260+
261+
if d.HasChange("auth_role") {
262+
if v, ok := d.GetOk("auth_role"); ok {
263+
for _, item := range v.([]interface{}) {
264+
auth := mongodb.Auth{}
265+
dMap := item.(map[string]interface{})
266+
if v, ok := dMap["mask"]; ok {
267+
auth.Mask = helper.IntInt64(v.(int))
268+
}
269+
if v, ok := dMap["namespace"]; ok {
270+
auth.NameSpace = helper.String(v.(string))
271+
}
272+
request.AuthRole = append(request.AuthRole, &auth)
273+
}
274+
}
275+
276+
var response *mongodb.SetAccountUserPrivilegeResponse
277+
err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
278+
result, e := meta.(*TencentCloudClient).apiV3Conn.UseMongodbClient().SetAccountUserPrivilege(request)
279+
if e != nil {
280+
return retryError(e)
281+
} else {
282+
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n", logId, request.GetAction(), request.ToJsonString(), result.ToJsonString())
283+
}
284+
response = result
285+
return nil
286+
})
287+
if err != nil {
288+
log.Printf("[CRITAL]%s update mongodb instanceAccount failed, reason:%+v", logId, err)
289+
return err
290+
}
291+
292+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
293+
service := MongodbService{client: meta.(*TencentCloudClient).apiV3Conn}
294+
295+
if response != nil && response.Response != nil {
296+
if err = service.DescribeAsyncRequestInfo(ctx, helper.UInt64ToStr(*response.Response.FlowId)); err != nil {
297+
return err
298+
}
299+
}
300+
}
301+
302+
if d.HasChange("password") {
303+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
304+
service := MongodbService{client: meta.(*TencentCloudClient).apiV3Conn}
305+
password := d.Get("password").(string)
306+
err := service.ResetInstancePassword(ctx, instanceId, userName, password)
307+
if err != nil {
308+
return err
309+
}
310+
311+
d.SetPartial("password")
312+
}
313+
314+
return resourceTencentCloudMongodbInstanceAccountRead(d, meta)
315+
}
316+
317+
func resourceTencentCloudMongodbInstanceAccountDelete(d *schema.ResourceData, meta interface{}) error {
318+
defer logElapsed("resource.tencentcloud_mongodb_instance_account.delete")()
319+
defer inconsistentCheck(d, meta)()
320+
321+
logId := getLogId(contextNil)
322+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
323+
324+
service := MongodbService{client: meta.(*TencentCloudClient).apiV3Conn}
325+
idSplit := strings.Split(d.Id(), FILED_SP)
326+
if len(idSplit) != 2 {
327+
return fmt.Errorf("id is broken,%s", d.Id())
328+
}
329+
instanceId := idSplit[0]
330+
userName := idSplit[1]
331+
332+
var mongoUserPassword string
333+
if v, ok := d.GetOk("mongo_user_password"); ok {
334+
mongoUserPassword = v.(string)
335+
}
336+
337+
if err := service.DeleteMongodbInstanceAccountById(ctx, instanceId, userName, mongoUserPassword); err != nil {
338+
return err
339+
}
340+
341+
return nil
342+
}

0 commit comments

Comments
 (0)