Skip to content

Commit

Permalink
feat: new loadbalancer data source supported (#1113)
Browse files Browse the repository at this point in the history
  • Loading branch information
Lance52259 authored May 11, 2021
1 parent 9ff76cd commit 9e96285
Show file tree
Hide file tree
Showing 5 changed files with 272 additions and 0 deletions.
45 changes: 45 additions & 0 deletions docs/data-sources/lb_balancer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
---
subcategory: "Elastic Load Balance (ELB)"
---

# huaweicloud\_lb\_loadbalancer

Use this data source to get available HuaweiCloud elb loadbalancer.

## Example Usage

```hcl
variable "lb_name" {}
data "huaweicloud_lb_loadbalancer" "test" {
name = var.lb_name
}
```

## Argument Reference

* `region` - (Optional, String) Specifies the region in which to obtain the load balancer.
If omitted, the provider-level region will be used.

* `name` - (Optional, String) Specifies the name of the load balancer.

* `id` - (Optional, String) Specifies the data source ID of the load balancer in UUID format.

* `status` - (Optional, String) Specifies the operating status of the load balancer.
Valid values are *ONLINE* and *FROZEN*.

* `description` - (Optional, String) Specifies the supplementary information about the load balancer.

* `vip_address` - (Optional, String) Specifies the private IP address of the load balancer.

* `vip_subnet_id` - (Optional, String) Specifies the ID of the subnet where the load balancer works.

* `enterprise_project_id` - (Optional, String) Specifies the enterprise project id of the load balancer.

## Attributes Reference

In addition to all arguments above, the following attributes are exported:

* `tags` - The tags associated with the load balancer.

* `vip_port_id` - The ID of the port bound to the private IP address of the load balancer.
132 changes: 132 additions & 0 deletions huaweicloud/data_source_huaweicloud_lb_loadbalancer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package huaweicloud

import (
"fmt"

"github.com/hashicorp/go-multierror"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/huaweicloud/golangsdk/openstack/common/tags"
"github.com/huaweicloud/golangsdk/openstack/elb/v2/loadbalancers"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/utils"
)

func dataSourceELBV2Loadbalancer() *schema.Resource {
return &schema.Resource{
Read: dataSourceELBV2LoadbalancerRead,
Schema: map[string]*schema.Schema{
"region": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"name": {
Type: schema.TypeString,
Optional: true,
},
"id": {
Type: schema.TypeString,
Optional: true,
},
"status": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{
"ONLINE", "FROZEN",
}, true),
},
"description": {
Type: schema.TypeString,
Optional: true,
},
"vip_address": {
Type: schema.TypeString,
Optional: true,
},
"vip_subnet_id": {
Type: schema.TypeString,
Optional: true,
},
"enterprise_project_id": {
Type: schema.TypeString,
Optional: true,
},
"tags": {
Type: schema.TypeMap,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"vip_port_id": {
Type: schema.TypeString,
Computed: true,
},
},
}
}

func dataSourceELBV2LoadbalancerRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*config.Config)
region := GetRegion(d, config)
elbClient, err := config.LoadBalancerClient(region)
if err != nil {
return fmt.Errorf("Error creating Huaweicloud elb client %s", err)
}
// Client for getting tags
elbV2Client, err := config.ElbV2Client(GetRegion(d, config))
if err != nil {
return fmt.Errorf("Error creating HuaweiCloud elb v2.0 client: %s", err)
}
listOpts := loadbalancers.ListOpts{
Name: d.Get("name").(string),
ID: d.Get("id").(string),
OperatingStatus: d.Get("status").(string),
Description: d.Get("description").(string),
VipAddress: d.Get("vip_address").(string),
VipSubnetID: d.Get("vip_subnet_id").(string),
EnterpriseProjectID: GetEnterpriseProjectID(d, config),
}
pages, err := loadbalancers.List(elbClient, listOpts).AllPages()
if err != nil {
return fmt.Errorf("Unable to retrieve loadbalancers: %s", err)
}
lbList, err := loadbalancers.ExtractLoadBalancers(pages)
if err != nil {
return fmt.Errorf("Unable to extract loadbalancers: %s", err)
}

if len(lbList) < 1 {
return fmt.Errorf("Your query returned no results, Please change your search criteria and try again")
}

if len(lbList) > 1 {
return fmt.Errorf("Your query returned more than one result, Please try a more specific search criteria")
}

lb := lbList[0]
d.SetId(lb.ID)

mErr := multierror.Append(
d.Set("region", GetRegion(d, config)),
d.Set("name", lb.Name),
d.Set("status", lb.OperatingStatus),
d.Set("description", lb.Description),
d.Set("vip_address", lb.VipAddress),
d.Set("vip_subnet_id", lb.VipSubnetID),
d.Set("enterprise_project_id", lb.EnterpriseProjectID),
d.Set("vip_port_id", lb.VipPortID),
)
if err := mErr.ErrorOrNil(); err != nil {
return fmt.Errorf("Error setting elb loadbalancer fields: %s", err)
}

