Skip to content

Commit

Permalink
New Resource: alicloud_hbr_cross_account.
Browse files Browse the repository at this point in the history
  • Loading branch information
ChenHanZhang committed Jan 9, 2025
1 parent e3a7579 commit 6132a48
Show file tree
Hide file tree
Showing 5 changed files with 402 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 @@ -885,6 +885,7 @@ func Provider() terraform.ResourceProvider {
},
ResourcesMap: map[string]*schema.Resource{
"alicloud_cloud_control_resource": resourceAliCloudCloudControlResource(),
"alicloud_hbr_cross_account": resourceAliCloudHbrCrossAccount(),
"alicloud_oss_access_point": resourceAliCloudOssAccessPoint(),
"alicloud_oss_bucket_worm": resourceAliCloudOssBucketWorm(),
"alicloud_apig_environment": resourceAliCloudApigEnvironment(),
Expand Down
171 changes: 171 additions & 0 deletions alicloud/resource_alicloud_hbr_cross_account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
// 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 resourceAliCloudHbrCrossAccount() *schema.Resource {
return &schema.Resource{
Create: resourceAliCloudHbrCrossAccountCreate,
Read: resourceAliCloudHbrCrossAccountRead,
Delete: resourceAliCloudHbrCrossAccountDelete,
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{
"alias": {
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"create_time": {
Type: schema.TypeInt,
Computed: true,
},
"cross_account_role_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"cross_account_user_id": {
Type: schema.TypeInt,
Required: true,
ForceNew: true,
},
},
}
}

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

client := meta.(*connectivity.AliyunClient)

action := "AddCrossAccount"
var request map[string]interface{}
var response map[string]interface{}
query := make(map[string]interface{})
conn, err := client.NewHbrClient()
if err != nil {
return WrapError(err)
}
request = make(map[string]interface{})
if v, ok := d.GetOk("cross_account_user_id"); ok {
request["CrossAccountUserId"] = v
}
if v, ok := d.GetOk("cross_account_role_name"); ok {
request["CrossAccountRoleName"] = v
}

if v, ok := d.GetOk("alias"); ok {
request["Alias"] = v
}
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("2017-09-08"), StringPointer("AK"), query, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return nil
})
addDebug(action, response, request)

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

d.SetId(fmt.Sprintf("%v:%v", request["CrossAccountUserId"], request["CrossAccountRoleName"]))

return resourceAliCloudHbrCrossAccountRead(d, meta)
}

func resourceAliCloudHbrCrossAccountRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
hbrServiceV2 := HbrServiceV2{client}

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

if objectRaw["Alias"] != nil {
d.Set("alias", objectRaw["Alias"])
}
if objectRaw["CreatedTime"] != nil {
d.Set("create_time", objectRaw["CreatedTime"])
}
if objectRaw["CrossAccountRoleName"] != nil {
d.Set("cross_account_role_name", objectRaw["CrossAccountRoleName"])
}
if objectRaw["CrossAccountUserId"] != nil {
d.Set("cross_account_user_id", objectRaw["CrossAccountUserId"])
}

return nil
}

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

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

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("2017-09-08"), StringPointer("AK"), query, request, &runtime)

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

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

return nil
}
73 changes: 73 additions & 0 deletions alicloud/resource_alicloud_hbr_cross_account_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
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 Hbr CrossAccount. >>> Resource test cases, automatically generated.
// Case CrossAccount验证 9417
func TestAccAliCloudHbrCrossAccount_basic9417(t *testing.T) {
var v map[string]interface{}
resourceId := "alicloud_hbr_cross_account.default"
ra := resourceAttrInit(resourceId, AlicloudHbrCrossAccountMap9417)
rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} {
return &HbrServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)}
}, "DescribeHbrCrossAccount")
rac := resourceAttrCheckInit(rc, ra)
testAccCheck := rac.resourceAttrMapUpdateSet()
rand := acctest.RandIntRange(10000, 99999)
name := fmt.Sprintf("tf-testacc%shbrcrossaccount%d", defaultRegionToTest, rand)
testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudHbrCrossAccountBasicDependence9417)
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-guangzhou"})
testAccPreCheck(t)
},
IDRefreshName: resourceId,
Providers: testAccProviders,
CheckDestroy: rac.checkResourceDestroy(),
Steps: []resource.TestStep{
{
Config: testAccConfig(map[string]interface{}{
"cross_account_user_id": "1",
"cross_account_role_name": "zhenyuan-时间引用:GetCurrentUnixTimeStamp(0,'ms','s')",
"alias": "镇元测试用例",
}),
Check: resource.ComposeTestCheckFunc(
testAccCheck(map[string]string{
"cross_account_user_id": "1",
"cross_account_role_name": "zhenyuan-时间引用:GetCurrentUnixTimeStamp(0,'ms','s')",
"alias": "镇元测试用例",
}),
),
},
{
ResourceName: resourceId,
ImportState: true,
ImportStateVerify: true,
ImportStateVerifyIgnore: []string{},
},
},
})
}

var AlicloudHbrCrossAccountMap9417 = map[string]string{
"create_time": CHECKSET,
}

func AlicloudHbrCrossAccountBasicDependence9417(name string) string {
return fmt.Sprintf(`
variable "name" {
default = "%s"
}
`, name)
}

// Test Hbr CrossAccount. <<< Resource test cases, automatically generated.
92 changes: 92 additions & 0 deletions alicloud/service_alicloud_hbr_v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,95 @@ func (s *HbrServiceV2) HbrPolicyBindingStateRefreshFunc(id string, field string,
}

// DescribeHbrPolicyBinding >>> Encapsulated.
// DescribeHbrCrossAccount <<< Encapsulated get interface for Hbr CrossAccount.

func (s *HbrServiceV2) DescribeHbrCrossAccount(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 := "DescribeCrossAccounts"
conn, err := client.NewHbrClient()
if err != nil {
return object, WrapError(err)
}
request = make(map[string]interface{})
query = make(map[string]interface{})

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("2017-09-08"), StringPointer("AK"), query, request, &runtime)

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

v, err := jsonpath.Get("$.CrossAccounts.CrossAccount[*]", response)
if err != nil {
return object, WrapErrorf(err, FailedGetAttributeMsg, id, "$.CrossAccounts.CrossAccount[*]", response)
}

if len(v.([]interface{})) == 0 {
return object, WrapErrorf(Error(GetNotFoundMessage("CrossAccount", id)), NotFoundMsg, response)
}

result, _ := v.([]interface{})
for _, v := range result {
item := v.(map[string]interface{})
if fmt.Sprint(item["CrossAccountRoleName"]) != parts[1] {
continue
}
if fmt.Sprint(item["CrossAccountUserId"]) != parts[0] {
continue
}
return item, nil
}
return object, WrapErrorf(Error(GetNotFoundMessage("CrossAccount", id)), NotFoundMsg, response)
}

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

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

if strings.HasPrefix(field, "#") {
v, _ := jsonpath.Get(strings.TrimPrefix(field, "#"), object)
if v != nil {
currentStatus = "#CHECKSET"
}
}

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

// DescribeHbrCrossAccount >>> Encapsulated.
Loading

0 comments on commit 6132a48

Please sign in to comment.