Skip to content

Commit

Permalink
resource/alicloud_common_bandwidth_package_attachment: improve code i…
Browse files Browse the repository at this point in the history
…mplementation and document.
  • Loading branch information
ChenHanZhang committed Jun 20, 2024
1 parent 5376edb commit 0d8f073
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 50 deletions.
70 changes: 44 additions & 26 deletions alicloud/resource_alicloud_common_bandwidth_package_attachment.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"
"time"

"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
Expand Down Expand Up @@ -70,13 +71,14 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentCreate(d *schema.Resour
action := "AddCommonBandwidthPackageIp"
var request map[string]interface{}
var response map[string]interface{}
query := make(map[string]interface{})
conn, err := client.NewCbwpClient()
if err != nil {
return WrapError(err)
}
request = make(map[string]interface{})
request["BandwidthPackageId"] = d.Get("bandwidth_package_id")
request["IpInstanceId"] = d.Get("instance_id")
query["BandwidthPackageId"] = d.Get("bandwidth_package_id")
query["IpInstanceId"] = d.Get("instance_id")
request["RegionId"] = client.RegionId
request["ClientToken"] = buildClientToken(action)

Expand All @@ -87,9 +89,7 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentCreate(d *schema.Resour
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("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
request["ClientToken"] = buildClientToken(action)

response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), query, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"BandwidthPackageOperation.conflict", "OperationConflict", "LastTokenProcessing", "IncorrectStatus", "SystemBusy", "ServiceUnavailable", "TaskConflict", "EipOperation.TooFrequently", "IncorrectStatus.Eip"}) || NeedRetry(err) {
wait()
Expand All @@ -105,7 +105,7 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentCreate(d *schema.Resour
return WrapErrorf(err, DefaultErrorMsg, "alicloud_common_bandwidth_package_attachment", action, AlibabaCloudSdkGoERROR)
}

d.SetId(fmt.Sprintf("%v:%v", request["BandwidthPackageId"], request["IpInstanceId"]))
d.SetId(fmt.Sprintf("%v:%v", query["BandwidthPackageId"], query["IpInstanceId"]))

cbwpServiceV2 := CbwpServiceV2{client}
stateConf := BuildStateConf([]string{}, []string{"Available"}, d.Timeout(schema.TimeoutCreate), 5*time.Second, cbwpServiceV2.CbwpCommonBandwidthPackageAttachmentStateRefreshFunc(d.Id(), "Status", []string{}))
Expand All @@ -130,23 +130,39 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentRead(d *schema.Resource
return WrapError(err)
}

d.Set("status", objectRaw["Status"])
d.Set("bandwidth_package_id", objectRaw["BandwidthPackageId"])
if objectRaw["Status"] != nil {
d.Set("status", objectRaw["Status"])
}
if objectRaw["BandwidthPackageId"] != nil {
d.Set("bandwidth_package_id", objectRaw["BandwidthPackageId"])
}

parts, err := ParseResourceId(d.Id(), 2)
if err != nil {
return WrapError(err)
publicIpAddresse1RawObj, _ := jsonpath.Get("$.PublicIpAddresses.PublicIpAddresse[*]", objectRaw)
publicIpAddresse1Raw := make([]interface{}, 0)
if publicIpAddresse1RawObj != nil {
publicIpAddresse1Raw = publicIpAddresse1RawObj.([]interface{})
}

publicIpAddresseChild1Raw := publicIpAddresse1Raw[0].(map[string]interface{})
if publicIpAddresseChild1Raw["AllocationId"] != nil {
d.Set("instance_id", publicIpAddresseChild1Raw["AllocationId"])
}
bandwidthPackageId, ipInstanceId := parts[0], parts[1]
d.Set("bandwidth_package_id", bandwidthPackageId)
d.Set("instance_id", ipInstanceId)

objectRaw, err = cbwpServiceV2.DescribeDescribeEipAddresses(d.Id())
if err != nil {
return WrapError(err)
}

d.Set("bandwidth_package_bandwidth", objectRaw["Bandwidth"])
if objectRaw["Bandwidth"] != nil {
d.Set("bandwidth_package_bandwidth", objectRaw["Bandwidth"])
}
if objectRaw["BandwidthPackageId"] != nil {
d.Set("bandwidth_package_id", objectRaw["BandwidthPackageId"])
}

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

return nil
}
Expand All @@ -155,6 +171,7 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentUpdate(d *schema.Resour
client := meta.(*connectivity.AliyunClient)
var request map[string]interface{}
var response map[string]interface{}
var query map[string]interface{}
update := false
parts := strings.Split(d.Id(), ":")
action := "ModifyCommonBandwidthPackageIpBandwidth"
Expand All @@ -163,8 +180,9 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentUpdate(d *schema.Resour
return WrapError(err)
}
request = make(map[string]interface{})
request["BandwidthPackageId"] = parts[0]
request["EipId"] = parts[1]
query = make(map[string]interface{})
query["BandwidthPackageId"] = parts[0]
query["EipId"] = parts[1]
request["RegionId"] = client.RegionId
if d.HasChange("bandwidth_package_bandwidth") {
update = true
Expand All @@ -176,8 +194,7 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentUpdate(d *schema.Resour
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)

response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), query, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"BandwidthPackageOperation.conflict", "OperationConflict", "LastTokenProcessing", "IncorrectStatus", "SystemBusy", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
Expand Down Expand Up @@ -209,15 +226,15 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentUpdate(d *schema.Resour
return WrapError(err)
}
request = make(map[string]interface{})
request["BandwidthPackageId"] = parts[0]
request["EipId"] = parts[1]
query = make(map[string]interface{})
query["BandwidthPackageId"] = parts[0]
query["EipId"] = parts[1]
request["RegionId"] = client.RegionId
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 5*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), nil, request, &runtime)

