Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/cam access key #2182

Merged
merged 7 commits into from
Oct 11, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .changelog/2182.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:new-resource
tencentcloud_cam_access_key
```
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ require (
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/apigateway v1.0.736
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/apm v1.0.624
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/as v1.0.756
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam v1.0.409
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam v1.0.760
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cat v1.0.760
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cbs v1.0.591
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cdb v1.0.699
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -784,6 +784,8 @@ github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/as v1.0.756 h1:dx4aBdOW
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/as v1.0.756/go.mod h1:lwWeh6aHg6GlttTMp+VIVtpZOtmpP6DQnnYWpyYW37Y=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam v1.0.409 h1:ToZpNh78SVdKakkeR9YV1a65tjtC4NJl+hrJqTuhO3g=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam v1.0.409/go.mod h1:U24yUxCDruJLayOsP/onO2E/7+9ljeNsNO+phu+PeiM=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam v1.0.760 h1:Ky9dRsTL2HXKWUrTFpQFZWQ1TrM+o+P35kczR7thalo=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam v1.0.760/go.mod h1:AAfdrxknvUedvigxbbzKQLxN+1EG5NPbytpiqmfuFvU=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cat v1.0.520 h1:n4FN0PI+1MVWi+RGQbD/cElXjquZQK0K1h1Z1nNWNWw=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cat v1.0.520/go.mod h1:gzI+2Qd/iUfPPQQjW30k0G3mJ3m7tXeXrydJMm8jsOo=
github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cat v1.0.760 h1:oGY4IigfIw0iQKh3/cOY29KBeEeFbvJft69e0beyfdI=
Expand Down
2 changes: 2 additions & 0 deletions tencentcloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ Cloud Access Management(CAM)
tencentcloud_cam_role_sso
tencentcloud_cam_service_linked_role
tencentcloud_cam_mfa_flag
tencentcloud_cam_access_key
tencentcloud_cam_user_saml_config
tencentcloud_cam_user_permission_boundary_attachment

Expand Down Expand Up @@ -2660,6 +2661,7 @@ func Provider() *schema.Provider {
"tencentcloud_cam_saml_provider": resourceTencentCloudCamSAMLProvider(),
"tencentcloud_cam_service_linked_role": resourceTencentCloudCamServiceLinkedRole(),
"tencentcloud_cam_mfa_flag": resourceTencentCloudCamMfaFlag(),
"tencentcloud_cam_access_key": resourceTencentCloudCamAccessKey(),
"tencentcloud_cam_user_saml_config": resourceTencentCloudCamUserSamlConfig(),
"tencentcloud_cam_user_permission_boundary_attachment": resourceTencentCloudCamUserPermissionBoundaryAttachment(),
"tencentcloud_ciam_user_group": resourceTencentCloudCiamUserGroup(),
Expand Down
211 changes: 211 additions & 0 deletions tencentcloud/resource_tc_cam_access_key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
/*
Provides a resource to create a cam access_key

Example Usage

```hcl
resource "tencentcloud_cam_access_key" "access_key" {
target_uin = 100033690181
}
```
Update
```hcl
resource "tencentcloud_cam_access_key" "access_key" {
target_uin = 100033690181
status = "Inactive"
}
```
Import

cam access_key can be imported using the id, e.g.

```
terraform import tencentcloud_cam_access_key.access_key access_key_id
```
*/
package tencentcloud

import (
"context"
"fmt"
"log"
"strings"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
cam "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cam/v20190116"
"github.com/tencentcloudstack/terraform-provider-tencentcloud/tencentcloud/internal/helper"
)

func resourceTencentCloudCamAccessKey() *schema.Resource {
return &schema.Resource{
Create: resourceTencentCloudCamAccessKeyCreate,
Read: resourceTencentCloudCamAccessKeyRead,
Update: resourceTencentCloudCamAccessKeyUpdate,
Delete: resourceTencentCloudCamAccessKeyDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"target_uin": {
Optional: true,
Type: schema.TypeInt,
Description: "Specify user Uin, if not filled, the access key is created for the current user by default.",
},
"access_key": {
Optional: true,
Copy link
Collaborator

@andrew-tx andrew-tx Oct 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个参数是可输入的吗

Computed: true,
Type: schema.TypeString,
Description: "Access_key is the access key identification, required when updating.",
},
"secret_access_key": {
Computed: true,
Type: schema.TypeString,
Description: "Access key (key is only visible when created, please keep it properly).",
},
"status": {
Optional: true,
Computed: true,
Type: schema.TypeString,
Description: "Key status, activated (Active) or inactive (Inactive), required when updating.",
},
},
}
}

func resourceTencentCloudCamAccessKeyCreate(d *schema.ResourceData, meta interface{}) error {
defer logElapsed("resource.tencentcloud_cam_access_key.create")()
defer inconsistentCheck(d, meta)()

logId := getLogId(contextNil)

var (
request = cam.NewCreateAccessKeyRequest()
response = cam.NewCreateAccessKeyResponse()
targetUin int64
)
if v, ok := d.GetOkExists("target_uin"); ok {
targetUin = int64(v.(int))
request.TargetUin = helper.IntUint64(v.(int))
}

err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
result, e := meta.(*TencentCloudClient).apiV3Conn.UseCamClient().CreateAccessKey(request)
if e != nil {
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 cam AccessKey failed, reason:%+v", logId, err)
return err
}
if response == nil || response.Response == nil || response.Response.AccessKey == nil || response.Response.AccessKey.SecretAccessKey == nil {
return fmt.Errorf("CAM AccessKey id is nil")
}
d.SetId(helper.Int64ToStr(targetUin) + FILED_SP + *response.Response.AccessKey.AccessKeyId)
_ = d.Set("secret_access_key", response.Response.AccessKey.SecretAccessKey)

return resourceTencentCloudCamAccessKeyRead(d, meta)
}

func resourceTencentCloudCamAccessKeyRead(d *schema.ResourceData, meta interface{}) error {
defer logElapsed("resource.tencentcloud_cam_access_key.read")()
defer inconsistentCheck(d, meta)()

logId := getLogId(contextNil)

ctx := context.WithValue(context.TODO(), logIdKey, logId)

service := CamService{client: meta.(*TencentCloudClient).apiV3Conn}

idSplit := strings.Split(d.Id(), FILED_SP)
if len(idSplit) != 2 {
return fmt.Errorf("id is broken,%s", idSplit)
}
uin := idSplit[0]
accessKey := idSplit[1]

AccessKey, err := service.DescribeCamAccessKeyById(ctx, helper.StrToUInt64(uin), accessKey)
if err != nil {
return err
}

if AccessKey == nil {
d.SetId("")
log.Printf("[WARN]%s resource `CamAccessKey` [%s] not found, please check if it has been deleted.\n", logId, d.Id())
return nil
}

if AccessKey.AccessKeyId != nil {
_ = d.Set("access_key", AccessKey.AccessKeyId)
}
if AccessKey.Status != nil {
_ = d.Set("status", AccessKey.Status)
}
_ = d.Set("target_uin", helper.StrToUInt64(uin))

return nil
}

func resourceTencentCloudCamAccessKeyUpdate(d *schema.ResourceData, meta interface{}) error {
defer logElapsed("resource.tencentcloud_cam_access_key.update")()
defer inconsistentCheck(d, meta)()

logId := getLogId(contextNil)

request := cam.NewUpdateAccessKeyRequest()

idSplit := strings.Split(d.Id(), FILED_SP)
if len(idSplit) != 2 {
return fmt.Errorf("id is broken,%s", idSplit)
}
uin := idSplit[0]
accessKey := idSplit[1]
request.TargetUin = helper.StrToUint64Point(uin)
request.AccessKeyId = &accessKey

if d.HasChange("status") {
if v, ok := d.GetOkExists("status"); ok {
request.Status = helper.String(v.(string))
}
}

err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
result, e := meta.(*TencentCloudClient).apiV3Conn.UseCamClient().UpdateAccessKey(request)
if e != nil {
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())
}
return nil
})
if err != nil {
log.Printf("[CRITAL]%s update cam AccessKey failed, reason:%+v", logId, err)
return err
}

return resourceTencentCloudCamAccessKeyRead(d, meta)
}

func resourceTencentCloudCamAccessKeyDelete(d *schema.ResourceData, meta interface{}) error {
defer logElapsed("resource.tencentcloud_cam_access_key.delete")()
defer inconsistentCheck(d, meta)()

logId := getLogId(contextNil)
ctx := context.WithValue(context.TODO(), logIdKey, logId)

service := CamService{client: meta.(*TencentCloudClient).apiV3Conn}
idSplit := strings.Split(d.Id(), FILED_SP)
uin := idSplit[0]
accessKey := idSplit[1]

if err := service.DeleteCamAccessKeyById(ctx, uin, accessKey); err != nil {
return err
}

return nil
}
54 changes: 54 additions & 0 deletions tencentcloud/resource_tc_cam_access_key_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package tencentcloud

import (
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestAccTencentCloudCamAccessKeyResource_basic(t *testing.T) {
t.Parallel()
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccCamAccessKey,
Check: resource.ComposeTestCheckFunc(resource.TestCheckResourceAttrSet("tencentcloud_cam_access_key.access_key", "id"),
resource.TestCheckResourceAttr("tencentcloud_cam_access_key.access_key", "target_uin", "100033690181"),
),
},
{
Config: testAccCamAccessKeyUpdate,
Check: resource.ComposeTestCheckFunc(resource.TestCheckResourceAttrSet("tencentcloud_cam_access_key.access_key", "id"),
resource.TestCheckResourceAttr("tencentcloud_cam_access_key.access_key", "target_uin", "100033690181"),
resource.TestCheckResourceAttr("tencentcloud_cam_access_key.access_key", "status", "Inactive"),
),
},
{
ResourceName: "tencentcloud_cam_access_key.access_key",
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{"secret_access_key"},
},
},
})
}

const testAccCamAccessKey = `

