Skip to content

Commit 94e8e86

Browse files
authored
add clb attach (#1840)
* add clb attach * add clb attach res * add res
1 parent 0c71647 commit 94e8e86

File tree

7 files changed

+301
-0
lines changed

7 files changed

+301
-0
lines changed

.changelog/1840.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_clb_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 Load Balancer(CLB)
313313
tencentcloud_clb_instance_sla_config
314314
tencentcloud_clb_instance_mix_ip_target_config
315315
tencentcloud_clb_replace_cert_for_lbs
316+
tencentcloud_clb_security_group_attachment
316317
317318
Cloud Object Storage(COS)
318319
Data Source
@@ -1931,6 +1932,7 @@ func Provider() *schema.Provider {
19311932
"tencentcloud_clb_instance_mix_ip_target_config": resourceTencentCloudClbInstanceMixIpTargetConfig(),
19321933
"tencentcloud_clb_instance_sla_config": resourceTencentCloudClbInstanceSlaConfig(),
19331934
"tencentcloud_clb_replace_cert_for_lbs": resourceTencentCloudClbReplaceCertForLbs(),
1935+
"tencentcloud_clb_security_group_attachment": resourceTencentCloudClbSecurityGroupAttachment(),
19341936
"tencentcloud_container_cluster": resourceTencentCloudContainerCluster(),
19351937
"tencentcloud_container_cluster_instance": resourceTencentCloudContainerClusterInstance(),
19361938
"tencentcloud_kubernetes_cluster": resourceTencentCloudTkeCluster(),
Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
/*
2+
Provides a resource to create a clb security_group_attachment
3+
4+
Example Usage
5+
6+
```hcl
7+
resource "tencentcloud_clb_security_group_attachment" "security_group_attachment" {
8+
security_group = "sg-ijato2x1"
9+
load_balancer_ids = ["lb-5dnrkgry"]
10+
}
11+
```
12+
13+
Import
14+
15+
clb security_group_attachment can be imported using the id, e.g.
16+
17+
```
18+
terraform import tencentcloud_clb_security_group_attachment.security_group_attachment security_group_id#clb_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/v2/helper/schema"
30+
clb "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/clb/v20180317"
31+
"github.com/tencentcloudstack/terraform-provider-tencentcloud/tencentcloud/internal/helper"
32+
)
33+
34+
func resourceTencentCloudClbSecurityGroupAttachment() *schema.Resource {
35+
return &schema.Resource{
36+
Create: resourceTencentCloudClbSecurityGroupAttachmentCreate,
37+
Read: resourceTencentCloudClbSecurityGroupAttachmentRead,
38+
Delete: resourceTencentCloudClbSecurityGroupAttachmentDelete,
39+
Importer: &schema.ResourceImporter{
40+
State: schema.ImportStatePassthrough,
41+
},
42+
Schema: map[string]*schema.Schema{
43+
"security_group": {
44+
Required: true,
45+
Type: schema.TypeString,
46+
ForceNew: true,
47+
Description: "Security group ID, such as esg-12345678.",
48+
},
49+
50+
"load_balancer_ids": {
51+
Required: true,
52+
Type: schema.TypeSet,
53+
ForceNew: true,
54+
MaxItems: 1,
55+
Elem: &schema.Schema{
56+
Type: schema.TypeString,
57+
},
58+
Description: "Array of CLB instance IDs. Only support set one security group now.",
59+
},
60+
},
61+
}
62+
}
63+
64+
func resourceTencentCloudClbSecurityGroupAttachmentCreate(d *schema.ResourceData, meta interface{}) error {
65+
defer logElapsed("resource.tencentcloud_clb_security_group_attachment.create")()
66+
defer inconsistentCheck(d, meta)()
67+
68+
logId := getLogId(contextNil)
69+
70+
var (
71+
request = clb.NewSetSecurityGroupForLoadbalancersRequest()
72+
securityGroup string
73+
loadBalancerId string
74+
)
75+
if v, ok := d.GetOk("security_group"); ok {
76+
securityGroup = v.(string)
77+
request.SecurityGroup = helper.String(v.(string))
78+
}
79+
80+
if v, ok := d.GetOk("load_balancer_ids"); ok {
81+
loadBalancerIdsSet := v.(*schema.Set).List()
82+
for i := range loadBalancerIdsSet {
83+
loadBalancerId = loadBalancerIdsSet[i].(string)
84+
request.LoadBalancerIds = append(request.LoadBalancerIds, &loadBalancerId)
85+
}
86+
}
87+
88+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
89+
90+
service := ClbService{client: meta.(*TencentCloudClient).apiV3Conn}
91+
92+
err := service.SetClbSecurityGroup(ctx, securityGroup, loadBalancerId, "ADD")
93+
if err != nil {
94+
return err
95+
}
96+
97+
d.SetId(securityGroup + FILED_SP + loadBalancerId)
98+
99+
return resourceTencentCloudClbSecurityGroupAttachmentRead(d, meta)
100+
}
101+
102+
func resourceTencentCloudClbSecurityGroupAttachmentRead(d *schema.ResourceData, meta interface{}) error {
103+
defer logElapsed("resource.tencentcloud_clb_security_group_attachment.read")()
104+
defer inconsistentCheck(d, meta)()
105+
106+
logId := getLogId(contextNil)
107+
108+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
109+
110+
service := ClbService{client: meta.(*TencentCloudClient).apiV3Conn}
111+
112+
idSplit := strings.Split(d.Id(), FILED_SP)
113+
if len(idSplit) != 2 {
114+
return fmt.Errorf("id is broken,%s", d.Id())
115+
}
116+
securityGroup := idSplit[0]
117+
loadBalancerId := idSplit[1]
118+
119+
instance, err := service.DescribeLoadBalancerById(ctx, loadBalancerId)
120+
if err != nil {
121+
return err
122+
}
123+
124+
if instance == nil {
125+
d.SetId("")
126+
log.Printf("[WARN]%s resource `ClbSecurityGroupAttachment` [%s] not found, please check if it has been deleted.\n", logId, d.Id())
127+
return nil
128+
}
129+
130+
exist := false
131+
for _, sg := range instance.SecureGroups {
132+
if *sg == securityGroup {
133+
exist = true
134+
break
135+
}
136+
}
137+
if !exist {
138+
d.SetId("")
139+
log.Printf("[WARN]%s resource `ClbSecurityGroupAttachment` [%s] not found, please check if it has been deleted.\n", logId, d.Id())
140+
return nil
141+
}
142+
143+
_ = d.Set("security_group", securityGroup)
144+
145+
_ = d.Set("load_balancer_ids", []*string{&loadBalancerId})
146+
147+
return nil
148+
}
149+
150+
func resourceTencentCloudClbSecurityGroupAttachmentDelete(d *schema.ResourceData, meta interface{}) error {
151+
defer logElapsed("resource.tencentcloud_clb_security_group_attachment.delete")()
152+
defer inconsistentCheck(d, meta)()
153+
154+
logId := getLogId(contextNil)
155+
ctx := context.WithValue(context.TODO(), logIdKey, logId)
156+
157+
service := ClbService{client: meta.(*TencentCloudClient).apiV3Conn}
158+
idSplit := strings.Split(d.Id(), FILED_SP)
159+
if len(idSplit) != 2 {
160+
return fmt.Errorf("id is broken,%s", d.Id())
161+
}
162+
securityGroup := idSplit[0]
163+
loadBalancerId := idSplit[1]
164+
165+
if err := service.SetClbSecurityGroup(ctx, securityGroup, loadBalancerId, "DEL"); err != nil {
166+
return err
167+
}
168+
169+
return nil
170+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package tencentcloud
2+
3+
import (
4+
"testing"
5+
6+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
7+
)
8+
9+
func TestAccTencentCloudClbSecurityGroupAttachmentResource_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: testAccClbSecurityGroupAttachment,
19+
Check: resource.ComposeTestCheckFunc(resource.TestCheckResourceAttrSet("tencentcloud_clb_security_group_attachment.security_group_attachment", "id")),
20+
},
21+
{
22+
ResourceName: "tencentcloud_clb_security_group_attachment.security_group_attachment",
23+
ImportState: true,
24+
ImportStateVerify: true,
25+
},
26+
},
27+
})
28+
}
29+
30+
const testAccClbSecurityGroupAttachment = `
31+
32+
resource "tencentcloud_clb_security_group_attachment" "security_group_attachment" {
33+
security_group = "sg-ijato2x1"
34+
load_balancer_ids = ["lb-5dnrkgry"]
35+
}
36+
37+
`

tencentcloud/service_tencentcloud_clb.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,21 @@ func (me *ClbService) DeleteListenerById(ctx context.Context, clbId string, list
230230
return nil
231231
}
232232

233+
func (me *ClbService) DescribeTaskStatusById(ctx context.Context, taskId string) (status int64, errRet error) {
234+
logId := getLogId(ctx)
235+
request := clb.NewDescribeTaskStatusRequest()
236+
request.TaskId = &taskId
237+
ratelimit.Check(request.GetAction())
238+
response, err := me.client.UseClbClient().DescribeTaskStatus(request)
239+
if err != nil {
240+
return 0, errors.WithStack(err)
241+
}
242+
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n",
243+
logId, request.GetAction(), request.ToJsonString(), response.ToJsonString())
244+
status = *response.Response.Status
245+
return
246+
}
247+
233248
func (me *ClbService) DescribeRulesByFilter(ctx context.Context, params map[string]string) (rules []*clb.RuleOutput, errRet error) {
234249
logId := getLogId(ctx)
235250
//listener filter
@@ -2201,3 +2216,29 @@ func (me *ClbService) DescribeClbTargetHealthByFilter(ctx context.Context, param
22012216

22022217
return
22032218
}
2219+
2220+
func (me *ClbService) SetClbSecurityGroup(ctx context.Context, securityGroup string, lbId string, operation string) (errRet error) {
2221+
logId := getLogId(ctx)
2222+
2223+
request := clb.NewSetSecurityGroupForLoadbalancersRequest()
2224+
request.SecurityGroup = &securityGroup
2225+
request.LoadBalancerIds = []*string{&lbId}
2226+
request.OperationType = &operation
2227+
2228+
defer func() {
2229+
if errRet != nil {
2230+
log.Printf("[CRITAL]%s api[%s] fail, request body [%s], reason[%s]\n", logId, request.GetAction(), request.ToJsonString(), errRet.Error())
2231+
}
2232+
}()
2233+
2234+
ratelimit.Check(request.GetAction())
2235+
2236+
response, err := me.client.UseClbClient().SetSecurityGroupForLoadbalancers(request)
2237+
if err != nil {
2238+
errRet = err
2239+
return
2240+
}
2241+
log.Printf("[DEBUG]%s api[%s] success, request body [%s], response body [%s]\n", logId, request.GetAction(), request.ToJsonString(), response.ToJsonString())
2242+
2243+
return
2244+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
subcategory: "Cloud Load Balancer(CLB)"
3+
layout: "tencentcloud"
4+
page_title: "TencentCloud: tencentcloud_clb_security_group_attachment"
5+
sidebar_current: "docs-tencentcloud-resource-clb_security_group_attachment"
6+
description: |-
7+
Provides a resource to create a clb security_group_attachment
8+
---
9+
10+
# tencentcloud_clb_security_group_attachment
11+
12+
Provides a resource to create a clb security_group_attachment
13+
14+
## Example Usage
15+
16+
```hcl
17+
resource "tencentcloud_clb_security_group_attachment" "security_group_attachment" {
18+
security_group = "sg-ijato2x1"
19+
load_balancer_ids = ["lb-5dnrkgry"]
20+
}
21+
```
22+
23+
## Argument Reference
24+
25+
The following arguments are supported:
26+
27+
* `load_balancer_ids` - (Required, Set: [`String`], ForceNew) Array of CLB instance IDs. Only support set one security group now.
28+
* `security_group` - (Required, String, ForceNew) Security group ID, such as esg-12345678.
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+
clb security_group_attachment can be imported using the id, e.g.
41+
42+
```
43+
terraform import tencentcloud_clb_security_group_attachment.security_group_attachment security_group_id#clb_id
44+
```
45+

website/tencentcloud.erb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -900,6 +900,9 @@
900900
<li>
901901
<a href="/docs/providers/tencentcloud/r/clb_replace_cert_for_lbs.html">tencentcloud_clb_replace_cert_for_lbs</a>
902902
</li>
903+
<li>
904+
<a href="/docs/providers/tencentcloud/r/clb_security_group_attachment.html">tencentcloud_clb_security_group_attachment</a>
905+
</li>
903906
<li>
904907
<a href="/docs/providers/tencentcloud/r/clb_snat_ip.html">tencentcloud_clb_snat_ip</a>
905908
</li>

0 commit comments

Comments
 (0)