Skip to content

Commit

Permalink
resource/alicloud_bastionhost_instance: Improves the invoking api met…
Browse files Browse the repository at this point in the history
…hod and supports refreshing credential automatically; Fixes the import does not work error
  • Loading branch information
xiaozhu36 committed Jan 7, 2025
1 parent 389e257 commit 5642205
Show file tree
Hide file tree
Showing 8 changed files with 331 additions and 419 deletions.
10 changes: 10 additions & 0 deletions alicloud/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -1809,3 +1809,13 @@ func convertPaymentTypeToChargeType(source interface{}) interface{} {
}
return source
}

func bytesToTB(bytes int64) float64 {
const (
KiB = 1024
MiB = KiB * KiB
GiB = MiB * KiB
TiB = GiB * KiB
)
return float64(bytes) / float64(TiB)
}
37 changes: 25 additions & 12 deletions alicloud/data_source_alicloud_bastionhost_instances.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package alicloud

import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"time"

"github.com/PaesslerAG/jsonpath"
util "github.com/alibabacloud-go/tea-utils/service"

"github.com/hashicorp/terraform-plugin-sdk/helper/resource"

"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
Expand Down Expand Up @@ -66,7 +66,6 @@ func dataSourceAlicloudBastionhostInstances() *schema.Resource {
"public_domain": {
Type: schema.TypeString,
Computed: true,
Optional: true,
},
"instance_status": {
Type: schema.TypeString,
Expand All @@ -80,12 +79,23 @@ func dataSourceAlicloudBastionhostInstances() *schema.Resource {
Type: schema.TypeBool,
Computed: true,
},
"storage": {
Type: schema.TypeString,
Computed: true,
},
"bandwidth": {
Type: schema.TypeString,
Computed: true,
},
"security_group_ids": {
Type: schema.TypeList,
Computed: true,
Elem: &schema.Schema{Type: schema.TypeString},
},
"tags": tagsSchema(),
"tags": {
Type: schema.TypeMap,
Computed: true,
},
},
},
},
Expand Down Expand Up @@ -139,16 +149,11 @@ func dataSourceAlicloudBastionhostInstancesRead(d *schema.ResourceData, meta int
request["Tag.*"] = tags
}
var response map[string]interface{}
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
var err error
for {
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(5*time.Minute, func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, request, &runtime)
response, err = client.RpcPost("Yundun-bastionhost", "2019-12-09", action, nil, request, true)
if err != nil {
if NeedRetry(err) {
wait()
Expand Down Expand Up @@ -210,8 +215,16 @@ func dataSourceAlicloudBastionhostInstancesRead(d *schema.ResourceData, meta int
return WrapError(err)
}
mapping["security_group_ids"] = getResp["AuthorizedSecurityGroups"]
// instance["Storage"] is in byte, and it is larger than request param
if v, err := strconv.ParseInt(getResp["Storage"].(json.Number).String(), 10, 64); err != nil {
return WrapError(err)
} else {
d.Set("storage", fmt.Sprint(bytesToTB(v)-1))
}

d.Set("bandwidth", getResp["BandwidthPackage"])

getResp2, err := bastionhostService.ListTagResources(id, "instance")
getResp2, err := bastionhostService.ListTagResources(id, "INSTANCE")
if err != nil {
return WrapError(err)
}
Expand Down
9 changes: 6 additions & 3 deletions alicloud/data_source_alicloud_bastionhost_instances_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ func TestAccAlicloudBastionhostInstancesDataSource(t *testing.T) {
"instances.0.description": fmt.Sprintf("tf_testAcc%d", rand),
"instances.0.license_code": "bhah_ent_50_asset",
"instances.0.user_vswitch_id": CHECKSET,
"instances.0.public_network_access": "true",
"instances.0.public_network_access": CHECKSET,
"instances.0.private_domain": CHECKSET,
"instances.0.instance_status": CHECKSET,
"instances.0.security_group_ids.#": "1",
Expand All @@ -93,7 +93,7 @@ func TestAccAlicloudBastionhostInstancesDataSource(t *testing.T) {
}

preCheck := func() {
testAccPreCheckWithAccountSiteType(t, DomesticSite)
testAccPreCheck(t)
}

yundunBastionhostInstanceCheckInfo.dataSourceTestCheckWithPreCheck(t, rand, preCheck, nameRegexConf, idsConf, tagsConf, allConf)
Expand Down Expand Up @@ -123,7 +123,7 @@ resource "alicloud_vswitch" "this" {
}
resource "alicloud_security_group" "default" {
vpc_id = data.alicloud_vpcs.default.ids.0
name = var.name
security_group_name = var.name
}
locals {
vswitch_id = length(data.alicloud_vswitches.default.ids) > 0 ? data.alicloud_vswitches.default.ids.0 : concat(alicloud_vswitch.this.*.id, [""])[0]
Expand All @@ -136,6 +136,9 @@ resource "alicloud_bastionhost_instance" "default" {
license_code = "bhah_ent_50_asset"
period = "1"
vswitch_id = local.vswitch_id
plan_code = "cloudbastion"
storage = "5"
bandwidth = "10"
security_group_ids = ["${alicloud_security_group.default.id}"]
tags = {
Created = "TF"
Expand Down
76 changes: 41 additions & 35 deletions alicloud/resource_alicloud_bastionhost_instance.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package alicloud

import (
"encoding/json"
"fmt"
"strconv"
"time"

log "github.com/sirupsen/logrus"

util "github.com/alibabacloud-go/tea-utils/service"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"

"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
Expand Down Expand Up @@ -134,7 +134,7 @@ func resourceAlicloudBastionhostInstance() *schema.Resource {
},
"password": {
Type: schema.TypeString,
Required: true,
Optional: true,
Sensitive: true,
},
"port": {
Expand Down Expand Up @@ -200,7 +200,7 @@ func resourceAlicloudBastionhostInstance() *schema.Resource {
},
"password": {
Type: schema.TypeString,
Required: true,
Optional: true,
Sensitive: true,
},
"port": {
Expand Down Expand Up @@ -254,13 +254,11 @@ func resourceAlicloudBastionhostInstance() *schema.Resource {
func resourceAlicloudBastionhostInstanceCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
var response map[string]interface{}
var err error
var endpoint string
action := "CreateInstance"
request := make(map[string]interface{})
parameterMapList := make([]map[string]interface{}, 0)
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "NetworkType",
"Value": "vpc",
Expand Down Expand Up @@ -296,25 +294,26 @@ func resourceAlicloudBastionhostInstanceCreate(d *schema.ResourceData, meta inte
}
request["ProductCode"] = "bastionhost"
request["ProductType"] = "bastionhost"
if client.IsInternationalAccount() {
request["ProductType"] = "bastionhost_std_public_intl"
}
parameterMapList = append(parameterMapList, map[string]interface{}{
"Code": "RegionId",
"Value": client.RegionId,
})
request["Parameter"] = parameterMapList
request["ClientToken"] = buildClientToken("CreateInstance")
runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutCreate)), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, request, &runtime)
response, err = client.RpcPostWithEndpoint("BssOpenApi", "2017-12-14", action, nil, request, true, endpoint)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
if !client.IsInternationalAccount() && IsExpectedErrors(err, []string{"NotApplicable"}) {
request["ProductType"] = "bastionhost_std_public_intl"
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
endpoint = connectivity.BssOpenAPIEndpointInternational
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
Expand All @@ -325,9 +324,6 @@ func resourceAlicloudBastionhostInstanceCreate(d *schema.ResourceData, meta inte
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, "alicloud_bastionhost_instance", action, AlibabaCloudSdkGoERROR)
}
if fmt.Sprint(response["Code"]) != "Success" {
return WrapError(fmt.Errorf("%s failed, response: %v", action, response))
}
responseData := response["Data"].(map[string]interface{})
d.SetId(fmt.Sprint(responseData["InstanceId"]))

Expand Down Expand Up @@ -377,6 +373,14 @@ func resourceAlicloudBastionhostInstanceRead(d *schema.ResourceData, meta interf
d.Set("security_group_ids", instance["AuthorizedSecurityGroups"])
d.Set("enable_public_access", instance["PublicNetworkAccess"])
d.Set("resource_group_id", instance["ResourceGroupId"])
// instance["Storage"] is in byte, and it is larger than request param
if v, err := strconv.ParseInt(instance["Storage"].(json.Number).String(), 10, 64); err != nil {
return WrapError(err)
} else {
d.Set("storage", fmt.Sprint(bytesToTB(v)-1))
}

d.Set("bandwidth", instance["BandwidthPackage"])

if fmt.Sprint(instance["PublicNetworkAccess"]) == "true" {
d.Set("public_white_list", instance["PublicWhiteList"])
Expand All @@ -388,11 +392,11 @@ func resourceAlicloudBastionhostInstanceRead(d *schema.ResourceData, meta interf
}
d.Set("plan_code", instance["PlanCode"])

tags, err := BastionhostService.DescribeTags(d.Id(), nil, TagResourceInstance)
tags, err := BastionhostService.ListTagResources(d.Id(), "INSTANCE")
if err != nil {
return WrapError(err)
}
d.Set("tags", BastionhostService.tagsToMap(tags))
d.Set("tags", tagsToMap(tags))

adAuthServer, err := BastionhostService.DescribeBastionhostAdAuthServer(d.Id())
if err != nil {
Expand All @@ -410,6 +414,7 @@ func resourceAlicloudBastionhostInstanceRead(d *schema.ResourceData, meta interf
"port": formatInt(adAuthServer["Port"]),
"server": adAuthServer["Server"],
"standby_server": adAuthServer["StandbyServer"],
"has_password": adAuthServer["HasPassword"],
}
d.Set("ad_auth_server", []map[string]interface{}{adAuthServerMap})

Expand All @@ -426,9 +431,10 @@ func resourceAlicloudBastionhostInstanceRead(d *schema.ResourceData, meta interf
"login_name_mapping": ldapAuthServer["LoginNameMapping"],
"mobile_mapping": ldapAuthServer["MobileMapping"],
"name_mapping": ldapAuthServer["NameMapping"],
"port": formatInt(ldapAuthServer["Port"]),
"port": ldapAuthServer["Port"],
"server": ldapAuthServer["Server"],
"standby_server": ldapAuthServer["StandbyServer"],
"has_password": adAuthServer["HasPassword"],
}
d.Set("ldap_auth_server", []map[string]interface{}{ldapAuthServerMap})

Expand All @@ -440,24 +446,23 @@ func resourceAlicloudBastionhostInstanceRead(d *schema.ResourceData, meta interf
}

d.Set("renewal_status", getQueryInstanceObject["RenewStatus"])
d.Set("renew_period", formatInt(getQueryInstanceObject["RenewalDuration"]))
if v, ok := getQueryInstanceObject["RenewalDuration"]; ok && v != nil {
d.Set("renew_period", getQueryInstanceObject["RenewalDuration"])
}
d.Set("renewal_period_unit", getQueryInstanceObject["RenewalDurationUnit"])

return nil
}

func resourceAlicloudBastionhostInstanceUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
conn, err := client.NewBastionhostClient()
if err != nil {
return WrapError(err)
}
bastionhostService := YundunBastionhostService{client}
var err error

d.Partial(true)

if d.HasChange("tags") {
if err := bastionhostService.setInstanceTags(d, TagResourceInstance); err != nil {
if err := bastionhostService.setInstanceTags(d, "INSTANCE"); err != nil {
return WrapError(err)
}
d.SetPartial("tags")
Expand All @@ -471,7 +476,7 @@ func resourceAlicloudBastionhostInstanceUpdate(d *schema.ResourceData, meta inte
}

if d.HasChange("resource_group_id") {
if err := bastionhostService.UpdateResourceGroup(d.Id(), d.Get("resource_group_id").(string)); err != nil {
if err := bastionhostService.UpdateResourceGroup(d.Id(), "INSTANCE", d.Get("resource_group_id").(string)); err != nil {
return WrapError(err)
}
d.SetPartial("resource_group_id")
Expand Down Expand Up @@ -562,7 +567,7 @@ func resourceAlicloudBastionhostInstanceUpdate(d *schema.ResourceData, meta inte
action := "ModifyInstanceADAuthServer"
wait := incrementalWait(3*time.Second, 3*time.Second)
err := resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutUpdate)), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, modifyAdRequest, &util.RuntimeOptions{})
response, err = client.RpcPost("Yundun-bastionhost", "2019-12-09", action, nil, modifyAdRequest, false)
if err != nil {
if NeedRetry(err) {
wait()
Expand Down Expand Up @@ -605,7 +610,7 @@ func resourceAlicloudBastionhostInstanceUpdate(d *schema.ResourceData, meta inte
action := "ModifyInstanceLDAPAuthServer"
wait := incrementalWait(3*time.Second, 3*time.Second)
err := resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutUpdate)), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, modifyLdapRequest, &util.RuntimeOptions{})
response, err = client.RpcPost("Yundun-bastionhost", "2019-12-09", action, nil, modifyLdapRequest, false)
if err != nil {
if NeedRetry(err) {
wait()
Expand All @@ -624,13 +629,17 @@ func resourceAlicloudBastionhostInstanceUpdate(d *schema.ResourceData, meta inte
}

var setRenewalResponse map[string]interface{}
var endpoint string
update := false
setRenewalReq := map[string]interface{}{
"InstanceIDs": d.Id(),
"ProductCode": "bastionhost",
"ProductType": "bastionhost",
"SubscriptionType": "Subscription",
}
if client.IsInternationalAccount() {
setRenewalReq["ProductType"] = "bastionhost_std_public_intl"
}

if !d.IsNewResource() && d.HasChange("renewal_status") {
update = true
Expand All @@ -657,21 +666,17 @@ func resourceAlicloudBastionhostInstanceUpdate(d *schema.ResourceData, meta inte

if update {
action := "SetRenewal"
conn, err := client.NewBssopenapiClient()
if err != nil {
return WrapError(err)
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutUpdate)), func() *resource.RetryError {
setRenewalResponse, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2017-12-14"), StringPointer("AK"), nil, setRenewalReq, &util.RuntimeOptions{})
setRenewalResponse, err = client.RpcPostWithEndpoint("BssOpenApi", "2017-12-14", action, nil, setRenewalReq, true, endpoint)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
if IsExpectedErrors(err, []string{"NotApplicable"}) {
conn.Endpoint = String(connectivity.BssOpenAPIEndpointInternational)
if !client.IsInternationalAccount() && IsExpectedErrors(err, []string{"NotApplicable"}) {
setRenewalReq["ProductType"] = "bastionhost_std_public_intl"
endpoint = connectivity.BssOpenAPIEndpointInternational
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
Expand Down Expand Up @@ -711,7 +716,8 @@ func resourceAlicloudBastionhostInstanceUpdate(d *schema.ResourceData, meta inte

wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutUpdate)), func() *resource.RetryError {
resp, err := conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2019-12-09"), StringPointer("AK"), nil, configInstanceWhiteListReq, &util.RuntimeOptions{})
resp, err := client.RpcPost("Yundun-bastionhost", "2019-12-09", action, nil, configInstanceWhiteListReq, false)

if err != nil {
if NeedRetry(err) {
wait()
Expand Down
Loading

0 comments on commit 5642205

Please sign in to comment.