Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

resource/alicloud_ecs_session_manager_status: Fixed the create, update error caused by state refresh #8106

Merged
merged 1 commit into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion alicloud/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -1608,7 +1608,7 @@ func Provider() terraform.ResourceProvider {
"alicloud_cloud_sso_access_configuration_provisioning": resourceAlicloudCloudSsoAccessConfigurationProvisioning(),
"alicloud_mongodb_account": resourceAlicloudMongodbAccount(),
"alicloud_mongodb_serverless_instance": resourceAlicloudMongodbServerlessInstance(),
"alicloud_ecs_session_manager_status": resourceAlicloudEcsSessionManagerStatus(),
"alicloud_ecs_session_manager_status": resourceAliCloudEcsSessionManagerStatus(),
"alicloud_cddc_dedicated_host_account": resourceAlicloudCddcDedicatedHostAccount(),
"alicloud_cr_chart_namespace": resourceAlicloudCrChartNamespace(),
"alicloud_fnf_execution": resourceAlicloudFnFExecution(),
Expand Down
120 changes: 79 additions & 41 deletions alicloud/resource_alicloud_ecs_session_manager_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ import (
"github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity"
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
)

func resourceAlicloudEcsSessionManagerStatus() *schema.Resource {
func resourceAliCloudEcsSessionManagerStatus() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudEcsSessionManagerStatusCreate,
Read: resourceAlicloudEcsSessionManagerStatusRead,
Update: resourceAlicloudEcsSessionManagerStatusUpdate,
Delete: resourceAlicloudEcsSessionManagerStatusDelete,
Create: resourceAliCloudEcsSessionManagerStatusCreate,
Read: resourceAliCloudEcsSessionManagerStatusRead,
Update: resourceAliCloudEcsSessionManagerStatusUpdate,
Delete: resourceAliCloudEcsSessionManagerStatusDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Expand All @@ -26,31 +25,36 @@ func resourceAlicloudEcsSessionManagerStatus() *schema.Resource {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"sessionManagerStatus"}, false),
ValidateFunc: StringInSlice([]string{"sessionManagerStatus"}, false),
},
"status": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{"Disabled", "Enabled"}, false),
ValidateFunc: StringInSlice([]string{"Enabled", "Disabled"}, false),
},
},
}
}

func resourceAlicloudEcsSessionManagerStatusCreate(d *schema.ResourceData, meta interface{}) error {
func resourceAliCloudEcsSessionManagerStatusCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}
action := "ModifyUserBusinessBehavior"
request := make(map[string]interface{})
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
}

request["statusKey"] = d.Get("session_manager_status_name")
request["statusValue"] = convertEcsSessionManagerStatusStatusRequest(d.Get("status").(string))
request["statusValue"] = convertEcsSessionManagerStatusStatusRequest(d.Get("status"))

runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutCreate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
err = resource.Retry(client.GetRetryTimeout(d.Timeout(schema.TimeoutCreate)), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
Expand All @@ -61,19 +65,28 @@ func resourceAlicloudEcsSessionManagerStatusCreate(d *schema.ResourceData, meta
return nil
})
addDebug(action, response, request)

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

d.SetId(fmt.Sprint(request["statusKey"]))
return resourceAlicloudEcsSessionManagerStatusRead(d, meta)

stateConf := BuildStateConf([]string{}, []string{fmt.Sprint(request["statusValue"])}, d.Timeout(schema.TimeoutCreate), 5*time.Second, ecsService.EcsSessionManagerStatusStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}

return resourceAliCloudEcsSessionManagerStatusRead(d, meta)
}
func resourceAlicloudEcsSessionManagerStatusRead(d *schema.ResourceData, meta interface{}) error {

func resourceAliCloudEcsSessionManagerStatusRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}