response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), query, request, &runtime)
if err != nil {
if IsExpectedErrors(err, []string{"BandwidthPackageOperation.conflict", "OperationConflict", "LastTokenProcessing", "IncorrectStatus", "SystemBusy", "ServiceUnavailable"}) || NeedRetry(err) {
wait()
Expand Down Expand Up @@ -250,13 +267,14 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentDelete(d *schema.Resour
action := "RemoveCommonBandwidthPackageIp"
var request map[string]interface{}
var response map[string]interface{}
query := make(map[string]interface{})
conn, err := client.NewCbwpClient()
if err != nil {
return WrapError(err)
}
request = make(map[string]interface{})
request["BandwidthPackageId"] = parts[0]
request["IpInstanceId"] = parts[1]
query["BandwidthPackageId"] = parts[0]
query["IpInstanceId"] = parts[1]
request["RegionId"] = client.RegionId

request["ClientToken"] = buildClientToken(action)
Expand All @@ -265,7 +283,7 @@ func resourceAliCloudCbwpCommonBandwidthPackageAttachmentDelete(d *schema.Resour
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("2016-04-28"), StringPointer("AK"), nil, request, &runtime)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), query, request, &runtime)
request["ClientToken"] = buildClientToken(action)

if err != nil {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ func TestAccAliCloudCommonBandwidthPackageAttachment_Multi(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"})
},
// module name
IDRefreshName: resourceId,
Expand Down Expand Up @@ -152,6 +153,7 @@ func TestAccAliCloudCommonBandwidthPackageAttachment_basic1(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"})
},
IDRefreshName: resourceId,
Providers: testAccProviders,
Expand Down Expand Up @@ -227,6 +229,7 @@ func TestAccAliCloudCommonBandwidthPackageAttachment_basic2(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"})
},
IDRefreshName: resourceId,
Providers: testAccProviders,
Expand Down Expand Up @@ -273,6 +276,7 @@ func TestAccAliCloudCommonBandwidthPackageAttachment_Multiple(t *testing.T) {
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"})
},
IDRefreshName: resourceId,
Providers: testAccProviders,
Expand Down
25 changes: 9 additions & 16 deletions alicloud/service_alicloud_cbwp_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,6 @@ func (s *CbwpServiceV2) DescribeCommonBandwidthPackageAttachment(id string) (obj
// DescribeCbwpCommonBandwidthPackageAttachment <<< Encapsulated get interface for Cbwp CommonBandwidthPackageAttachment.

func (s *CbwpServiceV2) DescribeCbwpCommonBandwidthPackageAttachment(id string) (object map[string]interface{}, err error) {

client := s.client
var request map[string]interface{}
var response map[string]interface{}
Expand All @@ -274,13 +273,13 @@ func (s *CbwpServiceV2) DescribeCbwpCommonBandwidthPackageAttachment(id string)
request = make(map[string]interface{})
query = make(map[string]interface{})
query["BandwidthPackageId"] = parts[0]
request["RegionId"] = client.RegionId
query["RegionId"] = client.RegionId

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("2016-04-28"), StringPointer("AK"), query, request, &runtime)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), query, nil, &runtime)

if err != nil {
if NeedRetry(err) {
Expand All @@ -292,11 +291,8 @@ func (s *CbwpServiceV2) DescribeCbwpCommonBandwidthPackageAttachment(id string)
addDebug(action, response, request)
return nil
})

if err != nil {
if IsExpectedErrors(err, []string{}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CommonBandwidthPackageAttachment", id)), NotFoundMsg, response)
}
addDebug(action, response, request)
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}

Expand Down Expand Up @@ -333,7 +329,6 @@ func (s *CbwpServiceV2) DescribeCbwpCommonBandwidthPackageAttachment(id string)
return object, WrapErrorf(Error(GetNotFoundMessage("CommonBandwidthPackageAttachment", id)), NotFoundMsg, response)
}
func (s *CbwpServiceV2) DescribeDescribeEipAddresses(id string) (object map[string]interface{}, err error) {

client := s.client
var request map[string]interface{}
var response map[string]interface{}
Expand All @@ -347,16 +342,15 @@ func (s *CbwpServiceV2) DescribeDescribeEipAddresses(id string) (object map[stri
if err != nil {
return object, WrapError(err)
}
request = make(map[string]interface{})
query = make(map[string]interface{})
query["AllocationId"] = parts[1]
request["RegionId"] = client.RegionId
query["RegionId"] = client.RegionId

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("2016-04-28"), StringPointer("AK"), query, request, &runtime)
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2016-04-28"), StringPointer("AK"), query, nil, &runtime)

if err != nil {
if NeedRetry(err) {
Expand All @@ -368,11 +362,8 @@ func (s *CbwpServiceV2) DescribeDescribeEipAddresses(id string) (object map[stri
addDebug(action, response, request)
return nil
})

if err != nil {
if IsExpectedErrors(err, []string{}) {
return object, WrapErrorf(Error(GetNotFoundMessage("CommonBandwidthPackageAttachment", id)), NotFoundMsg, response)
}
addDebug(action, response, request)
return object, WrapErrorf(err, DefaultErrorMsg, id, action, AlibabaCloudSdkGoERROR)
}

Expand Down Expand Up @@ -406,7 +397,9 @@ func (s *CbwpServiceV2) CbwpCommonBandwidthPackageAttachmentStateRefreshFunc(id
return nil, "", WrapError(err)
}

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

for _, failState := range failStates {
if currentStatus == failState {
return object, currentStatus, WrapError(Error(FailedToReachTargetStatus, currentStatus))
Expand Down
23 changes: 15 additions & 8 deletions website/docs/r/common_bandwidth_package_attachment.html.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@ subcategory: "EIP Bandwidth Plan (CBWP)"
layout: "alicloud"
page_title: "Alicloud: alicloud_common_bandwidth_package_attachment"
description: |-
Provides a Alicloud cbwp Common Bandwidth Package Attachment resource.
Provides a Alicloud CBWP Common Bandwidth Package Attachment resource.
---

# alicloud_common_bandwidth_package_attachment

Provides a cbwp Common Bandwidth Package Attachment resource. -> **NOTE:** Terraform will auto build common bandwidth package attachment while it uses `alicloud_common_bandwidth_package_attachment` to build a common bandwidth package attachment resource.
Provides a CBWP Common Bandwidth Package Attachment resource.

-> **NOTE:** Terraform will auto build common bandwidth package attachment while it uses `alicloud_common_bandwidth_package_attachment` to build a common bandwidth package attachment resource.

For information about common bandwidth package and how to use it, see [What is Common Bandwidth Package](https://www.alibabacloud.com/help/product/55092.htm).

-> **NOTE:** From version 1.194.0, the resource can set the maximum bandwidth of an EIP that is associated with an EIP bandwidth plan by `bandwidth_package_bandwidth`. see [how to use it](https://www.alibabacloud.com/help/en/eip-bandwidth-plan/latest/120327).

For information about cbwp Common Bandwidth Package Attachment and how to use it, see [What is Common Bandwidth Package Attachment](https://www.alibabacloud.com/help/product/55092.htm).
For information about CBWP Common Bandwidth Package Attachment and how to use it, see [What is Common Bandwidth Package Attachment](https://www.alibabacloud.com/help/product/55092.htm).

-> **NOTE:** Available since v1.94.0.

Expand Down Expand Up @@ -48,11 +50,16 @@ resource "alicloud_common_bandwidth_package_attachment" "default" {
## Argument Reference

The following arguments are supported:
* `bandwidth_package_bandwidth` - (Optional, Computed) The maximum bandwidth for the EIP. This value cannot be larger than the maximum bandwidth of the EIP bandwidth plan. Unit: Mbit/s.
* `bandwidth_package_id` - (Required, ForceNew) The bandwidth_package_id of the common bandwidth package attachment, the field can't be changed.
* `bandwidth_package_bandwidth` - (Optional, Computed) The maximum bandwidth for the EIP. This value cannot be larger than the maximum bandwidth of the Internet Shared Bandwidth instance. Unit: Mbit/s.
* `bandwidth_package_id` - (Required, ForceNew) The ID of the Internet Shared Bandwidth instance.
* `cancel_common_bandwidth_package_ip_bandwidth` - (Optional) Whether to cancel the maximum bandwidth configuration for the EIP. Default: false.
* `instance_id` - (Required, ForceNew) The instance_id of the common bandwidth package attachment, the field can't be changed.
* `ip_type` - (Optional, Available since v1.211.0) IP type. Set the value to **EIP**, which indicates that the EIP is added to the Internet shared bandwidth.
* `instance_id` - (Required, ForceNew) The ID of the EIP that you want to query.

You can specify up to 50 EIP IDs. Separate multiple IDs with commas (,).

-> **NOTE:** If both `EipAddress` and `AllocationId` are specified, you can specify up to 50 EIP IDs for `AllocationId`, and specify up to 50 EIPs for `EipAddress`.

* `ip_type` - (Optional) The type of IP address. Set the value to `EIP` to associate EIPs with the Internet Shared Bandwidth instance.

## Attributes Reference

Expand All @@ -69,7 +76,7 @@ The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/d

## Import

cbwp Common Bandwidth Package Attachment can be imported using the id, e.g.
CBWP Common Bandwidth Package Attachment can be imported using the id, e.g.

```shell
$ terraform import alicloud_common_bandwidth_package_attachment.example <bandwidth_package_id>:<instance_id>
Expand Down

0 comments on commit 0d8f073

Please sign in to comment.