resource "tencentcloud_cam_access_key" "access_key" {
target_uin = 100033690181
}

`
const testAccCamAccessKeyUpdate = `

resource "tencentcloud_cam_access_key" "access_key" {
target_uin = 100033690181
status = "Inactive"
}

`
57 changes: 57 additions & 0 deletions tencentcloud/service_tencentcloud_cam.go
Original file line number Diff line number Diff line change
Expand Up @@ -1385,6 +1385,63 @@ func (me *CamService) DescribeCamMfaFlagById(ctx context.Context, id uint64) (lo
return
}

func (me *CamService) DescribeCamAccessKeyById(ctx context.Context, targetUin uint64, accessKey string) (AccessKey *cam.AccessKey, errRet error) {
logId := getLogId(ctx)

request := cam.NewListAccessKeysRequest()
request.TargetUin = &targetUin

defer func() {
if errRet != nil {
log.Printf("[CRITAL]%s api[%s] fail, request body [%s], reason[%s]\n", logId, request.GetAction(), request.ToJsonString(), errRet.Error())
}
}()

ratelimit.Check(request.GetAction())

response, err := me.client.UseCamClient().ListAccessKeys(request)
if err != nil {
errRet = err
return
}
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n", logId, request.GetAction(), request.ToJsonString(), response.ToJsonString())

if response == nil || response.Response == nil || len(response.Response.AccessKeys) < 1 {
return
}

for _, v := range response.Response.AccessKeys {
if *v.AccessKeyId == accessKey {
AccessKey = v
}
}
return
}

func (me *CamService) DeleteCamAccessKeyById(ctx context.Context, uin, accessKeyId string) (errRet error) {
logId := getLogId(ctx)

request := cam.NewDeleteAccessKeyRequest()
request.AccessKeyId = &accessKeyId
request.TargetUin = helper.StrToUint64Point(uin)
defer func() {
if errRet != nil {
log.Printf("[CRITAL]%s api[%s] fail, request body [%s], reason[%s]\n", logId, request.GetAction(), request.ToJsonString(), errRet.Error())
}
}()

ratelimit.Check(request.GetAction())

response, err := me.client.UseCamClient().DeleteAccessKey(request)
if err != nil {
errRet = err
return
}
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n", logId, request.GetAction(), request.ToJsonString(), response.ToJsonString())

return
}

func (me *CamService) DescribeCamUserPermissionBoundaryById(ctx context.Context, targetUin string) (UserPermissionBoundary *cam.GetUserPermissionBoundaryResponse, errRet error) {
logId := getLogId(ctx)

Expand Down
Loading