object, err := ecsService.DescribeEcsSessionManagerStatus(d.Id())
if err != nil {
if NotFoundError(err) {
if !d.IsNewResource() && NotFoundError(err) {
log.Printf("[DEBUG] Resource alicloud_ecs_session_manager_status ecsService.DescribeEcsSessionManagerStatus Failed!!! %s", err)
d.SetId("")
return nil
Expand All @@ -83,59 +96,84 @@ func resourceAlicloudEcsSessionManagerStatusRead(d *schema.ResourceData, meta in

d.Set("session_manager_status_name", d.Id())
d.Set("status", convertEcsSessionManagerStatusStatusResponse(object["StatusValue"]))

return nil
}
func resourceAlicloudEcsSessionManagerStatusUpdate(d *schema.ResourceData, meta interface{}) error {

func resourceAliCloudEcsSessionManagerStatusUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
ecsService := EcsService{client}
var response map[string]interface{}

update := false
request := map[string]interface{}{
"statusKey": d.Id(),
}

if d.HasChange("status") {
request["statusValue"] = convertEcsSessionManagerStatusStatusRequest(d.Get("status").(string))
}
action := "ModifyUserBusinessBehavior"
conn, err := client.NewEcsClient()
if err != nil {
return WrapError(err)
update = true
}
wait := incrementalWait(3*time.Second, 3*time.Second)
err = resource.Retry(d.Timeout(schema.TimeoutUpdate), func() *resource.RetryError {
response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{})
request["statusValue"] = convertEcsSessionManagerStatusStatusRequest(d.Get("status"))

if update {
action := "ModifyUserBusinessBehavior"
conn, err := client.NewEcsClient()
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
return WrapError(err)
}

runtime := util.RuntimeOptions{}
runtime.SetAutoretry(true)
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("2014-05-26"), StringPointer("AK"), nil, request, &runtime)
if err != nil {
if NeedRetry(err) {
wait()
return resource.RetryableError(err)
}
return resource.NonRetryableError(err)
}
return resource.NonRetryableError(err)
return nil
})
addDebug(action, response, request)

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

stateConf := BuildStateConf([]string{}, []string{fmt.Sprint(request["statusValue"])}, d.Timeout(schema.TimeoutUpdate), 5*time.Second, ecsService.EcsSessionManagerStatusStateRefreshFunc(d.Id(), []string{}))
if _, err := stateConf.WaitForState(); err != nil {
return WrapErrorf(err, IdMsg, d.Id())
}
return nil
})
addDebug(action, response, request)
if err != nil {
return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR)
}
return resourceAlicloudEcsSessionManagerStatusRead(d, meta)

return resourceAliCloudEcsSessionManagerStatusRead(d, meta)
}
func resourceAlicloudEcsSessionManagerStatusDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAlicloudEcsSessionManagerStatus. Terraform will remove this resource from the state file, however resources may remain.")

func resourceAliCloudEcsSessionManagerStatusDelete(d *schema.ResourceData, meta interface{}) error {
log.Printf("[WARN] Cannot destroy resourceAliCloudEcsSessionManagerStatus. Terraform will remove this resource from the state file, however resources may remain.")
return nil
}

func convertEcsSessionManagerStatusStatusRequest(source interface{}) interface{} {
switch source {
case "Disabled":
return "disabled"
case "Enabled":
return "enabled"
case "Disabled":
return "disabled"
}

return source
}

func convertEcsSessionManagerStatusStatusResponse(source interface{}) interface{} {
switch source {
case "disabled":
return "Disabled"
case "enabled":
return "Enabled"
case "disabled":
return "Disabled"
}

return source
}
73 changes: 51 additions & 22 deletions alicloud/resource_alicloud_ecs_session_manager_status_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,21 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/helper/resource"
)

