Skip to content

Commit 1ace841

Browse files
tongyimingmikatong
andauthored
support tencentcloud_cvm_security_group_attachment (#1633)
* support tencentcloud_cvm_security_group_attachment * add changelog --------- Co-authored-by: mikatong <mikatong@tencent.com>
1 parent 39eb4ce commit 1ace841

File tree

6 files changed

+250
-0
lines changed

6 files changed

+250
-0
lines changed

.changelog/1633.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_cvm_security_group_attachment
3+
```

tencentcloud/provider.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,7 @@ Cloud Virtual Machine(CVM)
313313
tencentcloud_cvm_launch_template
314314
tencentcloud_cvm_launch_template_version
315315
tencentcloud_cvm_launch_template_default_version
316+
tencentcloud_cvm_security_group_attachment
316317
317318
TDSQL-C MySQL(CynosDB)
318319
Data Source
@@ -1793,6 +1794,7 @@ func Provider() terraform.ResourceProvider {
17931794
"tencentcloud_apm_instance": resourceTencentCloudApmInstance(),
17941795
"tencentcloud_cvm_launch_template_default_version": resourceTencentCloudCvmLaunchTemplateDefaultVersion(),
17951796
"tencentcloud_lighthouse_firewall_rule": resourceTencentCloudLighthouseFirewallRule(),
1797+
"tencentcloud_cvm_security_group_attachment": resourceTencentCloudCvmSecurityGroupAttachment(),
17961798
},
17971799

17981800
ConfigureFunc: providerConfigure,
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
/*
2+
Provides a resource to create a cvm security_group_attachment
3+
4+
Example Usage
5+
6+
```hcl
7+
resource "tencentcloud_cvm_security_group_attachment" "security_group_attachment" {
8+
security_group_id = "sg-xxxxxxx"
9+
instance_id = "ins-xxxxxxxx"
10+
}
11+
```
12+
13+
Import
14+
15+
cvm security_group_attachment can be imported using the id, e.g.
16+
17+
```
18+
terraform import tencentcloud_cvm_security_group_attachment.security_group_attachment ${instance_id}#${security_group_id}
19+
```
20+
*/
21+
package tencentcloud
22+
23+
import (
24+
"context"
25+
"fmt"
26+
"log"
27+
"strings"
28+
29+
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
30+
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
31+
cvm "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/cvm/v20170312"
32+
)
33+
34+
func resourceTencentCloudCvmSecurityGroupAttachment() *schema.Resource {
35+
return &schema.Resource{
36+
Create: resourceTencentCloudCvmSecurityGroupAttachmentCreate,
37+
Read: resourceTencentCloudCvmSecurityGroupAttachmentRead,
38+
Delete: resourceTencentCloudCvmSecurityGroupAttachmentDelete,
39+
Importer: &schema.ResourceImporter{
40+
State: schema.ImportStatePassthrough,
41+
},
42+
Schema: map[string]*schema.Schema{
43+
"security_group_id": {
44+
Required: true,
45+
ForceNew: true,
46+
Type: schema.TypeString,
47+
Description: "Security group id.",
48+
},
49+
50+
"instance_id": {
51+
Required: true,
52+
ForceNew: true,
53+
Type: schema.TypeString,
54+
Description: "Instance id.",
55+
},
56+
},
57+
}
58+
}
59+
60+
func resourceTencentCloudCvmSecurityGroupAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
61+
defer logElapsed("resource.tencentcloud_cvm_security_group_attachment.create")()
62+
defer inconsistentCheck(d, meta)()
63+
64+
logId := getLogId(contextNil)
65+
66+
request := cvm.NewAssociateSecurityGroupsRequest()
67+
securityGroupId := d.Get("security_group_id").(string)
68+
instanceId := d.Get("instance_id").(string)
69+
request.SecurityGroupIds = []*string{}
70+
71+
request.SecurityGroupIds = []*string{&securityGroupId}
72+
request.InstanceIds = []*string{&instanceId}
73+
74+
err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
75+
result, e := meta.(*TencentCloudClient).apiV3Conn.UseCvmClient().AssociateSecurityGroups(request)
76+
if e != nil {
77+
return retryError(e)
78+
} else {
79+
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n", logId, request.GetAction(), request.ToJsonString(), result.ToJsonString())
80+
}
81+
return nil
82+
})
83+
if err != nil {
84+
log.Printf("[CRITAL]%s create cvm securityGroupAttachment failed, reason:%+v", logId, err)
85+
return err
86+
}
87+
d.SetId(instanceId + FILED_SP + securityGroupId)
88+
89+
return resourceTencentCloudCvmSecurityGroupAttachmentRead(d, meta)
90+
}
91+
92+
func resourceTencentCloudCvmSecurityGroupAttachmentRead(d *schema.ResourceData, meta interface{}) error {
93+
defer logElapsed("resource.tencentcloud_cvm_security_group_attachment.read")()
94+
defer inconsistentCheck(d, meta)()
95+
96+
logId := getLogId(contextNil)
97+
98+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
99+
100+
service := CvmService{client: meta.(*TencentCloudClient).apiV3Conn}
101+
102+
idSplit := strings.Split(d.Id(), FILED_SP)
103+
if len(idSplit) != 2 {
104+
return fmt.Errorf("id is broken,%s", d.Id())
105+
}
106+
instanceId := idSplit[0]
107+
securityGroupId := idSplit[1]
108+
109+
instanceInfo, err := service.DescribeInstanceById(ctx, instanceId)
110+
if err != nil {
111+
return err
112+
}
113+
114+
if instanceInfo == nil {
115+
d.SetId("")
116+
log.Printf("[WARN]%s resource `CvmSecurityGroupAttachment` [%s] not found, please check if it has been deleted.\n", logId, d.Id())
117+
return nil
118+
}
119+
120+
for _, sgId := range instanceInfo.SecurityGroupIds {
121+
if *sgId == securityGroupId {
122+
_ = d.Set("instance_id", instanceId)
123+
_ = d.Set("security_group_id", securityGroupId)
124+
return nil
125+
126+
}
127+
}
128+
return fmt.Errorf("The security group get from api does not match with current instance %v", d.Id())
129+
}
130+
131+
func resourceTencentCloudCvmSecurityGroupAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
132+
defer logElapsed("resource.tencentcloud_cvm_security_group_attachment.delete")()
133+
defer inconsistentCheck(d, meta)()
134+
135+
logId := getLogId(contextNil)
136+
137+
idSplit := strings.Split(d.Id(), FILED_SP)
138+
if len(idSplit) != 2 {
139+
return fmt.Errorf("id is broken,%s", d.Id())
140+
}
141+
instanceId := idSplit[0]
142+
securityGroupId := idSplit[1]
143+
144+
request := cvm.NewDisassociateSecurityGroupsRequest()
145+
request.SecurityGroupIds = []*string{&securityGroupId}
146+
request.InstanceIds = []*string{&instanceId}
147+
err := resource.Retry(writeRetryTimeout, func() *resource.RetryError {
148+
result, e := meta.(*TencentCloudClient).apiV3Conn.UseCvmClient().DisassociateSecurityGroups(request)
149+
if e != nil {
150+
return retryError(e)
151+
} else {
152+
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n", logId, request.GetAction(), request.ToJsonString(), result.ToJsonString())
153+
}
154+
return nil
155+
})
156+
if err != nil {
157+
log.Printf("[CRITAL]%s delete cvm securityGroupAttachment failed, reason:%+v", logId, err)
158+
return err
159+
}
160+
161+
return nil
162+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package tencentcloud
2+
3+
import (
4+
"testing"
5+
6+
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
7+
)
8+
9+
func TestAccTencentCloudCvmSecurityGroupAttachmentResource_basic(t *testing.T) {
10+
t.Parallel()
11+
resource.Test(t, resource.TestCase{
12+
PreCheck: func() {
13+
testAccPreCheck(t)
14+
},
15+
Providers: testAccProviders,
16+
Steps: []resource.TestStep{
17+
{
18+
Config: testAccCvmSecurityGroupAttachment,
19+
Check: resource.ComposeTestCheckFunc(resource.TestCheckResourceAttrSet("tencentcloud_cvm_security_group_attachment.security_group_attachment", "id")),
20+
},
21+
{
22+
ResourceName: "tencentcloud_cvm_security_group_attachment.security_group_attachment",
23+
ImportState: true,
24+
ImportStateVerify: true,
25+
},
26+
},
27+
})
28+
}
29+
30+
const testAccCvmSecurityGroupAttachment = `
31+
resource "tencentcloud_cvm_security_group_attachment" "security_group_attachment" {
32+
security_group_id = "sg-a0212ii1"
33+
instance_id = "ins-cr2rfq78"
34+
}
35+
`
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
subcategory: "Cloud Virtual Machine(CVM)"
3+
layout: "tencentcloud"
4+
page_title: "TencentCloud: tencentcloud_cvm_security_group_attachment"
5+
sidebar_current: "docs-tencentcloud-resource-cvm_security_group_attachment"
6+
description: |-
7+
Provides a resource to create a cvm security_group_attachment
8+
---
9+
10+
# tencentcloud_cvm_security_group_attachment
11+
12+
Provides a resource to create a cvm security_group_attachment
13+
14+
## Example Usage
15+
16+
```hcl
17+
resource "tencentcloud_cvm_security_group_attachment" "security_group_attachment" {
18+
security_group_id = "sg-xxxxxxx"
19+
instance_id = "ins-xxxxxxxx"
20+
}
21+
```
22+
23+
## Argument Reference
24+
25+
The following arguments are supported:
26+
27+
* `instance_id` - (Required, String, ForceNew) Instance id.
28+
* `security_group_id` - (Required, String, ForceNew) Security group id.
29+
30+
## Attributes Reference
31+
32+
In addition to all arguments above, the following attributes are exported:
33+
34+
* `id` - ID of the resource.
35+
36+
37+
38+
## Import
39+
40+
cvm security_group_attachment can be imported using the id, e.g.
41+
42+
```
43+
terraform import tencentcloud_cvm_security_group_attachment.security_group_attachment ${instance_id}#${security_group_id}
44+
```
45+

website/tencentcloud.erb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1046,6 +1046,9 @@
10461046
<li>
10471047
<a href="/docs/providers/tencentcloud/r/cvm_launch_template_version.html">tencentcloud_cvm_launch_template_version</a>
10481048
</li>
1049+
<li>
1050+
<a href="/docs/providers/tencentcloud/r/cvm_security_group_attachment.html">tencentcloud_cvm_security_group_attachment</a>
1051+
</li>
10491052
<li>
10501053
<a href="/docs/providers/tencentcloud/r/eip.html">tencentcloud_eip</a>
10511054
</li>

0 commit comments

Comments
 (0)