From 5bb48258f66713a82ef1ebceb1c1eb2e1d54503e Mon Sep 17 00:00:00 2001 From: MrWolong Date: Thu, 28 Nov 2024 18:19:44 +0800 Subject: [PATCH] resource/alicloud_ecs_auto_snapshot_policy: Refactored the resource alicloud_ecs_auto_snapshot_policy; Added the field auto_snapshot_policy_name, copy_encryption_configuration, resource_group_id, create_time, region_id; Deprecated the field name --- alicloud/provider.go | 4 +- ...ource_alicloud_ecs_auto_snapshot_policy.go | 432 +++++++--- ..._alicloud_ecs_auto_snapshot_policy_test.go | 813 +++++++++++------- alicloud/service_alicloud_ecs_v2.go | 56 ++ .../r/ecs_auto_snapshot_policy.html.markdown | 66 +- 5 files changed, 937 insertions(+), 434 deletions(-) diff --git a/alicloud/provider.go b/alicloud/provider.go index 683e0ab8f427..3b72770845d7 100644 --- a/alicloud/provider.go +++ b/alicloud/provider.go @@ -1049,7 +1049,7 @@ func Provider() terraform.ResourceProvider { "alicloud_network_interface": resourceAliCloudEcsNetworkInterface(), "alicloud_network_interface_attachment": resourceAliCloudEcsNetworkInterfaceAttachment(), "alicloud_snapshot": resourceAliCloudEcsSnapshot(), - "alicloud_snapshot_policy": resourceAlicloudEcsAutoSnapshotPolicy(), + "alicloud_snapshot_policy": resourceAliCloudEcsAutoSnapshotPolicy(), "alicloud_launch_template": resourceAliCloudEcsLaunchTemplate(), "alicloud_security_group": resourceAliyunSecurityGroup(), "alicloud_security_group_rule": resourceAliyunSecurityGroupRule(), @@ -1381,7 +1381,7 @@ func Provider() terraform.ResourceProvider { "alicloud_vpc_flow_log": resourceAliCloudVpcFlowLog(), "alicloud_brain_industrial_pid_loop": resourceAlicloudBrainIndustrialPidLoop(), "alicloud_quotas_quota_application": resourceAliCloudQuotasQuotaApplication(), - "alicloud_ecs_auto_snapshot_policy": resourceAlicloudEcsAutoSnapshotPolicy(), + "alicloud_ecs_auto_snapshot_policy": resourceAliCloudEcsAutoSnapshotPolicy(), "alicloud_rds_parameter_group": resourceAlicloudRdsParameterGroup(), "alicloud_ecs_launch_template": resourceAliCloudEcsLaunchTemplate(), "alicloud_resource_manager_control_policy": resourceAlicloudResourceManagerControlPolicy(), diff --git a/alicloud/resource_alicloud_ecs_auto_snapshot_policy.go b/alicloud/resource_alicloud_ecs_auto_snapshot_policy.go index 86bdf8919966..2f315f1201a5 100644 --- a/alicloud/resource_alicloud_ecs_auto_snapshot_policy.go +++ b/alicloud/resource_alicloud_ecs_auto_snapshot_policy.go @@ -1,49 +1,82 @@ +// Package alicloud. This file is generated automatically. Please do not modify it manually, thank you! package alicloud import ( "fmt" - "log" - "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" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "time" ) -func resourceAlicloudEcsAutoSnapshotPolicy() *schema.Resource { +func resourceAliCloudEcsAutoSnapshotPolicy() *schema.Resource { return &schema.Resource{ - Create: resourceAlicloudEcsAutoSnapshotPolicyCreate, - Read: resourceAlicloudEcsAutoSnapshotPolicyRead, - Update: resourceAlicloudEcsAutoSnapshotPolicyUpdate, - Delete: resourceAlicloudEcsAutoSnapshotPolicyDelete, + Create: resourceAliCloudEcsAutoSnapshotPolicyCreate, + Read: resourceAliCloudEcsAutoSnapshotPolicyRead, + Update: resourceAliCloudEcsAutoSnapshotPolicyUpdate, + Delete: resourceAliCloudEcsAutoSnapshotPolicyDelete, Importer: &schema.ResourceImporter{ State: schema.ImportStatePassthrough, }, Timeouts: &schema.ResourceTimeout{ - Create: schema.DefaultTimeout(2 * time.Minute), - Delete: schema.DefaultTimeout(3 * time.Minute), + Create: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(5 * time.Minute), + Delete: schema.DefaultTimeout(5 * time.Minute), }, Schema: map[string]*schema.Schema{ + "auto_snapshot_policy_name": { + Type: schema.TypeString, + Optional: true, + ConflictsWith: []string{"name"}, + Computed: true, + }, "copied_snapshots_retention_days": { Type: schema.TypeInt, Optional: true, - Default: -1, + Computed: true, + }, + "copy_encryption_configuration": { + Type: schema.TypeList, + Optional: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "kms_key_id": { + Type: schema.TypeString, + Optional: true, + }, + "encrypted": { + Type: schema.TypeBool, + Optional: true, + //Computed: true, + }, + }, + }, + }, + "create_time": { + Type: schema.TypeString, + Computed: true, }, "enable_cross_region_copy": { Type: schema.TypeBool, Optional: true, }, - "name": { + "region_id": { Type: schema.TypeString, - Optional: true, + Computed: true, }, "repeat_weekdays": { - Type: schema.TypeSet, + Type: schema.TypeList, Required: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "resource_group_id": { + Type: schema.TypeString, + Optional: true, + //Computed: true, }, "retention_days": { Type: schema.TypeInt, @@ -57,62 +90,93 @@ func resourceAlicloudEcsAutoSnapshotPolicy() *schema.Resource { "target_copy_regions": { Type: schema.TypeSet, Optional: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, + Elem: &schema.Schema{Type: schema.TypeString}, }, "time_points": { - Type: schema.TypeSet, + Type: schema.TypeList, Required: true, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, + Elem: &schema.Schema{Type: schema.TypeString}, + }, + "name": { + Type: schema.TypeString, + Optional: true, + Computed: true, + Deprecated: "Field `name` has been deprecated from provider version 1.236.0. New field `auto_snapshot_policy_name` instead.", }, }, } } -func resourceAlicloudEcsAutoSnapshotPolicyCreate(d *schema.ResourceData, meta interface{}) error { +func resourceAliCloudEcsAutoSnapshotPolicyCreate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) - ecsService := EcsService{client} - var response map[string]interface{} + action := "CreateAutoSnapshotPolicy" - request := make(map[string]interface{}) + var request map[string]interface{} + var response map[string]interface{} + query := make(map[string]interface{}) conn, err := client.NewEcsClient() if err != nil { return WrapError(err) } - if v, ok := d.GetOk("copied_snapshots_retention_days"); ok { - request["CopiedSnapshotsRetentionDays"] = v + request = make(map[string]interface{}) + request["regionId"] = client.RegionId + + if v, ok := d.GetOk("name"); ok || d.HasChange("name") { + request["autoSnapshotPolicyName"] = v } + if v, ok := d.GetOk("auto_snapshot_policy_name"); ok { + request["autoSnapshotPolicyName"] = v + } + request["retentionDays"] = d.Get("retention_days") if v, ok := d.GetOkExists("enable_cross_region_copy"); ok { request["EnableCrossRegionCopy"] = v } + if v, ok := d.GetOkExists("copied_snapshots_retention_days"); ok { + request["CopiedSnapshotsRetentionDays"] = v + } + if v, ok := d.GetOk("resource_group_id"); ok { + request["ResourceGroupId"] = v + } + if v, ok := d.GetOk("copy_encryption_configuration"); ok { + jsonPathResult5, err := jsonpath.Get("$[0].encrypted", v) + if err == nil && jsonPathResult5 != "" { + request["CopyEncryptionConfiguration.Encrypted"] = jsonPathResult5 + } + } + if v, ok := d.GetOk("copy_encryption_configuration"); ok { + jsonPathResult6, err := jsonpath.Get("$[0].kms_key_id", v) + if err == nil && jsonPathResult6 != "" { + request["CopyEncryptionConfiguration.KMSKeyId"] = jsonPathResult6 + } + } + jsonPathResult7, err := jsonpath.Get("$", d.Get("time_points")) + if err == nil { + request["timePoints"] = convertListToJsonString(jsonPathResult7.([]interface{})) + } - if v, ok := d.GetOk("name"); ok { - request["autoSnapshotPolicyName"] = v + jsonPathResult8, err := jsonpath.Get("$", d.Get("repeat_weekdays")) + if err == nil { + request["repeatWeekdays"] = convertListToJsonString(jsonPathResult8.([]interface{})) } - request["regionId"] = client.RegionId - request["repeatWeekdays"] = convertListToJsonString(d.Get("repeat_weekdays").(*schema.Set).List()) - request["retentionDays"] = d.Get("retention_days") if v, ok := d.GetOk("tags"); ok { - count := 1 - for key, value := range v.(map[string]interface{}) { - request[fmt.Sprintf("Tag.%d.Key", count)] = key - request[fmt.Sprintf("Tag.%d.Value", count)] = value - count++ - } + tagsMap := ConvertTags(v.(map[string]interface{})) + request = expandTagsToMap(request, tagsMap) } + if v, ok := d.GetOk("target_copy_regions"); ok { - request["TargetCopyRegions"] = convertListToJsonString(v.(*schema.Set).List()) + jsonPathResult9, err := jsonpath.Get("$", v) + if err == nil && jsonPathResult9 != "" { + request["TargetCopyRegions"] = convertListToJsonString(jsonPathResult9.(*schema.Set).List()) + } } - - request["timePoints"] = convertListToJsonString(d.Get("time_points").(*schema.Set).List()) - wait := incrementalWait(3*time.Second, 3*time.Second) + 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("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{}) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), query, request, &runtime) if err != nil { if NeedRetry(err) { wait() @@ -120,116 +184,244 @@ func resourceAlicloudEcsAutoSnapshotPolicyCreate(d *schema.ResourceData, meta in } return resource.NonRetryableError(err) } - addDebug(action, response, request) return nil }) + addDebug(action, response, request) + if err != nil { return WrapErrorf(err, DefaultErrorMsg, "alicloud_ecs_auto_snapshot_policy", action, AlibabaCloudSdkGoERROR) } d.SetId(fmt.Sprint(response["AutoSnapshotPolicyId"])) - stateConf := BuildStateConf([]string{}, []string{"Normal"}, d.Timeout(schema.TimeoutCreate), 10*time.Second, ecsService.EcsAutoSnapshotPolicyStateRefreshFunc(d.Id(), []string{})) - if _, err := stateConf.WaitForState(); err != nil { - return WrapErrorf(err, IdMsg, d.Id()) - } - return resourceAlicloudEcsAutoSnapshotPolicyRead(d, meta) + return resourceAliCloudEcsAutoSnapshotPolicyRead(d, meta) } -func resourceAlicloudEcsAutoSnapshotPolicyRead(d *schema.ResourceData, meta interface{}) error { + +func resourceAliCloudEcsAutoSnapshotPolicyRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) - ecsService := EcsService{client} - object, err := ecsService.DescribeEcsAutoSnapshotPolicy(d.Id()) + ecsServiceV2 := EcsServiceV2{client} + + objectRaw, err := ecsServiceV2.DescribeEcsAutoSnapshotPolicy(d.Id()) if err != nil { - if NotFoundError(err) { - log.Printf("[DEBUG] Resource alicloud_ecs_auto_snapshot_policy ecsService.DescribeEcsAutoSnapshotPolicy Failed!!! %s", err) + if !d.IsNewResource() && NotFoundError(err) { + log.Printf("[DEBUG] Resource alicloud_ecs_auto_snapshot_policy DescribeEcsAutoSnapshotPolicy Failed!!! %s", err) d.SetId("") return nil } return WrapError(err) } - d.Set("copied_snapshots_retention_days", formatInt(object["CopiedSnapshotsRetentionDays"])) - d.Set("enable_cross_region_copy", object["EnableCrossRegionCopy"]) - d.Set("name", object["AutoSnapshotPolicyName"]) - if object["RepeatWeekdays"] != nil { - if repeatWeekdays, err := convertJsonStringToList(object["RepeatWeekdays"].(string)); err != nil { + + if objectRaw["AutoSnapshotPolicyName"] != nil { + d.Set("auto_snapshot_policy_name", objectRaw["AutoSnapshotPolicyName"]) + } + if objectRaw["CopiedSnapshotsRetentionDays"] != nil { + d.Set("copied_snapshots_retention_days", objectRaw["CopiedSnapshotsRetentionDays"]) + } + if objectRaw["CreationTime"] != nil { + d.Set("create_time", objectRaw["CreationTime"]) + } + if objectRaw["EnableCrossRegionCopy"] != nil { + d.Set("enable_cross_region_copy", objectRaw["EnableCrossRegionCopy"]) + } + if objectRaw["RegionId"] != nil { + d.Set("region_id", objectRaw["RegionId"]) + } + if objectRaw["ResourceGroupId"] != nil { + d.Set("resource_group_id", objectRaw["ResourceGroupId"]) + } + if objectRaw["RetentionDays"] != nil { + d.Set("retention_days", objectRaw["RetentionDays"]) + } + if objectRaw["Status"] != nil { + d.Set("status", objectRaw["Status"]) + } + + copyEncryptionConfigurationMaps := make([]map[string]interface{}, 0) + copyEncryptionConfigurationMap := make(map[string]interface{}) + copyEncryptionConfiguration1Raw := make(map[string]interface{}) + if objectRaw["CopyEncryptionConfiguration"] != nil { + copyEncryptionConfiguration1Raw = objectRaw["CopyEncryptionConfiguration"].(map[string]interface{}) + } + if len(copyEncryptionConfiguration1Raw) > 0 { + if copyEncryptionConfiguration1Raw["Encrypted"] != nil { + copyEncryptionConfigurationMap["encrypted"] = copyEncryptionConfiguration1Raw["Encrypted"] + } + + if copyEncryptionConfiguration1Raw["KMSKeyId"] != nil { + copyEncryptionConfigurationMap["kms_key_id"] = copyEncryptionConfiguration1Raw["KMSKeyId"] + } + + copyEncryptionConfigurationMaps = append(copyEncryptionConfigurationMaps, copyEncryptionConfigurationMap) + } + + if objectRaw["CopyEncryptionConfiguration"] != nil { + if err := d.Set("copy_encryption_configuration", copyEncryptionConfigurationMaps); err != nil { + return err + } + } + + tagsMaps, _ := jsonpath.Get("$.Tags.Tag", objectRaw) + d.Set("tags", tagsToMap(tagsMaps)) + + if objectRaw["RepeatWeekdays"] != nil { + if repeatWeekdays, err := convertJsonStringToList(objectRaw["RepeatWeekdays"].(string)); err != nil { return WrapError(err) } else { d.Set("repeat_weekdays", repeatWeekdays) } } - d.Set("retention_days", formatInt(object["RetentionDays"])) - d.Set("status", object["Status"]) - d.Set("tags", tagsToMap(object["Tags"].(map[string]interface{})["Tag"])) - if object["TargetCopyRegions"] != nil { - if targetCopyRegions, err := convertJsonStringToList(object["TargetCopyRegions"].(string)); err != nil { + + if objectRaw["TargetCopyRegions"] != nil { + if targetCopyRegions, err := convertJsonStringToList(objectRaw["TargetCopyRegions"].(string)); err != nil { return WrapError(err) } else { d.Set("target_copy_regions", targetCopyRegions) } } - if object["TimePoints"] != nil { - if timePoints, err := convertJsonStringToList(object["TimePoints"].(string)); err != nil { + + if objectRaw["TimePoints"] != nil { + if timePoints, err := convertJsonStringToList(objectRaw["TimePoints"].(string)); err != nil { return WrapError(err) } else { d.Set("time_points", timePoints) } } + + d.Set("name", d.Get("auto_snapshot_policy_name")) return nil } -func resourceAlicloudEcsAutoSnapshotPolicyUpdate(d *schema.ResourceData, meta interface{}) error { + +func resourceAliCloudEcsAutoSnapshotPolicyUpdate(d *schema.ResourceData, meta interface{}) error { client := meta.(*connectivity.AliyunClient) - ecsService := EcsService{client} + var request map[string]interface{} + var response map[string]interface{} + var query map[string]interface{} + update := false + d.Partial(true) + + action := "ModifyAutoSnapshotPolicyEx" conn, err := client.NewEcsClient() if err != nil { return WrapError(err) } - var response map[string]interface{} - d.Partial(true) + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["autoSnapshotPolicyId"] = d.Id() + request["regionId"] = client.RegionId + if d.HasChange("retention_days") { + update = true + } + request["retentionDays"] = d.Get("retention_days") + if d.HasChange("repeat_weekdays") { + update = true + } + jsonPathResult1, err := jsonpath.Get("$", d.Get("repeat_weekdays")) + if err == nil { + request["repeatWeekdays"] = convertListToJsonString(jsonPathResult1.([]interface{})) + } - if !d.IsNewResource() && d.HasChange("tags") { - if err := ecsService.SetResourceTags(d, "snapshotpolicy"); err != nil { - return WrapError(err) - } - d.SetPartial("tags") + if d.HasChange("time_points") { + update = true } - update := false - request := map[string]interface{}{ - "autoSnapshotPolicyId": d.Id(), + jsonPathResult2, err := jsonpath.Get("$", d.Get("time_points")) + if err == nil { + request["timePoints"] = convertListToJsonString(jsonPathResult2.([]interface{})) } - request["RegionId"] = client.RegionId - if !d.IsNewResource() && d.HasChange("copied_snapshots_retention_days") { + + if d.HasChange("copied_snapshots_retention_days") { update = true request["CopiedSnapshotsRetentionDays"] = d.Get("copied_snapshots_retention_days") } - if !d.IsNewResource() && d.HasChange("enable_cross_region_copy") { + + if d.HasChange("enable_cross_region_copy") { + update = true + } + if v, ok := d.GetOkExists("enable_cross_region_copy"); ok { + request["EnableCrossRegionCopy"] = v + } + + if d.HasChange("target_copy_regions") { update = true - request["EnableCrossRegionCopy"] = d.Get("enable_cross_region_copy") } - if !d.IsNewResource() && d.HasChange("name") { + if v, ok := d.GetOk("target_copy_regions"); ok { + jsonPathResult9, err := jsonpath.Get("$", v) + if err == nil && jsonPathResult9 != "" { + request["TargetCopyRegions"] = convertListToJsonString(jsonPathResult9.(*schema.Set).List()) + } + } + + if d.HasChange("name") { update = true request["autoSnapshotPolicyName"] = d.Get("name") } - if !d.IsNewResource() && d.HasChange("repeat_weekdays") { + + if d.HasChange("auto_snapshot_policy_name") { update = true - request["repeatWeekdays"] = convertListToJsonString(d.Get("repeat_weekdays").(*schema.Set).List()) + request["autoSnapshotPolicyName"] = d.Get("auto_snapshot_policy_name") } - if !d.IsNewResource() && d.HasChange("retention_days") { + + if d.HasChange("copy_encryption_configuration.0.encrypted") { update = true - request["retentionDays"] = d.Get("retention_days") } - if !d.IsNewResource() && d.HasChange("target_copy_regions") { + if v, ok := d.GetOk("copy_encryption_configuration"); ok { + jsonPathResult5, err := jsonpath.Get("$[0].encrypted", v) + if err == nil && jsonPathResult5 != "" { + request["CopyEncryptionConfiguration.Encrypted"] = jsonPathResult5 + } + } + + if d.HasChange("copy_encryption_configuration.0.kms_key_id") { update = true - request["TargetCopyRegions"] = convertListToJsonString(d.Get("target_copy_regions").(*schema.Set).List()) } - if !d.IsNewResource() && d.HasChange("time_points") { + if v, ok := d.GetOk("copy_encryption_configuration"); ok { + jsonPathResult6, err := jsonpath.Get("$[0].kms_key_id", v) + if err == nil && jsonPathResult6 != "" { + request["CopyEncryptionConfiguration.KMSKeyId"] = jsonPathResult6 + } + } + + if update { + 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("2014-05-26"), 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, d.Id(), action, AlibabaCloudSdkGoERROR) + } + } + update = false + action = "JoinResourceGroup" + conn, err = client.NewEcsClient() + if err != nil { + return WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["ResourceId"] = d.Id() + request["RegionId"] = client.RegionId + request["ResourceType"] = "snapshotpolicy" + if _, ok := d.GetOk("resource_group_id"); ok && d.HasChange("resource_group_id") { update = true - request["timePoints"] = convertListToJsonString(d.Get("time_points").(*schema.Set).List()) + request["ResourceGroupId"] = d.Get("resource_group_id") } + if update { - action := "ModifyAutoSnapshotPolicyEx" - wait := incrementalWait(3*time.Second, 3*time.Second) + 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("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{}) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), query, request, &runtime) if err != nil { if NeedRetry(err) { wait() @@ -237,54 +429,62 @@ func resourceAlicloudEcsAutoSnapshotPolicyUpdate(d *schema.ResourceData, meta in } return resource.NonRetryableError(err) } - addDebug(action, response, request) return nil }) + addDebug(action, response, request) if err != nil { return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } - d.SetPartial("copied_snapshots_retention_days") - d.SetPartial("enable_cross_region_copy") - d.SetPartial("name") - d.SetPartial("repeat_weekdays") - d.SetPartial("retention_days") - d.SetPartial("target_copy_regions") - d.SetPartial("time_points") + } + + if d.HasChange("tags") { + ecsServiceV2 := EcsServiceV2{client} + if err := ecsServiceV2.SetResourceTags(d, "snapshotpolicy"); err != nil { + return WrapError(err) + } } d.Partial(false) - return resourceAlicloudEcsAutoSnapshotPolicyRead(d, meta) + return resourceAliCloudEcsAutoSnapshotPolicyRead(d, meta) } -func resourceAlicloudEcsAutoSnapshotPolicyDelete(d *schema.ResourceData, meta interface{}) error { + +func resourceAliCloudEcsAutoSnapshotPolicyDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*connectivity.AliyunClient) action := "DeleteAutoSnapshotPolicy" + var request map[string]interface{} var response map[string]interface{} + query := make(map[string]interface{}) conn, err := client.NewEcsClient() if err != nil { return WrapError(err) } - request := map[string]interface{}{ - "autoSnapshotPolicyId": d.Id(), - } - + request = make(map[string]interface{}) + request["autoSnapshotPolicyId"] = d.Id() request["regionId"] = client.RegionId - wait := incrementalWait(3*time.Second, 10*time.Second) + + 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("2014-05-26"), StringPointer("AK"), nil, request, &util.RuntimeOptions{}) + response, err = conn.DoRequest(StringPointer(action), nil, StringPointer("POST"), StringPointer("2014-05-26"), StringPointer("AK"), query, request, &runtime) + if err != nil { - if IsExpectedErrors(err, []string{"InternalError", "OperationConflict", "ServiceUnavailable", "SnapshotCreatedDisk", "SnapshotCreatedImage"}) || NeedRetry(err) { + if NeedRetry(err) { wait() return resource.RetryableError(err) } return resource.NonRetryableError(err) } - addDebug(action, response, request) return nil }) + addDebug(action, response, request) + if err != nil { - if IsExpectedErrors(err, []string{"ParameterInvalid"}) { + if NotFoundError(err) { return nil } return WrapErrorf(err, DefaultErrorMsg, d.Id(), action, AlibabaCloudSdkGoERROR) } + return nil } diff --git a/alicloud/resource_alicloud_ecs_auto_snapshot_policy_test.go b/alicloud/resource_alicloud_ecs_auto_snapshot_policy_test.go index a8c8e5a2df80..f38c3f1e2837 100644 --- a/alicloud/resource_alicloud_ecs_auto_snapshot_policy_test.go +++ b/alicloud/resource_alicloud_ecs_auto_snapshot_policy_test.go @@ -2,6 +2,7 @@ package alicloud import ( "fmt" + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" "log" "os" "reflect" @@ -18,8 +19,6 @@ import ( "github.com/PaesslerAG/jsonpath" util "github.com/alibabacloud-go/tea-utils/service" - "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" - "github.com/alibabacloud-go/tea-rpc/client" "github.com/aliyun/terraform-provider-alicloud/alicloud/connectivity" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" @@ -35,7 +34,7 @@ func init() { func testSweepEcsAutoSnapshotPolicy(region string) error { rawClient, err := sharedClientForRegion(region) if err != nil { - return WrapErrorf(err, "Error getting Alicloud client.") + return WrapErrorf(err, "Error getting AliCloud client.") } client := rawClient.(*connectivity.AliyunClient) @@ -97,278 +96,7 @@ func testSweepEcsAutoSnapshotPolicy(region string) error { return nil } -func TestAccAlicloudECSAutoSnapshotPolicyBasic(t *testing.T) { - - resourceId := "alicloud_ecs_auto_snapshot_policy.default" - randInt := acctest.RandIntRange(10000, 99999) - name := fmt.Sprintf("tf-testAccSnapshotPolicyBasic%d", randInt) - basicMap := map[string]string{ - "name": name, - "repeat_weekdays.#": "1", - "retention_days": "-1", - "time_points.#": "1", - } - var v map[string]interface{} - ra := resourceAttrInit(resourceId, basicMap) - serviceFunc := func() interface{} { - return &EcsService{testAccProvider.Meta().(*connectivity.AliyunClient)} - } - rc := resourceCheckInit(resourceId, &v, serviceFunc) - rac := resourceAttrCheckInit(rc, ra) - testAccCheck := rac.resourceAttrMapUpdateSet() - - testAccConfig := resourceTestAccConfigFunc(resourceId, name, func(name string) string { - return "" - }) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { - testAccPreCheck(t) - }, - - // module name - IDRefreshName: resourceId, - - Providers: testAccProviders, - CheckDestroy: rac.checkResourceDestroy(), - Steps: []resource.TestStep{ - { - Config: testAccConfig(map[string]interface{}{ - "name": name, - "repeat_weekdays": []string{"1"}, - "retention_days": "-1", - "time_points": []string{"1"}, - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(nil), - ), - }, - { - Config: testAccConfig(map[string]interface{}{ - "name": name + "_change", - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(map[string]string{ - "name": name + "_change", - }), - ), - }, - { - Config: testAccConfig(map[string]interface{}{ - "repeat_weekdays": []string{"1", "2"}, - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(map[string]string{ - "repeat_weekdays.#": "2", - }), - ), - }, - { - Config: testAccConfig(map[string]interface{}{ - "retention_days": "1", - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(map[string]string{ - "retention_days": "1", - }), - ), - }, - { - Config: testAccConfig(map[string]interface{}{ - "time_points": []string{"1", "2"}, - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(map[string]string{ - "time_points.#": "2", - }), - ), - }, - { - Config: testAccConfig(map[string]interface{}{ - "tags": map[string]string{ - "Created": "TF", - "For": "Test", - }, - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(map[string]string{ - "tags.%": "2", - "tags.Created": "TF", - "tags.For": "Test", - }), - ), - }, - { - Config: testAccConfig(map[string]interface{}{ - "enable_cross_region_copy": "true", - "target_copy_regions": []string{"cn-beijing"}, - "copied_snapshots_retention_days": "2", - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(map[string]string{ - "enable_cross_region_copy": "true", - "target_copy_regions.#": "1", - "copied_snapshots_retention_days": "2", - }), - ), - }, - { - Config: testAccConfig(map[string]interface{}{ - "name": name, - "repeat_weekdays": []string{"1"}, - "retention_days": "-1", - "time_points": []string{"1"}, - "enable_cross_region_copy": "false", - "target_copy_regions": []string{"cn-shanghai"}, - "copied_snapshots_retention_days": "-1", - "tags": map[string]string{ - "Created": "TF-update", - "For": "Test-update", - }, - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(map[string]string{ - "name": name, - "repeat_weekdays.#": "1", - "retention_days": "-1", - "time_points.#": "1", - "enable_cross_region_copy": "false", - "target_copy_regions.#": "1", - "copied_snapshots_retention_days": "-1", - "tags.%": "2", - "tags.Created": "TF-update", - "tags.For": "Test-update", - }), - ), - }, - }, - }) -} - -func TestAccAlicloudECSSnapshotPolicyMulti(t *testing.T) { - - resourceId := "alicloud_snapshot_policy.default.4" - randInt := acctest.RandIntRange(10000, 99999) - var v map[string]interface{} - name := fmt.Sprintf("tf-testAccSnapshotPolicyMulti%d", randInt) - basicMap := map[string]string{ - "name": name, - "repeat_weekdays.#": "1", - "retention_days": "-1", - "time_points.#": "1", - } - ra := resourceAttrInit(resourceId, basicMap) - serviceFunc := func() interface{} { - return &EcsService{testAccProvider.Meta().(*connectivity.AliyunClient)} - } - rc := resourceCheckInit(resourceId, &v, serviceFunc) - rac := resourceAttrCheckInit(rc, ra) - testAccCheck := rac.resourceAttrMapUpdateSet() - testAccConfig := resourceTestAccConfigFunc(resourceId, name, func(name string) string { - return "" - }) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { - testAccPreCheck(t) - }, - - // module name - IDRefreshName: resourceId, - - Providers: testAccProviders, - CheckDestroy: rac.checkResourceDestroy(), - Steps: []resource.TestStep{ - { - Config: testAccConfig(map[string]interface{}{ - "count": "5", - "name": name, - "repeat_weekdays": []string{"1"}, - "retention_days": "-1", - "time_points": []string{"1"}, - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(nil), - ), - }, - }, - }) -} - -func TestAccAlicloudECSAutoSnapshotPolicyBasic1(t *testing.T) { - - resourceId := "alicloud_ecs_auto_snapshot_policy.default" - randInt := acctest.RandIntRange(10000, 99999) - name := fmt.Sprintf("tf-testAccSnapshotPolicyBasic%d", randInt) - basicMap := map[string]string{ - "name": name, - "repeat_weekdays.#": "1", - "retention_days": "-1", - "time_points.#": "1", - } - var v map[string]interface{} - ra := resourceAttrInit(resourceId, basicMap) - serviceFunc := func() interface{} { - return &EcsService{testAccProvider.Meta().(*connectivity.AliyunClient)} - } - rc := resourceCheckInit(resourceId, &v, serviceFunc) - rac := resourceAttrCheckInit(rc, ra) - testAccCheck := rac.resourceAttrMapUpdateSet() - - testAccConfig := resourceTestAccConfigFunc(resourceId, name, func(name string) string { - return "" - }) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { - testAccPreCheck(t) - }, - - // module name - IDRefreshName: resourceId, - - Providers: testAccProviders, - CheckDestroy: rac.checkResourceDestroy(), - Steps: []resource.TestStep{ - { - Config: testAccConfig(map[string]interface{}{ - "name": name, - "repeat_weekdays": []string{"1"}, - "retention_days": "-1", - "time_points": []string{"1"}, - "copied_snapshots_retention_days": "2", - "enable_cross_region_copy": "true", - "target_copy_regions": []string{"cn-beijing"}, - "tags": map[string]string{ - "Created": "TF", - "For": "Test", - }, - }), - Check: resource.ComposeTestCheckFunc( - testAccCheck(map[string]string{ - "name": name, - "repeat_weekdays.#": "1", - "retention_days": "-1", - "time_points.#": "1", - "copied_snapshots_retention_days": "2", - "enable_cross_region_copy": "true", - "target_copy_regions.#": "1", - "tags.%": "2", - "tags.Created": "TF", - "tags.For": "Test", - }), - ), - }, - { - ResourceName: resourceId, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) -} - -func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { +func TestUnitAliCloudECSAutoSnapshotPolicy(t *testing.T) { p := Provider().(*schema.Provider).ResourcesMap d, _ := schema.InternalMap(p["alicloud_ecs_auto_snapshot_policy"].Schema).Data(nil, nil) dCreate, _ := schema.InternalMap(p["alicloud_ecs_auto_snapshot_policy"].Schema).Data(nil, nil) @@ -468,7 +196,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { StatusCode: tea.Int(400), } }) - err := resourceAlicloudEcsAutoSnapshotPolicyCreate(d, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyCreate(d, rawClient) patches.Reset() assert.NotNil(t, err) }) @@ -485,7 +213,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["CreateNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyCreate(d, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyCreate(d, rawClient) patches.Reset() assert.NotNil(t, err) }) @@ -502,7 +230,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["CreateNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyCreate(dCreate, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyCreate(dCreate, rawClient) patches.Reset() assert.Nil(t, err) }) @@ -520,7 +248,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["CreateNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyCreate(dCreate, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyCreate(dCreate, rawClient) patches.Reset() assert.NotNil(t, err) }) @@ -538,7 +266,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } }) - err := resourceAlicloudEcsAutoSnapshotPolicyUpdate(d, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyUpdate(d, rawClient) patches.Reset() assert.NotNil(t, err) }) @@ -580,7 +308,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["UpdateNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyUpdate(resourceData1, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyUpdate(resourceData1, rawClient) patches.Reset() assert.NotNil(t, err) }) @@ -622,7 +350,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["UpdateNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyUpdate(resourceData1, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyUpdate(resourceData1, rawClient) patches.Reset() assert.Nil(t, err) }) @@ -637,7 +365,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { StatusCode: tea.Int(400), } }) - err := resourceAlicloudEcsAutoSnapshotPolicyDelete(d, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyDelete(d, rawClient) patches.Reset() assert.NotNil(t, err) }) @@ -654,7 +382,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["DeleteNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyDelete(d, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyDelete(d, rawClient) patches.Reset() assert.NotNil(t, err) }) @@ -671,7 +399,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["DeleteNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyDelete(d, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyDelete(d, rawClient) patches.Reset() assert.Nil(t, err) }) @@ -688,7 +416,7 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["ReadNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyRead(d, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyRead(d, rawClient) patcheDorequest.Reset() assert.Nil(t, err) }) @@ -704,8 +432,519 @@ func TestUnitAlicloudECSAutoSnapshotPolicy(t *testing.T) { } return responseMock["ReadNormal"]("") }) - err := resourceAlicloudEcsAutoSnapshotPolicyRead(d, rawClient) + err := resourceAliCloudEcsAutoSnapshotPolicyRead(d, rawClient) patcheDorequest.Reset() assert.NotNil(t, err) }) } + +// Test Ecs AutoSnapshotPolicy. >>> Resource test cases, automatically generated. +// Case 自动快照策略 7893 +func TestAccAliCloudEcsAutoSnapshotPolicy_basic7893(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_ecs_auto_snapshot_policy.default" + ra := resourceAttrInit(resourceId, AliCloudEcsAutoSnapshotPolicyMap7893) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &EcsServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeEcsAutoSnapshotPolicy") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(1, 999) + name := fmt.Sprintf("tf_testacc%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudEcsAutoSnapshotPolicyBasicDependence7893) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"}) + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "repeat_weekdays": []string{"1", "2"}, + "retention_days": "1", + "time_points": []string{"1", "2"}, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "repeat_weekdays.#": "2", + "retention_days": "1", + "time_points.#": "2", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "auto_snapshot_policy_name": name, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "auto_snapshot_policy_name": name, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "copied_snapshots_retention_days": "2", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "copied_snapshots_retention_days": "2", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "enable_cross_region_copy": "true", + "target_copy_regions": []string{"cn-hangzhou"}, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "enable_cross_region_copy": "true", + "target_copy_regions.#": "1", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "copy_encryption_configuration": []map[string]interface{}{ + { + "encrypted": "true", + "kms_key_id": "${alicloud_kms_key.default.id}", + }, + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "copy_encryption_configuration.#": "1", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "repeat_weekdays": []string{"3", "4", "5"}, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "repeat_weekdays.#": "3", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "resource_group_id": "${data.alicloud_resource_manager_resource_groups.default.ids.1}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "resource_group_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "retention_days": "2", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "retention_days": "2", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF-update", + "For": "Test-update", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF-update", + "tags.For": "Test-update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "0", + "tags.Created": REMOVEKEY, + "tags.For": REMOVEKEY, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "time_points": []string{"7", "6", "5"}, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "time_points.#": "3", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAliCloudEcsAutoSnapshotPolicy_basic7893_twin(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_ecs_auto_snapshot_policy.default" + ra := resourceAttrInit(resourceId, AliCloudEcsAutoSnapshotPolicyMap7893) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &EcsServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeEcsAutoSnapshotPolicy") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(1, 999) + name := fmt.Sprintf("tf_testacc%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudEcsAutoSnapshotPolicyBasicDependence7893) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"}) + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "repeat_weekdays": []string{"1", "2"}, + "retention_days": "1", + "time_points": []string{"1", "2"}, + "auto_snapshot_policy_name": name, + "copied_snapshots_retention_days": "2", + "copy_encryption_configuration": []map[string]interface{}{ + { + "encrypted": "true", + "kms_key_id": "${alicloud_kms_key.default.id}", + }, + }, + "enable_cross_region_copy": "true", + "resource_group_id": "${data.alicloud_resource_manager_resource_groups.default.ids.1}", + "target_copy_regions": []string{"cn-hangzhou"}, + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "repeat_weekdays.#": "2", + "retention_days": "1", + "time_points.#": "2", + "auto_snapshot_policy_name": name, + "copied_snapshots_retention_days": "2", + "copy_encryption_configuration.#": "1", + "enable_cross_region_copy": "true", + "resource_group_id": CHECKSET, + "target_copy_regions.#": "1", + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +var AliCloudEcsAutoSnapshotPolicyMap7893 = map[string]string{ + "status": CHECKSET, + "create_time": CHECKSET, + "region_id": CHECKSET, +} + +func AliCloudEcsAutoSnapshotPolicyBasicDependence7893(name string) string { + return fmt.Sprintf(` + variable "name" { + default = "%s" + } + + data "alicloud_resource_manager_resource_groups" "default" { + status = "OK" + } + + resource "alicloud_kms_key" "default" { + description = var.name + pending_window_in_days = 7 + key_state = "Enabled" + } +`, name) +} + +// Case 适配废弃字段name 8035 +func TestAccAliCloudEcsAutoSnapshotPolicy_basic8035(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_ecs_auto_snapshot_policy.default" + ra := resourceAttrInit(resourceId, AliCloudEcsAutoSnapshotPolicyMap7893) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &EcsServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeEcsAutoSnapshotPolicy") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(1, 999) + name := fmt.Sprintf("tf_testacc%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudEcsAutoSnapshotPolicyBasicDependence7893) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"}) + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "repeat_weekdays": []string{"1", "2"}, + "retention_days": "1", + "time_points": []string{"1", "2"}, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "repeat_weekdays.#": "2", + "retention_days": "1", + "time_points.#": "2", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "name": name, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "name": name, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "copied_snapshots_retention_days": "2", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "copied_snapshots_retention_days": "2", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "enable_cross_region_copy": "true", + "target_copy_regions": []string{"cn-hangzhou"}, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "enable_cross_region_copy": "true", + "target_copy_regions.#": "1", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "copy_encryption_configuration": []map[string]interface{}{ + { + "encrypted": "true", + "kms_key_id": "${alicloud_kms_key.default.id}", + }, + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "copy_encryption_configuration.#": "1", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "repeat_weekdays": []string{"3", "4", "5"}, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "repeat_weekdays.#": "3", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "resource_group_id": "${data.alicloud_resource_manager_resource_groups.default.ids.1}", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "resource_group_id": CHECKSET, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "retention_days": "2", + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "retention_days": "2", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": map[string]string{ + "Created": "TF-update", + "For": "Test-update", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "2", + "tags.Created": "TF-update", + "tags.For": "Test-update", + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "tags": REMOVEKEY, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "tags.%": "0", + "tags.Created": REMOVEKEY, + "tags.For": REMOVEKEY, + }), + ), + }, + { + Config: testAccConfig(map[string]interface{}{ + "time_points": []string{"7", "6", "5"}, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "time_points.#": "3", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +func TestAccAliCloudEcsAutoSnapshotPolicy_basic8035_twin(t *testing.T) { + var v map[string]interface{} + resourceId := "alicloud_ecs_auto_snapshot_policy.default" + ra := resourceAttrInit(resourceId, AliCloudEcsAutoSnapshotPolicyMap7893) + rc := resourceCheckInitWithDescribeMethod(resourceId, &v, func() interface{} { + return &EcsServiceV2{testAccProvider.Meta().(*connectivity.AliyunClient)} + }, "DescribeEcsAutoSnapshotPolicy") + rac := resourceAttrCheckInit(rc, ra) + testAccCheck := rac.resourceAttrMapUpdateSet() + rand := acctest.RandIntRange(1, 999) + name := fmt.Sprintf("tf_testacc%d", rand) + testAccConfig := resourceTestAccConfigFunc(resourceId, name, AliCloudEcsAutoSnapshotPolicyBasicDependence7893) + resource.Test(t, resource.TestCase{ + PreCheck: func() { + testAccPreCheckWithRegions(t, true, []connectivity.Region{"cn-hangzhou"}) + testAccPreCheck(t) + }, + IDRefreshName: resourceId, + Providers: testAccProviders, + CheckDestroy: rac.checkResourceDestroy(), + Steps: []resource.TestStep{ + { + Config: testAccConfig(map[string]interface{}{ + "repeat_weekdays": []string{"1", "2"}, + "retention_days": "1", + "time_points": []string{"1", "2"}, + "name": name, + "copied_snapshots_retention_days": "2", + "copy_encryption_configuration": []map[string]interface{}{ + { + "encrypted": "true", + "kms_key_id": "${alicloud_kms_key.default.id}", + }, + }, + "enable_cross_region_copy": "true", + "resource_group_id": "${data.alicloud_resource_manager_resource_groups.default.ids.1}", + "target_copy_regions": []string{"cn-hangzhou"}, + "tags": map[string]string{ + "Created": "TF", + "For": "Test", + }, + }), + Check: resource.ComposeTestCheckFunc( + testAccCheck(map[string]string{ + "repeat_weekdays.#": "2", + "retention_days": "1", + "time_points.#": "2", + "name": name, + "copied_snapshots_retention_days": "2", + "copy_encryption_configuration.#": "1", + "enable_cross_region_copy": "true", + "resource_group_id": CHECKSET, + "target_copy_regions.#": "1", + "tags.%": "2", + "tags.Created": "TF", + "tags.For": "Test", + }), + ), + }, + { + ResourceName: resourceId, + ImportState: true, + ImportStateVerify: true, + }, + }, + }) +} + +// Test Ecs AutoSnapshotPolicy. <<< Resource test cases, automatically generated. diff --git a/alicloud/service_alicloud_ecs_v2.go b/alicloud/service_alicloud_ecs_v2.go index 1e861ae48ff2..a076671e26ad 100644 --- a/alicloud/service_alicloud_ecs_v2.go +++ b/alicloud/service_alicloud_ecs_v2.go @@ -264,3 +264,59 @@ func (s *EcsServiceV2) EcsImageStateRefreshFunc(id string, field string, failSta } // DescribeEcsImage >>> Encapsulated. + +// DescribeEcsAutoSnapshotPolicy <<< Encapsulated get interface for Ecs AutoSnapshotPolicy. + +func (s *EcsServiceV2) DescribeEcsAutoSnapshotPolicy(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{} + action := "DescribeAutoSnapshotPolicyEx" + conn, err := client.NewEcsClient() + if err != nil { + return object, WrapError(err) + } + request = make(map[string]interface{}) + query = make(map[string]interface{}) + request["AutoSnapshotPolicyId"] = id + request["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("2014-05-26"), 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("$.AutoSnapshotPolicies.AutoSnapshotPolicy[*]", response) + if err != nil { + return object, WrapErrorf(Error(GetNotFoundMessage("AutoSnapshotPolicy", id)), NotFoundMsg, response) + } + + if len(v.([]interface{})) == 0 { + return object, WrapErrorf(Error(GetNotFoundMessage("AutoSnapshotPolicy", id)), NotFoundMsg, response) + } + + currentStatus := v.([]interface{})[0].(map[string]interface{})["Status"] + if currentStatus == nil { + return object, WrapErrorf(Error(GetNotFoundMessage("AutoSnapshotPolicy", id)), NotFoundMsg, response) + } + + return v.([]interface{})[0].(map[string]interface{}), nil +} + +// DescribeEcsAutoSnapshotPolicy >>> Encapsulated. diff --git a/website/docs/r/ecs_auto_snapshot_policy.html.markdown b/website/docs/r/ecs_auto_snapshot_policy.html.markdown index 9a35c73a1878..98b922bbfbcb 100644 --- a/website/docs/r/ecs_auto_snapshot_policy.html.markdown +++ b/website/docs/r/ecs_auto_snapshot_policy.html.markdown @@ -2,18 +2,17 @@ subcategory: "ECS" layout: "alicloud" page_title: "Alicloud: alicloud_ecs_auto_snapshot_policy" -sidebar_current: "docs-alicloud-resource-ecs-auto-snapshot-policy" description: |- Provides a Alicloud ECS Auto Snapshot Policy resource. --- -# alicloud\_ecs\_auto\_snapshot\_policy +# alicloud_ecs_auto_snapshot_policy Provides a ECS Auto Snapshot Policy resource. For information about ECS Auto Snapshot Policy and how to use it, see [What is Auto Snapshot Policy](https://www.alibabacloud.com/help/en/doc-detail/25527.htm). --> **NOTE:** Available in v1.117.0+. +-> **NOTE:** Available since v1.117.0. ## Example Usage @@ -27,7 +26,7 @@ Basic Usage ```terraform resource "alicloud_ecs_auto_snapshot_policy" "example" { - name = "tf-testAcc" + name = "terraform-example" repeat_weekdays = ["1", "2", "3"] retention_days = -1 time_points = ["1", "22", "23"] @@ -38,39 +37,48 @@ resource "alicloud_ecs_auto_snapshot_policy" "example" { ## Argument Reference The following arguments are supported: - -* `name` - (Optional) The snapshot policy name. -* `repeat_weekdays` - (Required) The automatic snapshot repetition dates. The unit of measurement is day and the repeating cycle is a week. Value range: [1, 7], which represents days starting from Monday to Sunday, for example 1 indicates Monday. When you want to schedule multiple automatic snapshot tasks for a disk in a week, you can set the RepeatWeekdays to an array. - - A maximum of seven time points can be selected. - - The format is an JSON array of ["1", "2", … "7"] and the time points are separated by commas (,). -* `retention_days` - (Required) The snapshot retention time, and the unit of measurement is day. Optional values: - - -1: The automatic snapshots are retained permanently. - - [1, 65536]: The number of days retained. - Default value: -1. -* `time_points` - (Required) The automatic snapshot creation schedule, and the unit of measurement is hour. Value range: [0, 23], which represents from 00:00 to 24:00, for example 1 indicates 01:00. When you want to schedule multiple automatic snapshot tasks for a disk in a day, you can set the TimePoints to an array. - - A maximum of 24 time points can be selected. - - The format is an JSON array of ["0", "1", … "23"] and the time points are separated by commas (,). -* `target_copy_regions` - (Optional) The destination region to which the snapshot is copied. You can set a destination region. -* `copied_snapshots_retention_days` - (Optional) The retention period of the snapshot copied across regions. - - -1: The snapshot is permanently retained. - - [1, 65535]: The automatic snapshot is retained for the specified number of days. - Default value: -1. -* `enable_cross_region_copy` - (Optional) Specifies whether to enable the system to automatically copy snapshots across regions. -* `tags` - (Optional) A mapping of tags to assign to the resource. +* `auto_snapshot_policy_name` - (Optional, Available since v1.236.0) The name of the automatic snapshot policy. The name must be 2 to 128 characters in length. The name must start with a letter and cannot start with http:// or https://. The name can contain letters, digits, colons (:), underscores (_), and hyphens (-). +* `copied_snapshots_retention_days` - (Optional, Int) The retention period of the snapshot copy in the destination region. Unit: days. Valid values: + - `-1`: The snapshot copy is retained until it is deleted. + - `1` to `65535`: The snapshot copy is retained for the specified number of days. After the retention period of the snapshot copy expires, the snapshot copy is automatically deleted. +* `copy_encryption_configuration` - (Optional, Set, Available since v1.236.0) The encryption parameters for cross-region snapshot replication. See [`copy_encryption_configuration`](#copy_encryption_configuration) below. +* `enable_cross_region_copy` - (Optional, Bool) Specifies whether to enable cross-region replication for snapshots. Valid values: `true`, `false`. +* `repeat_weekdays` - (Required, List) The days of the week on which to create automatic snapshots. Valid values: `1` to `7`, which correspond to the days of the week. For example, `1` indicates Monday. One or more days can be specified. +* `resource_group_id` - (Optional, Available since v1.236.0) The ID of the resource group. If this parameter is specified to query resources, up to 1,000 resources that belong to the specified resource group can be displayed in the response. +* `retention_days` - (Required, Int) The retention period of the automatic snapshots. Unit: days. Valid values: + - `-1`: Automatic snapshots are retained until they are deleted. + - `1` to `65536`: Auto snapshots are retained for the specified number of days. After the retention period of auto snapshots expires, the auto snapshots are automatically deleted. +* `tags` - (Optional, Map) A mapping of tags to assign to the resource. +* `target_copy_regions` - (Optional, List) The destination region to which to copy the snapshot. You can specify only a single destination region. +* `time_points` - (Required, List) The points in time of the day at which to create automatic snapshots. + + The time is displayed in UTC+8. Unit: hours. Valid values: `0` to `23`, which correspond to the 24 points in time on the hour from 00:00:00 to 23:00:00. For example, 1 indicates 01:00:00. Multiple points in time can be specified. + + The parameter value is a JSON array that contains up to 24 points in time separated by commas (,). Example: ["0", "1", ... "23"]. + +The following arguments will be discarded. Please use new fields as soon as possible: +* `name` - (Deprecated since v1.236.0). Field `name` has been deprecated from provider version 1.236.0. New field `auto_snapshot_policy_name` instead. + +### `copy_encryption_configuration` + +The copy_encryption_configuration supports the following: +* `encrypted` - (Optional, Bool) Whether to enable encryption for cross-region snapshot replication. Default value: `false`. Valid values: `true`, `false`. +* `kms_key_id` - (Optional) The ID of the Key Management Service (KMS) key used to encrypt snapshots in cross-region snapshot replication. ## Attributes Reference The following attributes are exported: - * `id` - The resource ID in terraform of Auto Snapshot Policy. -* `status` - The status of Auto Snapshot Policy. +* `create_time` - (Available since v1.236.0) The time when the automatic snapshot policy was created. The time follows the ISO 8601 standard in the yyyy-MM-ddThh:mm:ssZ format. The time is displayed in UTC. +* `region_id` - (Available since v1.236.0) The region ID of the automatic snapshot policy. +* `status` - The status of the automatic snapshot policy. -### Timeouts +## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration-0-11/resources.html#timeouts) for certain actions: - -* `create` - (Defaults to 2 mins) Used when create the Auto Snapshot Policy. -* `delete` - (Defaults to 3 mins) Used when delete the Auto Snapshot Policy. +* `create` - (Defaults to 5 mins) Used when create the Auto Snapshot Policy. +* `delete` - (Defaults to 5 mins) Used when delete the Auto Snapshot Policy. +* `update` - (Defaults to 5 mins) Used when update the Auto Snapshot Policy. ## Import