func TestAccAlicloudECSSessionManagerStatus_basic0(t *testing.T) {
func TestAccAliCloudEcsSessionManagerStatus_basic0(t *testing.T) {
var v map[string]interface{}
resourceId := "alicloud_ecs_session_manager_status.default"
ra := resourceAttrInit(resourceId, AlicloudECSSessionManagerStatusMap0)
ra := resourceAttrInit(resourceId, AliCloudEcsSessionManagerStatusMap0)
rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} {
return &EcsService{testAccProvider.Meta().(*connectivity.AliyunClient)}
}, "DescribeEcsSessionManagerStatus")
rac := resourceAttrCheckInit(rc, ra)
testAccCheck := rac.resourceAttrMapUpdateSet()
rand := acctest.RandIntRange(10000, 99999)
name := fmt.Sprintf("tf-testacc%secssessionmanagerstatus%d", defaultRegionToTest, rand)
testAccConfig := resourceTestAccConfigFunc(resourceId, name, AlicloudECSSessionManagerStatusBasicDependence0)
testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudEcsSessionManagerStatusBasicDependence0)
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
testAccPreCheckWithEnvVariable(t, "OPEN_WITH_MAIN_ACCOUNT")

},
IDRefreshName: resourceId,
Providers: testAccProviders,
Expand Down Expand Up @@ -64,13 +62,44 @@ func TestAccAlicloudECSSessionManagerStatus_basic0(t *testing.T) {
}),
),
},
{
ResourceName: resourceId,
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func TestAccAliCloudEcsSessionManagerStatus_basic0_twin(t *testing.T) {
var v map[string]interface{}
resourceId := "alicloud_ecs_session_manager_status.default"
ra := resourceAttrInit(resourceId, AliCloudEcsSessionManagerStatusMap0)
rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} {
return &EcsService{testAccProvider.Meta().(*connectivity.AliyunClient)}
}, "DescribeEcsSessionManagerStatus")
rac := resourceAttrCheckInit(rc, ra)
testAccCheck := rac.resourceAttrMapUpdateSet()
rand := acctest.RandIntRange(10000, 99999)
name := fmt.Sprintf("tf-testacc%secssessionmanagerstatus%d", defaultRegionToTest, rand)
testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudEcsSessionManagerStatusBasicDependence0)
resource.Test(t, resource.TestCase{
PreCheck: func() {
testAccPreCheck(t)
},
IDRefreshName: resourceId,
Providers: testAccProviders,
CheckDestroy: nil,
Steps: []resource.TestStep{
{
Config: testAccConfig(map[string]interface{}{
"status": "Enabled",
"session_manager_status_name": "sessionManagerStatus",
"status": "Disabled",
}),
Check: resource.ComposeTestCheckFunc(
testAccCheck(map[string]string{
"status": "Enabled",
"session_manager_status_name": "sessionManagerStatus",
"status": "Disabled",
}),
),
},
Expand All @@ -83,17 +112,17 @@ func TestAccAlicloudECSSessionManagerStatus_basic0(t *testing.T) {
})
}

var AlicloudECSSessionManagerStatusMap0 = map[string]string{}
var AliCloudEcsSessionManagerStatusMap0 = map[string]string{}

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

func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
func TestUnitAliCloudEcsSessionManagerStatus(t *testing.T) {
p := Provider().(*schema.Provider).ResourcesMap
d, _ := schema.InternalMap(p["alicloud_ecs_session_manager_status"].Schema).Data(nil, nil)
dCreate, _ := schema.InternalMap(p["alicloud_ecs_session_manager_status"].Schema).Data(nil, nil)
Expand Down Expand Up @@ -167,7 +196,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
StatusCode: tea.Int(400),
}
})
err := resourceAlicloudEcsSessionManagerStatusCreate(d, rawClient)
err := resourceAliCloudEcsSessionManagerStatusCreate(d, rawClient)
patches.Reset()
assert.NotNil(t, err)
})
Expand All @@ -184,7 +213,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
}
return responseMock["CreateNormal"]("")
})
err := resourceAlicloudEcsSessionManagerStatusCreate(d, rawClient)
err := resourceAliCloudEcsSessionManagerStatusCreate(d, rawClient)
patches.Reset()
assert.NotNil(t, err)
})
Expand All @@ -201,7 +230,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
}
return responseMock["CreateNormal"]("")
})
err := resourceAlicloudEcsSessionManagerStatusCreate(dCreate, rawClient)
err := resourceAliCloudEcsSessionManagerStatusCreate(dCreate, rawClient)
patches.Reset()
assert.Nil(t, err)
})
Expand All @@ -219,7 +248,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
}
})

err := resourceAlicloudEcsSessionManagerStatusUpdate(d, rawClient)
err := resourceAliCloudEcsSessionManagerStatusUpdate(d, rawClient)
patches.Reset()
assert.NotNil(t, err)
})
Expand Down Expand Up @@ -251,7 +280,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
}
return responseMock["UpdateNormal"]("")
})
err := resourceAlicloudEcsSessionManagerStatusUpdate(resourceData1, rawClient)
err := resourceAliCloudEcsSessionManagerStatusUpdate(resourceData1, rawClient)
patches.Reset()
assert.NotNil(t, err)
})
Expand Down Expand Up @@ -284,7 +313,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
}
return responseMock["UpdateNormal"]("")
})
err := resourceAlicloudEcsSessionManagerStatusUpdate(resourceData1, rawClient)
err := resourceAliCloudEcsSessionManagerStatusUpdate(resourceData1, rawClient)
patches.Reset()
assert.Nil(t, err)
})
Expand All @@ -301,7 +330,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
}
return responseMock["DeleteNormal"]("")
})
err := resourceAlicloudEcsSessionManagerStatusDelete(d, rawClient)
err := resourceAliCloudEcsSessionManagerStatusDelete(d, rawClient)
patches.Reset()
assert.Nil(t, err)
})
Expand All @@ -318,7 +347,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
}
return responseMock["ReadNormal"]("")
})
err := resourceAlicloudEcsSessionManagerStatusRead(d, rawClient)
err := resourceAliCloudEcsSessionManagerStatusRead(d, rawClient)
patchDoRequest.Reset()
assert.Nil(t, err)
})
Expand All @@ -334,7 +363,7 @@ func TestUnitAlicloudECSSessionManagerStatus(t *testing.T) {
}
return responseMock["ReadNormal"]("")
})
err := resourceAlicloudEcsSessionManagerStatusRead(d, rawClient)
err := resourceAliCloudEcsSessionManagerStatusRead(d, rawClient)
patcheDorequest.Reset()
assert.NotNil(t, err)
})
Expand Down
Loading
Loading