Skip to content

Commit 7f009c8

Browse files
committed
add data source data_source_tc_kms_key
1 parent 41fd6bf commit 7f009c8

File tree

2 files changed

+296
-0
lines changed

2 files changed

+296
-0
lines changed
Lines changed: 231 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,231 @@
1+
/*
2+
Use this data source to query detailed information of KMS key
3+
4+
Example Usage
5+
6+
```hcl
7+
data "tencentcloud_kms_key" "foo" {
8+
search_key_alias = "test"
9+
key_state = "All"
10+
origin = "TENCENT_KMS"
11+
key_usage = "ALL"
12+
}
13+
```
14+
*/
15+
package tencentcloud
16+
17+
import (
18+
"context"
19+
"log"
20+
21+
"github.com/tencentcloudstack/terraform-provider-tencentcloud/tencentcloud/internal/helper"
22+
23+
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
24+
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
25+
kms "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/kms/v20190118"
26+
)
27+
28+
func dataSourceTencentCloudKmsKey() *schema.Resource {
29+
return &schema.Resource{
30+
Read: dataSourceTencentCloudKmsKeyRead,
31+
Schema: map[string]*schema.Schema{
32+
"role": {
33+
Type: schema.TypeInt,
34+
Optional: true,
35+
ValidateFunc: validateAllowedIntValue([]int{0, 1}),
36+
Default: 0,
37+
Description: "Role of the CMK creator.`0` - created by user, `1` - created by cloud product.Default value is `0`.",
38+
},
39+
"order_type": {
40+
Type: schema.TypeInt,
41+
Optional: true,
42+
ValidateFunc: validateAllowedIntValue([]int{0, 1}),
43+
Default: 0,
44+
Description: "Order to sort the CMK create time.`0` - desc, `1` - asc.Default value is `0`.",
45+
},
46+
"key_state": {
47+
Type: schema.TypeString,
48+
Optional: true,
49+
ValidateFunc: validateAllowedStringValue(KMS_KEY_STATE_FILTER),
50+
Default: KMS_KEY_STATE_ALL,
51+
Description: "State of CMK.Available values include `All`, `Enabled`, `Disabled`, `PendingDelete`, `PendingImport`, `Archived`.",
52+
},
53+
"search_key_alias": {
54+
Type: schema.TypeString,
55+
Optional: true,
56+
Description: "Words used to match the results,and the words can be: key_id and alias.",
57+
},
58+
"origin": {
59+
Type: schema.TypeString,
60+
Optional: true,
61+
ValidateFunc: validateAllowedStringValue(KMS_ORIGIN_FILTER),
62+
Default: KMS_ORIGIN_ALL,
63+
Description: "Origin of CMK.`TENCENT_KMS` - CMK created by KMS, `EXTERNAL` - CMK imported by user, `ALL` - All CMK.Default value is `ALL`.",
64+
},
65+
"key_usage": {
66+
Type: schema.TypeString,
67+
Optional: true,
68+
ValidateFunc: validateAllowedStringValue(KMS_KEY_USAGE_FILTER),
69+
Default: KMS_KEY_USAGE_ENCRYPT_DECRYPT,
70+
Description: "Usage of CMK.Available values include `ALL`, `ENCRYPT_DECRYPT`, `ASYMMETRIC_DECRYPT_RSA_2048`, `ASYMMETRIC_DECRYPT_SM2`, `ASYMMETRIC_SIGN_VERIFY_SM2`, `ASYMMETRIC_SIGN_VERIFY_RSA_2048`, `ASYMMETRIC_SIGN_VERIFY_ECC`.Default value is `ENCRYPT_DECRYPT`.",
71+
},
72+
"tags": {
73+
Type: schema.TypeMap,
74+
Optional: true,
75+
Description: "Tags to filter CMK.",
76+
},
77+
"key_list": {
78+
Type: schema.TypeList,
79+
Computed: true,
80+
Description: "A list of KMS keys.",
81+
Elem: &schema.Resource{
82+
Schema: map[string]*schema.Schema{
83+
"key_id": {
84+
Type: schema.TypeString,
85+
Computed: true,
86+
Description: "ID of CMK.",
87+
},
88+
"alias": {
89+
Type: schema.TypeString,
90+
Computed: true,
91+
Description: "Name of CMK.",
92+
},
93+
"create_time": {
94+
Type: schema.TypeString,
95+
Computed: true,
96+
Description: "Create time of CMK.",
97+
},
98+
"description": {
99+
Type: schema.TypeString,
100+
Computed: true,
101+
Description: "Description of CMK.",
102+
},
103+
"key_state": {
104+
Type: schema.TypeString,
105+
Computed: true,
106+
Description: "State of CMK.Available values include `Enabled`, `Disabled`, `PendingDelete`, `PendingImport`, `Archived`.",
107+
},
108+
"key_usage": {
109+
Type: schema.TypeString,
110+
Computed: true,
111+
Description: "Usage of CMK.Available values include `ENCRYPT_DECRYPT`, `ASYMMETRIC_DECRYPT_RSA_2048`, `ASYMMETRIC_DECRYPT_SM2`, `ASYMMETRIC_SIGN_VERIFY_SM2`, `ASYMMETRIC_SIGN_VERIFY_RSA_2048`, `ASYMMETRIC_SIGN_VERIFY_ECC`.",
112+
},
113+
"creator_uin": {
114+
Type: schema.TypeInt,
115+
Computed: true,
116+
Description: "Uin of CMK Creator.",
117+
},
118+
"key_rotation_enabled": {
119+
Type: schema.TypeBool,
120+
Computed: true,
121+
Description: "Specify whether to enable key rotation.",
122+
},
123+
"owner": {
124+
Type: schema.TypeString,
125+
Computed: true,
126+
Description: "Creator of CMK.",
127+
},
128+
"next_rotate_time": {
129+
Type: schema.TypeString,
130+
Computed: true,
131+
Description: "Next rotate time of CMK when key_rotation_enabled is true.",
132+
},
133+
"deletion_date": {
134+
Type: schema.TypeString,
135+
Computed: true,
136+
Description: "Delete time of CMK.`1970-01-01T12:00:00Z` means it does not delete.",
137+
},
138+
"origin": {
139+
Type: schema.TypeString,
140+
Computed: true,
141+
Description: "Origin of CMK.`TENCENT_KMS` - CMK created by KMS, `EXTERNAL` - CMK imported by user.",
142+
},
143+
"valid_to": {
144+
Type: schema.TypeString,
145+
Computed: true,
146+
Description: "Valid when Origin is EXTERNAL, it means the effective date of the key material.`1970-01-01T12:00:00Z` means it does not expire.",
147+
},
148+
},
149+
},
150+
},
151+
},
152+
}
153+
}
154+
155+
func dataSourceTencentCloudKmsKeyRead(d *schema.ResourceData, meta interface{}) error {
156+
defer logElapsed("data_source.tencentcloud_kms_key.read")()
157+
158+
logId := getLogId(contextNil)
159+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
160+
161+
param := make(map[string]interface{})
162+
if v, ok := d.GetOk("role"); ok {
163+
param["role"] = v.(int)
164+
}
165+
if v, ok := d.GetOk("order_type"); ok {
166+
param["order_type"] = v.(int)
167+
}
168+
if v, ok := d.GetOk("key_state"); ok {
169+
keyState := v.(string)
170+
param["key_state"] = KMS_KEY_STATE_MAP[keyState]
171+
}
172+
if v, ok := d.GetOk("search_key_alias"); ok {
173+
param["search_key_alias"] = v.(string)
174+
}
175+
if v, ok := d.GetOk("origin"); ok {
176+
param["origin"] = v.(string)
177+
}
178+
if v, ok := d.GetOk("key_usage"); ok {
179+
param["key_usage"] = v.(string)
180+
}
181+
if tags := helper.GetTags(d, "tags"); len(tags) > 0 {
182+
param["tag_filter"] = tags
183+
}
184+
185+
kmsService := KmsService{
186+
client: meta.(*TencentCloudClient).apiV3Conn,
187+
}
188+
var keys []*kms.KeyMetadata
189+
err := resource.Retry(readRetryTimeout, func() *resource.RetryError {
190+
results, e := kmsService.DescribeKeysByFilter(ctx, param)
191+
if e != nil {
192+
return retryError(e)
193+
}
194+
keys = results
195+
return nil
196+
})
197+
if err != nil {
198+
log.Printf("[CRITAL]%s read KMS keys failed, reason:%+v", logId, err)
199+
return err
200+
}
201+
keyList := make([]map[string]interface{}, 0, len(keys))
202+
ids := make([]string, 0, len(keys))
203+
for _, key := range keys {
204+
mapping := map[string]interface{}{
205+
"key_id": key.KeyId,
206+
"alias": key.Alias,
207+
"create_time": helper.FormatUnixTime(*key.CreateTime),
208+
"description": key.Description,
209+
"key_state": key.KeyState,
210+
"key_usage": key.KeyUsage,
211+
"creator_uin": key.CreatorUin,
212+
"key_rotation_enabled": key.KeyRotationEnabled,
213+
"owner": key.Owner,
214+
"deletion_date": helper.FormatUnixTime(*key.DeletionDate),
215+
"origin": key.Origin,
216+
"valid_to": helper.FormatUnixTime(*key.ValidTo),
217+
}
218+
if *key.KeyRotationEnabled {
219+
mapping["next_rotate_time"] = helper.FormatUnixTime(*key.NextRotateTime)
220+
}
221+
keyList = append(keyList, mapping)
222+
ids = append(ids, *key.KeyId)
223+
}
224+
225+
d.SetId(helper.DataResourceIdsHash(ids))
226+
if e := d.Set("key_list", keyList); e != nil {
227+
log.Printf("[CRITAL]%s provider set KMS key list fail, reason:%+v", logId, e)
228+
return e
229+
}
230+
return nil
231+
}
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
package tencentcloud
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
8+
"github.com/hashicorp/terraform-plugin-sdk/terraform"
9+
10+
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
11+
)
12+
13+
func TestAccTencentCloudKmsKeyDataSource(t *testing.T) {
14+
dataSourceName := "data.tencentcloud_kms_key.test"
15+
rName := fmt.Sprintf("tf-testacc-kms-key-%s", acctest.RandString(13))
16+
17+
resource.Test(t, resource.TestCase{
18+
PreCheck: func() { testAccPreCheck(t) },
19+
Providers: testAccProviders,
20+
Steps: []resource.TestStep{
21+
{
22+
Config: testAccDataSourceKmsKeyConfig(rName),
23+
Check: resource.ComposeTestCheckFunc(
24+
testAccDataSourceKmsKeyCheck(dataSourceName),
25+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.key_id"),
26+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.create_time"),
27+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.description"),
28+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.key_state"),
29+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.key_usage"),
30+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.creator_uin"),
31+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.key_rotation_enabled"),
32+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.owner"),
33+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.next_rotate_time"),
34+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.origin"),
35+
resource.TestCheckResourceAttrSet(dataSourceName, "key_list.0.valid_to"),
36+
),
37+
},
38+
},
39+
})
40+
}
41+
42+
func testAccDataSourceKmsKeyCheck(name string) resource.TestCheckFunc {
43+
return func(s *terraform.State) error {
44+
_, ok := s.RootModule().Resources[name]
45+
if !ok {
46+
return fmt.Errorf("root module has no resource called %s", name)
47+
}
48+
49+
return nil
50+
}
51+
}
52+
53+
func testAccDataSourceKmsKeyConfig(rName string) string {
54+
return fmt.Sprintf(`
55+
resource "tencentcloud_kms_key" "test" {
56+
alias = %[1]q
57+
description = %[1]q
58+
key_state = "Disabled"
59+
key_rotation_enabled = true
60+
}
61+
data "tencentcloud_kms_key" "test" {
62+
search_key_alias = tencentcloud_kms_key.test.alias
63+
}
64+
`, rName)
65+
}

0 commit comments

Comments
 (0)