Skip to content

Commit

Permalink
New Resource: alicloud_alb_load_balancer_security_group_attachment.
Browse files Browse the repository at this point in the history
  • Loading branch information
ChenHanZhang committed Jul 1, 2024
1 parent 0ffa686 commit d717183
Show file tree
Hide file tree
Showing 5 changed files with 480 additions and 0 deletions.
1 change: 1 addition & 0 deletions alicloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -865,6 +865,7 @@ func Provider() terraform.ResourceProvider {
ResourcesMap: map[string]*schema.Resource{
"alicloud_ddos_bgp_policy": resourceAliCloudDdosBgpPolicy(),
"alicloud_cen_transit_router_ecr_attachment": resourceAliCloudCenTransitRouterEcrAttachment(),
"alicloud_alb_load_balancer_security_group_attachment": resourceAliCloudAlbLoadBalancerSecurityGroupAttachment(),
"alicloud_gpdb_db_resource_group": resourceAliCloudGpdbDbResourceGroup(),
"alicloud_cloud_firewall_nat_firewall": resourceAliCloudCloudFirewallNatFirewall(),
"alicloud_oss_bucket_public_access_block": resourceAliCloudOssBucketPublicAccessBlock(),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you!
package alicloud

import (
"fmt"
"log"
"strings"
"time"

util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
)

func resourceAliCloudAlbLoadBalancerSecurityGroupAttachment() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudAlbLoadBalancerSecurityGroupAttachmentCreate,
Read: resourceAliCloudAlbLoadBalancerSecurityGroupAttachmentRead,
Delete: resourceAliCloudAlbLoadBalancerSecurityGroupAttachmentDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(5 * time.Minute),
Delete: schema.DefaultTimeout(5 * time.Minute),
},
Schema: map[string]*schema.Schema{
"load_balancer_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"security_group_id": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}

func resourceAliCloudAlbLoadBalancerSecurityGroupAttachmentCreate(d *schema.ResourceData, meta interface{}) error {

client := meta.(*connectivity.AliyunClient)

action := "LoadBalancerJoinSecurityGroup"
var request map[string]interface{}
var response map[string]interface{}
query := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request = make(map[string]interface{})
request["SecurityGroupIds.1"] = d.Get("security_group_id")
query["LoadBalancerId"] = d.Get("load_balancer_id")

request["ClientToken"] = buildClientToken(action)

runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), query, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})

if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_alb_load_balancer_security_group_attachment", action, AlibabaCloudSdkGoERROR)
}

d.SetId(fmt.Sprintf("%v:%v", query["LoadBalancerId"], request["SecurityGroupIds.1"]))

albServiceV2 := AlbServiceV2{client}
stateConf := BuildStateConf([]string{}, []string{"#CHECKSET"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, albServiceV2.AlbLoadBalancerSecurityGroupAttachmentStateRefreshFunc(d.Id(), "#ID", []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}

return resourceAliCloudAlbLoadBalancerSecurityGroupAttachmentRead(d, meta)
}

func resourceAliCloudAlbLoadBalancerSecurityGroupAttachmentRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
albServiceV2 := AlbServiceV2{client}

objectRaw, err := albServiceV2.DescribeAlbLoadBalancerSecurityGroupAttachment(d.Id())
if err != nil {
if !d.IsNewResource() && NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_alb_load_balancer_security_group_attachment DescribeAlbLoadBalancerSecurityGroupAttachment Failed!!! %s", err)
d.SetId("")
return nil
}
return WrapError(err)
}

if objectRaw["LoadBalancerId"] != nil {
d.Set("load_balancer_id", objectRaw["LoadBalancerId"])
}

parts := strings.Split(d.Id(), ":")
d.Set("load_balancer_id", parts[0])
d.Set("security_group_id", parts[1])

return nil
}

func resourceAliCloudAlbLoadBalancerSecurityGroupAttachmentDelete(d *schema.ResourceData, meta interface{}) error {

client := meta.(*connectivity.AliyunClient)
parts := strings.Split(d.Id(), ":")
action := "LoadBalancerLeaveSecurityGroup"
var request map[string]interface{}
var response map[string]interface{}
query := make(map[string]interface{})
conn, err := client.NewAlbClient()
if err != nil {
return WrapError(err)
}
request = make(map[string]interface{})
request["SecurityGroupIds.1"] = parts[1]
query["LoadBalancerId"] = parts[0]

request["ClientToken"] = buildClientToken(action)

runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutDelete), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), query, request, &runtime)
request["ClientToken"] = buildClientToken(action)

if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})

if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}

albServiceV2 := AlbServiceV2{client}
stateConf := BuildStateConf([]string{}, []string{}, d.Timeout(schema.TimeoutDelete), 5*time.Second, albServiceV2.AlbLoadBalancerSecurityGroupAttachmentStateRefreshFunc(d.Id(), "#ID", []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package alicloud

import (
"fmt"
"testing"

"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)

// Test Alb LoadBalancerSecurityGroupAttachment. >>> Resource test cases, automatically generated.
// Case LoadBalancerSecurityGroupAttachment 7120
func TestAccAliCloudAlbLoadBalancerSecurityGroupAttachment_basic7120(t *testing.T) {
var v map[string]interface{}
resourceId := "alicloud_alb_load_balancer_security_group_attachment.default"
ra := resourceAttrInit(resourceId, AlicloudAlbLoadBalancerSecurityGroupAttachmentMap7120)
rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} {
return &AlbServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)}
}, "DescribeAlbLoadBalancerSecurityGroupAttachment")
rac := resourceAttrCheckInit(rc, ra)
testAccCheck := rac.resourceAttrMapUpdateSet()
rand := acctest.RandIntRange(10000, 99999)
name := fmt.Sprintf("tf-testacc%salbloadbalancersecuritygroupattachment%d", defaultRegionToTest, rand)
testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudAlbLoadBalancerSecurityGroupAttachmentBasicDependence7120)
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
IDRefreshName: resourceId,
Providers: testAccProviders,
CheckDestroy: rac.checkResourceDestroy(),
Steps: []resource.TestStep{
{
Config: testAccConfig(map[string]interface{}{
"security_group_id": "${alicloud_security_group.create_security_group.id}",
"load_balancer_id": "${alicloud_alb_load_balancer.create_alb.id}",
}),
Check: resource.ComposeTestCheckFunc(
testAccCheck(map[string]string{
"security_group_id": CHECKSET,
"load_balancer_id": CHECKSET,
}),
),
},
{
ResourceName: resourceId,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{},
},
},
})
}

