Skip to content

Commit 0762e4d

Browse files
tongyimingmikatong
andauthored
fix: add key-pair-sweeper (#1154)
Co-authored-by: mikatong <mikatong@tencent.com>
1 parent ac8bed8 commit 0762e4d

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

tencentcloud/resource_tc_key_pair_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,60 @@ package tencentcloud
33
import (
44
"context"
55
"fmt"
6+
"log"
7+
"strings"
68
"testing"
9+
"time"
710

811
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
912
"github.com/hashicorp/terraform-plugin-sdk/terraform"
1013
)
1114

15+
func init() {
16+
// go test -v ./tencentcloud -sweep=ap-guangzhou -sweep-run=tencentcloud_cvm_key_pair
17+
resource.AddTestSweepers("tencentcloud_cvm_key_pair", &resource.Sweeper{
18+
Name: "tencentcloud_cvm_key_pair",
19+
F: func(region string) error {
20+
logId := getLogId(contextNil)
21+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
22+
sharedClient, err := sharedClientForRegion(region)
23+
if err != nil {
24+
return fmt.Errorf("getting tencentcloud client error: %s", err.Error())
25+
}
26+
client := sharedClient.(*TencentCloudClient)
27+
28+
cvmService := CvmService{
29+
client: client.apiV3Conn,
30+
}
31+
keyPairs, err := cvmService.DescribeKeyPairByFilter(ctx, "", "", nil)
32+
if err != nil {
33+
return fmt.Errorf("get instance list error: %s", err.Error())
34+
}
35+
for _, keyPair := range keyPairs {
36+
instanceId := *keyPair.KeyId
37+
instanceName := *keyPair.KeyName
38+
createTime := stringTotime(*keyPair.CreatedTime)
39+
now := time.Now()
40+
interval := now.Sub(createTime).Minutes()
41+
42+
if strings.HasPrefix(instanceName, keepResource) || strings.HasPrefix(instanceName, defaultResource) {
43+
continue
44+
}
45+
46+
if needProtect == 1 && int64(interval) < 30 {
47+
continue
48+
}
49+
50+
if err = cvmService.DeleteKeyPair(ctx, instanceId); err != nil {
51+
log.Printf("[ERROR] sweep keyPair instance %s error: %s", instanceId, err.Error())
52+
}
53+
}
54+
55+
return nil
56+
},
57+
})
58+
}
59+
1260
func TestAccTencentCloudKeyPair(t *testing.T) {
1361
t.Parallel()
1462
resource.Test(t, resource.TestCase{

0 commit comments

Comments
 (0)