// Get tags
resourceTags, err := tags.Get(elbV2Client, "loadbalancers", d.Id()).Extract()
if err != nil {
fmt.Errorf("Error fetching tags of elb loadbalancer: %s", err)
}
tagmap := utils.TagsToMap(resourceTags.Tags)
d.Set("tags", tagmap)

return nil
}
92 changes: 92 additions & 0 deletions huaweicloud/data_source_huaweicloud_lb_loadbalancer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package huaweicloud

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/terraform"
"github.com/huaweicloud/golangsdk/openstack/elb/v2/loadbalancers"
"github.com/huaweicloud/terraform-provider-huaweicloud/huaweicloud/config"
)

func TestAccELBV2LoadbalancerDataSource_basic(t *testing.T) {
rName := fmt.Sprintf("tf-acc-test-%s", acctest.RandString(5))

resource.ParallelTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
Steps: []resource.TestStep{
{
Config: testAccELBV2LoadbalancerDataSource_basic(rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckELBV2LoadbalancerDataSourceID("data.huaweicloud_lb_loadbalancer.test_by_name"),
testAccCheckELBV2LoadbalancerDataSourceID("data.huaweicloud_lb_loadbalancer.test_by_description"),
resource.TestCheckResourceAttr(
"data.huaweicloud_lb_loadbalancer.test_by_name", "name", rName),
resource.TestCheckResourceAttr(
"data.huaweicloud_lb_loadbalancer.test_by_description", "name", rName),
),
},
},
})
}

func testAccCheckELBV2LoadbalancerDataSourceID(n string) resource.TestCheckFunc {
return func(s *terraform.State) error {
rs, ok := s.RootModule().Resources[n]
if !ok {
return fmt.Errorf("Can't find elb load balancer data source: %s", n)
}

if rs.Primary.ID == "" {
return fmt.Errorf("load balancer data source ID not set")
}

return nil
}
}

func testAccCheckELBV2LoadbalancerDestroy(s *terraform.State) error {
config := testAccProvider.Meta().(*config.Config)
client, err := config.LoadBalancerClient(HW_REGION_NAME)
if err != nil {
return fmt.Errorf("Error creating HuaweiCloud load balancer client: %s", err)
}

for _, rs := range s.RootModule().Resources {
if rs.Type != "huaweicloud_lb_loadbalancer" {
continue
}

lb, err := loadbalancers.Get(client, rs.Primary.ID).Extract()
if err == nil || lb.ID != "" {
return fmt.Errorf("Load balancer still exists")
}
}

return nil
}

func testAccELBV2LoadbalancerDataSource_basic(rName string) string {
return fmt.Sprintf(`
data "huaweicloud_vpc_subnet" "test" {
name = "subnet-default"
}
resource "huaweicloud_lb_loadbalancer" "test" {
name = "%s"
vip_subnet_id = data.huaweicloud_vpc_subnet.test.subnet_id
description = "test for load balancer data source"
}
data "huaweicloud_lb_loadbalancer" "test_by_name" {
name = huaweicloud_lb_loadbalancer.test.name
}
data "huaweicloud_lb_loadbalancer" "test_by_description" {
description = huaweicloud_lb_loadbalancer.test.description
}
`, rName)
}
1 change: 1 addition & 0 deletions huaweicloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,7 @@ func Provider() terraform.ResourceProvider {
"huaweicloud_images_image": DataSourceImagesImageV2(),
"huaweicloud_kms_key": dataSourceKmsKeyV1(),
"huaweicloud_kms_data_key": dataSourceKmsDataKeyV1(),
"huaweicloud_lb_loadbalancer": dataSourceELBV2Loadbalancer(),
"huaweicloud_nat_gateway": DataSourceNatGatewayV2(),
"huaweicloud_networking_port": DataSourceNetworkingPortV2(),
"huaweicloud_networking_secgroup": DataSourceNetworkingSecGroupV2(),
Expand Down
2 changes: 2 additions & 0 deletions huaweicloud/resource_huaweicloud_lb_loadbalancer.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ func ResourceLoadBalancerV2() *schema.Resource {
},

"tags": tagsSchema(),

"loadbalancer_provider": {
Type: schema.TypeString,
Optional: true,
Expand All @@ -100,6 +101,7 @@ func ResourceLoadBalancerV2() *schema.Resource {
Elem: &schema.Schema{Type: schema.TypeString},
Set: schema.HashString,
},

"enterprise_project_id": {
Type: schema.TypeString,
Optional: true,
Expand Down

0 comments on commit 9e96285

Please sign in to comment.