var AlicloudAlbLoadBalancerSecurityGroupAttachmentMap7120 = map[string]string{
"security_group_id": CHECKSET,
}

func AlicloudAlbLoadBalancerSecurityGroupAttachmentBasicDependence7120(name string) string {
return fmt.Sprintf(`
variable "name" {
default = "%s"
}
data "alicloud_zones" "default" {
available_resource_creation = "VSwitch"
}
resource "alicloud_vpc" "create_vpc" {
cidr_block = "192.168.0.0/16"
vpc_name = var.name
}
resource "alicloud_vswitch" "create_vsw_1" {
vpc_id = alicloud_vpc.create_vpc.id
zone_id = data.alicloud_zones.default.zones.0.id
cidr_block = "192.168.1.0/24"
vswitch_name = var.name
}
resource "alicloud_vswitch" "create_vsw_2" {
vpc_id = alicloud_vpc.create_vpc.id
zone_id = data.alicloud_zones.default.zones.1.id
cidr_block = "192.168.2.0/24"
vswitch_name = var.name
}
resource "alicloud_security_group" "create_security_group" {
name = var.name
vpc_id = alicloud_vpc.create_vpc.id
}
resource "alicloud_alb_load_balancer" "create_alb" {
load_balancer_name = var.name
load_balancer_edition = "Standard"
vpc_id = alicloud_vpc.create_vpc.id
load_balancer_billing_config {
pay_type = "PayAsYouGo"
}
address_type = "Intranet"
address_allocated_mode = "Fixed"
zone_mappings {
vswitch_id = alicloud_vswitch.create_vsw_2.id
zone_id = alicloud_vswitch.create_vsw_2.zone_id
}
zone_mappings {
vswitch_id = alicloud_vswitch.create_vsw_1.id
zone_id = alicloud_vswitch.create_vsw_1.zone_id
}
}
`, name)
}

// Test Alb LoadBalancerSecurityGroupAttachment. <<< Resource test cases, automatically generated.
90 changes: 90 additions & 0 deletions alicloud/service_alicloud_alb_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -340,3 +340,93 @@ func (s *AlbServiceV2) SetResourceTags(d *schema.ResourceData, resourceType stri
}

// SetResourceTags >>> tag function encapsulated.

// DescribeAlbLoadBalancerSecurityGroupAttachment <<< Encapsulated get interface for Alb LoadBalancerSecurityGroupAttachment.

func (s *AlbServiceV2) DescribeAlbLoadBalancerSecurityGroupAttachment(id string) (object map[string]interface{}, err error) {
client := s.client
var request map[string]interface{}
var response map[string]interface{}
var query map[string]interface{}
parts := strings.Split(id, ":")
if len(parts) != 2 {
err = WrapError(fmt.Errorf("invalid Resource Id %s. Expected parts' length %d, got %d", id, 2, len(parts)))
}
action := "GetLoadBalancerAttribute"
conn, err := client.NewAlbClient()
if err != nil {
return object, WrapError(err)
}
request = make(map[string]interface{})
query = make(map[string]interface{})
query["LoadBalancerId"] = parts[0]

runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(1*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2020-06-16"), StringPointer("AK"), query, request, &runtime)

if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
addDebug(action, response, request)
return nil
})
if err != nil {
addDebug(action, response, request)
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}

v, err := jsonpath.Get("$", response)
instanceIds, err := jsonpath.Get("$.SecurityGroupIds[*]", v)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.SecurityGroupIds[*]", v)
}
found := false
for _, vv := range instanceIds.([]interface{}) {
if vv.(string) == parts[1] {
found = true
break
}
}
if found {
return v.(map[string]interface{}), nil
}

return object, WrapErrorf(Error(GetNotFoundMessage("LoadBalancerSecurityGroupAttachment", id)), NotFoundMsg, response)
}

func (s *AlbServiceV2) AlbLoadBalancerSecurityGroupAttachmentStateRefreshFunc(id string, field string, failStates []string) resource.StateRefreshFunc {
return func() (interface{}, string, error) {
object, err := s.DescribeAlbLoadBalancerSecurityGroupAttachment(id)
if err != nil {
if NotFoundError(err) {
return nil, "", nil
}
return nil, "", WrapError(err)
}

v, err := jsonpath.Get(field, object)
currentStatus := fmt.Sprint(v)

if field == "#ID" {
if currentStatus != "" {
currentStatus = "#CHECKSET"
}
}

for _, failState := range failStates {
if currentStatus == failState {
return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus))
}
}
return object, currentStatus, nil
}
}

// DescribeAlbLoadBalancerSecurityGroupAttachment >>> Encapsulated.
Loading

0 comments on commit d717183

Please sign in to comment.