From e74f2b867ac0c93738a700b79c086a00fb32b889 Mon Sep 17 00:00:00 2001 From: henglu Date: Sat, 5 Jun 2021 11:08:28 +0800 Subject: [PATCH 1/4] add resource "azurerm_data_protection_backup_policy_postgresql" --- .../services/dataprotection/client/client.go | 9 +- ...ction_backup_policy_postgresql_resource.go | 652 ++++++++++++++++++ ..._backup_policy_postgresql_resource_test.go | 208 ++++++ .../dataprotection/parse/backup_policy.go | 75 ++ .../parse/backup_policy_test.go | 128 ++++ .../services/dataprotection/registration.go | 3 +- .../services/dataprotection/resourceids.go | 1 + .../validate/backup_policy_id.go | 23 + .../validate/backup_policy_id_test.go | 88 +++ ...ion_backup_policy_postgresql.html.markdown | 154 +++++ 10 files changed, 1338 insertions(+), 3 deletions(-) create mode 100644 azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go create mode 100644 azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go create mode 100644 azurerm/internal/services/dataprotection/parse/backup_policy.go create mode 100644 azurerm/internal/services/dataprotection/parse/backup_policy_test.go create mode 100644 azurerm/internal/services/dataprotection/validate/backup_policy_id.go create mode 100644 azurerm/internal/services/dataprotection/validate/backup_policy_id_test.go create mode 100644 website/docs/r/data_protection_backup_policy_postgresql.html.markdown diff --git a/azurerm/internal/services/dataprotection/client/client.go b/azurerm/internal/services/dataprotection/client/client.go index 65836b48c876..67cfcb9e1eb2 100644 --- a/azurerm/internal/services/dataprotection/client/client.go +++ b/azurerm/internal/services/dataprotection/client/client.go @@ -6,14 +6,19 @@ import ( ) type Client struct { - BackupVaultClient *dataprotection.BackupVaultsClient + BackupVaultClient *dataprotection.BackupVaultsClient + BackupPolicyClient *dataprotection.BackupPoliciesClient } func NewClient(o *common.ClientOptions) *Client { backupVaultClient := dataprotection.NewBackupVaultsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&backupVaultClient.Client, o.ResourceManagerAuthorizer) + backupPolicyClient := dataprotection.NewBackupPoliciesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) + o.ConfigureClient(&backupPolicyClient.Client, o.ResourceManagerAuthorizer) + return &Client{ - BackupVaultClient: &backupVaultClient, + BackupVaultClient: &backupVaultClient, + BackupPolicyClient: &backupPolicyClient, } } diff --git a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go new file mode 100644 index 000000000000..f4b84c0dfcc0 --- /dev/null +++ b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go @@ -0,0 +1,652 @@ +package dataprotection + +import ( + "fmt" + "log" + "regexp" + "strings" + "time" + + "github.com/Azure/go-autorest/autorest/date" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/dataprotection/legacysdk/dataprotection" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/dataprotection/parse" + azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/validation" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +func resourceDataProtectionBackupPolicyPostgreSql() *schema.Resource { + return &schema.Resource{ + Create: resourceDataProtectionBackupPolicyPostgreSqlCreate, + Read: resourceDataProtectionBackupPolicyPostgreSqlRead, + Delete: resourceDataProtectionBackupPolicyPostgreSqlDelete, + + Timeouts: &schema.ResourceTimeout{ + Create: schema.DefaultTimeout(30 * time.Minute), + Read: schema.DefaultTimeout(5 * time.Minute), + Update: schema.DefaultTimeout(30 * time.Minute), + Delete: schema.DefaultTimeout(30 * time.Minute), + }, + + Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error { + _, err := parse.BackupPolicyID(id) + return err + }), + + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringMatch( + regexp.MustCompile("^[-a-zA-Z0-9]{3,150}$"), + "DataProtection BackupPolicy name must be 3 - 150 characters long, contain only letters, numbers and hyphens.", + ), + }, + + "resource_group_name": azure.SchemaResourceGroupName(), + + "vault_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "backup_rules": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "repeating_time_intervals": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + }, + }, + }, + }, + + "default_retention_duration": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "retention_rules": { + Type: schema.TypeList, + Optional: true, + ForceNew: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "duration": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + + "tagging_criteria": { + Type: schema.TypeList, + Required: true, + ForceNew: true, + MaxItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "absolute_criteria": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + ValidateFunc: validation.StringInSlice([]string{ + string(dataprotection.AllBackup), + string(dataprotection.FirstOfDay), + string(dataprotection.FirstOfMonth), + string(dataprotection.FirstOfWeek), + string(dataprotection.FirstOfYear), + }, false), + }, + + "days_of_month": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + MinItems: 1, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "date": { + Type: schema.TypeInt, + Optional: true, + ForceNew: true, + }, + + "is_last": { + Type: schema.TypeBool, + Optional: true, + ForceNew: true, + }, + }, + }, + }, + + "days_of_the_week": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.IsDayOfTheWeek(false), + }, + }, + + "months_of_year": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.IsMonth(false), + }, + }, + + "schedule_times": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.IsRFC3339Time, + }, + }, + + "weeks_of_the_month": { + Type: schema.TypeSet, + Optional: true, + ForceNew: true, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, + ValidateFunc: validation.StringInSlice([]string{ + string(dataprotection.First), + string(dataprotection.Second), + string(dataprotection.Third), + string(dataprotection.Fourth), + string(dataprotection.Last), + }, false), + }, + }, + }, + }, + }, + + "tagging_priority": { + Type: schema.TypeInt, + Required: true, + ForceNew: true, + }, + }, + }, + }, + }, + } +} +func resourceDataProtectionBackupPolicyPostgreSqlCreate(d *schema.ResourceData, meta interface{}) error { + subscriptionId := meta.(*clients.Client).Account.SubscriptionId + client := meta.(*clients.Client).DataProtection.BackupPolicyClient + ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + name := d.Get("name").(string) + resourceGroup := d.Get("resource_group_name").(string) + vaultName := d.Get("vault_name").(string) + + id := parse.NewBackupPolicyID(subscriptionId, resourceGroup, vaultName, name) + + existing, err := client.Get(ctx, id.BackupVaultName, id.ResourceGroup, id.Name) + if err != nil { + if !utils.ResponseWasNotFound(existing.Response) { + return fmt.Errorf("checking for existing DataProtection BackupPolicy (%q): %+v", id, err) + } + } + if !utils.ResponseWasNotFound(existing.Response) { + return tf.ImportAsExistsError("azurerm_data_protection_backup_policy_postgresql", id.ID()) + } + + taggingCriteria := expandBackupPolicyPostgreSqlTaggingCriteriaArray(d.Get("retention_rules").([]interface{})) + policyRules := make([]dataprotection.BasicBasePolicyRule, 0) + policyRules = append(policyRules, expandBackupPolicyPostgreSqlAzureBackupRuleArray(d.Get("backup_rules").([]interface{}), taggingCriteria)...) + policyRules = append(policyRules, expandBackupPolicyPostgreSqlDefaultAzureRetentionRule(d.Get("default_retention_duration"))) + policyRules = append(policyRules, expandBackupPolicyPostgreSqlAzureRetentionRuleArray(d.Get("retention_rules").([]interface{}))...) + parameters := dataprotection.BaseBackupPolicyResource{ + Properties: &dataprotection.BackupPolicy{ + PolicyRules: &policyRules, + DatasourceTypes: &[]string{"Microsoft.DBforPostgreSQL/servers/databases"}, + ObjectType: dataprotection.ObjectTypeBackupPolicy, + }, + } + + if _, err := client.CreateOrUpdate(ctx, id.BackupVaultName, id.ResourceGroup, id.Name, parameters); err != nil { + return fmt.Errorf("creating/updating DataProtection BackupPolicy (%q): %+v", id, err) + } + + d.SetId(id.ID()) + return resourceDataProtectionBackupPolicyPostgreSqlRead(d, meta) +} + +func resourceDataProtectionBackupPolicyPostgreSqlRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).DataProtection.BackupPolicyClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.BackupPolicyID(d.Id()) + if err != nil { + return err + } + + resp, err := client.Get(ctx, id.BackupVaultName, id.ResourceGroup, id.Name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[INFO] dataprotection %q does not exist - removing from state", d.Id()) + d.SetId("") + return nil + } + return fmt.Errorf("retrieving DataProtection BackupPolicy (%q): %+v", id, err) + } + d.Set("name", id.Name) + d.Set("resource_group_name", id.ResourceGroup) + d.Set("vault_name", id.BackupVaultName) + if resp.Properties != nil { + if props, ok := resp.Properties.AsBackupPolicy(); ok { + if err := d.Set("backup_rules", flattenBackupPolicyPostgreSqlBackupRuleArray(props.PolicyRules)); err != nil { + return fmt.Errorf("setting `backup_rules`: %+v", err) + } + if err := d.Set("default_retention_duration", flattenBackupPolicyPostgreSqlDefaultRetentionRuleDuration(props.PolicyRules)); err != nil { + return fmt.Errorf("setting `default_retention_duration`: %+v", err) + } + if err := d.Set("retention_rules", flattenBackupPolicyPostgreSqlRetentionRuleArray(props.PolicyRules)); err != nil { + return fmt.Errorf("setting `retention_rules`: %+v", err) + } + } + } + return nil +} + +func resourceDataProtectionBackupPolicyPostgreSqlDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).DataProtection.BackupPolicyClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.BackupPolicyID(d.Id()) + if err != nil { + return err + } + + if resp, err := client.Delete(ctx, id.BackupVaultName, id.ResourceGroup, id.Name); err != nil { + if utils.ResponseWasNotFound(resp) { + return nil + } + + return fmt.Errorf("deleting DataProtection BackupPolicy (%q): %+v", id, err) + } + return nil +} + +func expandBackupPolicyPostgreSqlAzureBackupRuleArray(input []interface{}, taggingCriteria *[]dataprotection.TaggingCriteria) []dataprotection.BasicBasePolicyRule { + results := make([]dataprotection.BasicBasePolicyRule, 0) + for _, item := range input { + v := item.(map[string]interface{}) + results = append(results, dataprotection.AzureBackupRule{ + Name: utils.String(v["name"].(string)), + ObjectType: dataprotection.ObjectTypeAzureBackupRule, + DataStore: &dataprotection.DataStoreInfoBase{ + DataStoreType: dataprotection.VaultStore, + ObjectType: utils.String("DataStoreInfoBase"), + }, + BackupParameters: &dataprotection.AzureBackupParams{ + BackupType: utils.String("Full"), + ObjectType: dataprotection.ObjectTypeAzureBackupParams, + }, + Trigger: dataprotection.ScheduleBasedTriggerContext{ + Schedule: &dataprotection.BackupSchedule{ + RepeatingTimeIntervals: utils.ExpandStringSlice(v["repeating_time_intervals"].([]interface{})), + }, + TaggingCriteria: taggingCriteria, + ObjectType: dataprotection.ObjectTypeScheduleBasedTriggerContext, + }, + }) + } + return results +} + +func expandBackupPolicyPostgreSqlAzureRetentionRuleArray(input []interface{}) []dataprotection.BasicBasePolicyRule { + results := make([]dataprotection.BasicBasePolicyRule, 0) + for _, item := range input { + v := item.(map[string]interface{}) + results = append(results, dataprotection.AzureRetentionRule{ + Name: utils.String(v["name"].(string)), + ObjectType: dataprotection.ObjectTypeAzureRetentionRule, + IsDefault: utils.Bool(false), + Lifecycles: &[]dataprotection.SourceLifeCycle{ + { + DeleteAfter: dataprotection.AbsoluteDeleteOption{ + Duration: utils.String(v["duration"].(string)), + ObjectType: dataprotection.ObjectTypeAbsoluteDeleteOption, + }, + SourceDataStore: &dataprotection.DataStoreInfoBase{ + DataStoreType: "VaultStore", + ObjectType: utils.String("DataStoreInfoBase"), + }, + TargetDataStoreCopySettings: &[]dataprotection.TargetCopySetting{}, + }, + }, + }) + } + return results +} + +func expandBackupPolicyPostgreSqlDefaultAzureRetentionRule(input interface{}) dataprotection.BasicBasePolicyRule { + return dataprotection.AzureRetentionRule{ + Name: utils.String("Default"), + ObjectType: dataprotection.ObjectTypeAzureRetentionRule, + IsDefault: utils.Bool(true), + Lifecycles: &[]dataprotection.SourceLifeCycle{ + { + DeleteAfter: dataprotection.AbsoluteDeleteOption{ + Duration: utils.String(input.(string)), + ObjectType: dataprotection.ObjectTypeAbsoluteDeleteOption, + }, + SourceDataStore: &dataprotection.DataStoreInfoBase{ + DataStoreType: "VaultStore", + ObjectType: utils.String("DataStoreInfoBase"), + }, + TargetDataStoreCopySettings: &[]dataprotection.TargetCopySetting{}, + }, + }, + } +} + +func expandBackupPolicyPostgreSqlTaggingCriteriaArray(input []interface{}) *[]dataprotection.TaggingCriteria { + results := []dataprotection.TaggingCriteria{ + { + Criteria: nil, + IsDefault: utils.Bool(true), + TaggingPriority: utils.Int64(99), + TagInfo: &dataprotection.RetentionTag{ + ID: utils.String("Default_"), + TagName: utils.String("Default"), + }, + }, + } + for _, item := range input { + v := item.(map[string]interface{}) + results = append(results, dataprotection.TaggingCriteria{ + Criteria: expandBackupPolicyPostgreSqlCriteriaArray(v["tagging_criteria"].([]interface{})), + IsDefault: utils.Bool(false), + TaggingPriority: utils.Int64(int64(v["tagging_priority"].(int))), + TagInfo: &dataprotection.RetentionTag{ + ID: utils.String(v["name"].(string) + "_"), + TagName: utils.String(v["name"].(string)), + }, + }) + } + return &results +} + +func expandBackupPolicyPostgreSqlCriteriaArray(input []interface{}) *[]dataprotection.BasicBackupCriteria { + results := make([]dataprotection.BasicBackupCriteria, 0) + for _, item := range input { + v := item.(map[string]interface{}) + var absoluteCriteria []dataprotection.AbsoluteMarker + if absoluteCriteriaRaw := v["absolute_criteria"].(string); len(absoluteCriteriaRaw) > 0 { + absoluteCriteria = []dataprotection.AbsoluteMarker{dataprotection.AbsoluteMarker(absoluteCriteriaRaw)} + } + + var daysOfMonth []dataprotection.Day + if v["days_of_month"].(*schema.Set).Len() > 0 { + daysOfMonth = make([]dataprotection.Day, 0) + for _, value := range v["days_of_month"].(*schema.Set).List() { + v := value.(map[string]interface{}) + daysOfMonth = append(daysOfMonth, dataprotection.Day{ + Date: utils.Int32(int32(v["date"].(int))), + IsLast: utils.Bool(v["is_last"].(bool)), + }) + } + } + + var daysOfTheWeek []dataprotection.DayOfWeek + if v["days_of_the_week"].(*schema.Set).Len() > 0 { + daysOfTheWeek = make([]dataprotection.DayOfWeek, 0) + for _, value := range v["days_of_the_week"].(*schema.Set).List() { + daysOfTheWeek = append(daysOfTheWeek, dataprotection.DayOfWeek(value.(string))) + } + } + + var monthsOfYear []dataprotection.Month + if v["months_of_year"].(*schema.Set).Len() > 0 { + monthsOfYear = make([]dataprotection.Month, 0) + for _, value := range v["months_of_year"].(*schema.Set).List() { + monthsOfYear = append(monthsOfYear, dataprotection.Month(value.(string))) + } + } + + var weeksOfTheMonth []dataprotection.WeekNumber + if v["weeks_of_the_month"].(*schema.Set).Len() > 0 { + weeksOfTheMonth = make([]dataprotection.WeekNumber, 0) + for _, value := range v["weeks_of_the_month"].(*schema.Set).List() { + weeksOfTheMonth = append(weeksOfTheMonth, dataprotection.WeekNumber(value.(string))) + } + } + + var scheduleTimes []date.Time + if v["schedule_times"].(*schema.Set).Len() > 0 { + scheduleTimes = make([]date.Time, 0) + for _, value := range v["schedule_times"].(*schema.Set).List() { + t, _ := time.Parse(time.RFC3339, value.(string)) + scheduleTimes = append(scheduleTimes, date.Time{Time: t}) + } + } + results = append(results, dataprotection.ScheduleBasedBackupCriteria{ + AbsoluteCriteria: &absoluteCriteria, + DaysOfMonth: &daysOfMonth, + DaysOfTheWeek: &daysOfTheWeek, + MonthsOfYear: &monthsOfYear, + ScheduleTimes: &scheduleTimes, + WeeksOfTheMonth: &weeksOfTheMonth, + ObjectType: dataprotection.ObjectTypeScheduleBasedBackupCriteria, + }) + } + return &results +} + +func flattenBackupPolicyPostgreSqlBackupRuleArray(input *[]dataprotection.BasicBasePolicyRule) []interface{} { + results := make([]interface{}, 0) + if input == nil { + return results + } + for _, item := range *input { + if backupRule, ok := item.AsAzureBackupRule(); ok { + var name string + if backupRule.Name != nil { + name = *backupRule.Name + } + intervals := make([]interface{}, 0) + if backupRule.Trigger != nil { + if scheduleBasedTrigger, ok := backupRule.Trigger.AsScheduleBasedTriggerContext(); ok { + if scheduleBasedTrigger.Schedule != nil { + intervals = utils.FlattenStringSlice(scheduleBasedTrigger.Schedule.RepeatingTimeIntervals) + } + } + } + results = append(results, map[string]interface{}{ + "name": name, + "repeating_time_intervals": intervals, + }) + } + } + return results +} + +func flattenBackupPolicyPostgreSqlDefaultRetentionRuleDuration(input *[]dataprotection.BasicBasePolicyRule) interface{} { + if input == nil { + return nil + } + + for _, item := range *input { + if retentionRule, ok := item.AsAzureRetentionRule(); ok && retentionRule.IsDefault != nil && *retentionRule.IsDefault { + if retentionRule.Lifecycles != nil && len(*retentionRule.Lifecycles) > 0 { + if deleteOption, ok := (*retentionRule.Lifecycles)[0].DeleteAfter.AsAbsoluteDeleteOption(); ok { + return *deleteOption.Duration + } + } + } + } + return nil +} + +func flattenBackupPolicyPostgreSqlRetentionRuleArray(input *[]dataprotection.BasicBasePolicyRule) []interface{} { + results := make([]interface{}, 0) + if input == nil { + return results + } + + var taggingCriterias []dataprotection.TaggingCriteria + for _, item := range *input { + if backupRule, ok := item.AsAzureBackupRule(); ok { + if trigger, ok := backupRule.Trigger.AsScheduleBasedTriggerContext(); ok { + if trigger.TaggingCriteria != nil { + taggingCriterias = *trigger.TaggingCriteria + } + } + } + } + + for _, item := range *input { + if retentionRule, ok := item.AsAzureRetentionRule(); ok && (retentionRule.IsDefault == nil || !*retentionRule.IsDefault) { + var name string + if retentionRule.Name != nil { + name = *retentionRule.Name + } + var taggingPriority int64 + var taggingCriteria []interface{} + for _, criteria := range taggingCriterias { + if criteria.TagInfo != nil && criteria.TagInfo.TagName != nil && strings.EqualFold(*criteria.TagInfo.TagName, name) { + taggingPriority = *criteria.TaggingPriority + taggingCriteria = flattenBackupPolicyPostgreSqlBackupCriteriaArray(criteria.Criteria) + } + } + var duration string + if retentionRule.Lifecycles != nil && len(*retentionRule.Lifecycles) > 0 { + if deleteOption, ok := (*retentionRule.Lifecycles)[0].DeleteAfter.AsAbsoluteDeleteOption(); ok { + duration = *deleteOption.Duration + } + } + results = append(results, map[string]interface{}{ + "name": name, + "tagging_priority": taggingPriority, + "tagging_criteria": taggingCriteria, + "duration": duration, + }) + } + } + return results +} + +func flattenBackupPolicyPostgreSqlBackupCriteriaArray(input *[]dataprotection.BasicBackupCriteria) []interface{} { + results := make([]interface{}, 0) + if input == nil { + return results + } + + for _, item := range *input { + if criteria, ok := item.AsScheduleBasedBackupCriteria(); ok { + var absoluteCriteria string + if criteria.AbsoluteCriteria != nil && len(*criteria.AbsoluteCriteria) > 0 { + absoluteCriteria = string((*criteria.AbsoluteCriteria)[0]) + } + var daysOfTheWeek []string + if criteria.DaysOfTheWeek != nil { + daysOfTheWeek = make([]string, 0) + for _, item := range *criteria.DaysOfTheWeek { + daysOfTheWeek = append(daysOfTheWeek, (string)(item)) + } + } + var monthsOfYear []string + if criteria.MonthsOfYear != nil { + monthsOfYear = make([]string, 0) + for _, item := range *criteria.MonthsOfYear { + monthsOfYear = append(monthsOfYear, (string)(item)) + } + } + var weeksOfTheMonth []string + if criteria.WeeksOfTheMonth != nil { + weeksOfTheMonth = make([]string, 0) + for _, item := range *criteria.WeeksOfTheMonth { + weeksOfTheMonth = append(weeksOfTheMonth, (string)(item)) + } + } + var scheduleTimes []string + if criteria.ScheduleTimes != nil { + scheduleTimes = make([]string, 0) + for _, item := range *criteria.ScheduleTimes { + scheduleTimes = append(scheduleTimes, item.String()) + } + } + + results = append(results, map[string]interface{}{ + "absolute_criteria": absoluteCriteria, + "days_of_month": flattenBackupPolicyPostgreSqlDayArray(criteria.DaysOfMonth), + "days_of_the_week": daysOfTheWeek, + "months_of_year": monthsOfYear, + "weeks_of_the_month": weeksOfTheMonth, + "schedule_times": scheduleTimes, + }) + } + } + return results +} + +func flattenBackupPolicyPostgreSqlDayArray(input *[]dataprotection.Day) []interface{} { + results := make([]interface{}, 0) + if input == nil { + return results + } + + for _, item := range *input { + var d int32 + if item.Date != nil { + d = *item.Date + } + var isLast bool + if item.IsLast != nil { + isLast = *item.IsLast + } + results = append(results, map[string]interface{}{ + "date": d, + "is_last": isLast, + }) + } + return results +} diff --git a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go new file mode 100644 index 000000000000..5420b9651dda --- /dev/null +++ b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go @@ -0,0 +1,208 @@ +package dataprotection_test + +import ( + "context" + "fmt" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/acceptance/check" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/dataprotection/parse" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" +) + +type DataProtectionBackupPolicyPostgreSqlResource struct{} + +func TestAccDataProtectionBackupPolicyPostgreSql_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_data_protection_backup_policy_postgresql", "test") + r := DataProtectionBackupPolicyPostgreSqlResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccDataProtectionBackupPolicyPostgreSql_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_data_protection_backup_policy_postgresql", "test") + r := DataProtectionBackupPolicyPostgreSqlResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.RequiresImportErrorStep(r.requiresImport), + }) +} + +func TestAccDataProtectionBackupPolicyPostgreSql_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_data_protection_backup_policy_postgresql", "test") + r := DataProtectionBackupPolicyPostgreSqlResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.complete(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccDataProtectionBackupPolicyPostgreSql_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_data_protection_backup_policy_postgresql", "test") + r := DataProtectionBackupPolicyPostgreSqlResource{} + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.complete(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func (r DataProtectionBackupPolicyPostgreSqlResource) Exists(ctx context.Context, client *clients.Client, state *terraform.InstanceState) (*bool, error) { + id, err := parse.BackupPolicyID(state.ID) + if err != nil { + return nil, err + } + resp, err := client.DataProtection.BackupPolicyClient.Get(ctx, id.BackupVaultName, id.ResourceGroup, id.Name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving DataProtection BackupPolicy (%q): %+v", id, err) + } + return utils.Bool(true), nil +} + +func (r DataProtectionBackupPolicyPostgreSqlResource) template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctest-dataprotection-%d" + location = "%s" +} + +resource "azurerm_data_protection_backup_vault" "test" { + name = "acctest-dbv-%d" + resource_group_name = azurerm_resource_group.test.name + location = azurerm_resource_group.test.location + datastore_type = "VaultStore" + redundancy = "LocallyRedundant" +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} + +func (r DataProtectionBackupPolicyPostgreSqlResource) basic(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_data_protection_backup_policy_postgresql" "test" { + name = "acctest-dbp-%d" + resource_group_name = azurerm_resource_group.test.name + vault_name = azurerm_data_protection_backup_vault.test.name + + backup_rules { + name = "backup" + repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] + } + default_retention_duration = "P4M" +} +`, template, data.RandomInteger) +} + +func (r DataProtectionBackupPolicyPostgreSqlResource) requiresImport(data acceptance.TestData) string { + config := r.basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_data_protection_backup_policy_postgresql" "import" { + name = azurerm_data_protection_backup_policy_postgresql.test.name + resource_group_name = azurerm_data_protection_backup_policy_postgresql.test.resource_group_name + vault_name = azurerm_data_protection_backup_policy_postgresql.test.vault_name + backup_rules { + name = "backup" + repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] + } + default_retention_duration = "P4M" +} +`, config) +} + +func (r DataProtectionBackupPolicyPostgreSqlResource) complete(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_data_protection_backup_policy_postgresql" "test" { + name = "acctest-dbp-%d" + resource_group_name = azurerm_resource_group.test.name + vault_name = azurerm_data_protection_backup_vault.test.name + + backup_rules { + name = "backup" + repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] + } + default_retention_duration = "P4M" + retention_rules { + name = "weekly" + duration = "P6M" + tagging_priority = 20 + tagging_criteria { + absolute_criteria = "FirstOfWeek" + } + } + + retention_rules { + name = "thursday" + duration = "P1W" + tagging_priority = 25 + tagging_criteria { + days_of_the_week = ["Thursday"] + schedule_times = ["2021-05-23T02:30:00Z"] + } + } + + retention_rules { + name = "monthly" + duration = "P1D" + tagging_priority = 30 + tagging_criteria { + weeks_of_the_month = ["First", "Last"] + days_of_the_week = ["Tuesday"] + schedule_times = ["2021-05-23T02:30:00Z"] + } + } +} +`, template, data.RandomInteger) +} diff --git a/azurerm/internal/services/dataprotection/parse/backup_policy.go b/azurerm/internal/services/dataprotection/parse/backup_policy.go new file mode 100644 index 000000000000..242d360697e1 --- /dev/null +++ b/azurerm/internal/services/dataprotection/parse/backup_policy.go @@ -0,0 +1,75 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + "strings" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure" +) + +type BackupPolicyId struct { + SubscriptionId string + ResourceGroup string + BackupVaultName string + Name string +} + +func NewBackupPolicyID(subscriptionId, resourceGroup, backupVaultName, name string) BackupPolicyId { + return BackupPolicyId{ + SubscriptionId: subscriptionId, + ResourceGroup: resourceGroup, + BackupVaultName: backupVaultName, + Name: name, + } +} + +func (id BackupPolicyId) String() string { + segments := []string{ + fmt.Sprintf("Name %q", id.Name), + fmt.Sprintf("Backup Vault Name %q", id.BackupVaultName), + fmt.Sprintf("Resource Group %q", id.ResourceGroup), + } + segmentsStr := strings.Join(segments, " / ") + return fmt.Sprintf("%s: (%s)", "Backup Policy", segmentsStr) +} + +func (id BackupPolicyId) ID() string { + fmtString := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.DataProtection/backupVaults/%s/backupPolicies/%s" + return fmt.Sprintf(fmtString, id.SubscriptionId, id.ResourceGroup, id.BackupVaultName, id.Name) +} + +// BackupPolicyID parses a BackupPolicy ID into an BackupPolicyId struct +func BackupPolicyID(input string) (*BackupPolicyId, error) { + id, err := azure.ParseAzureResourceID(input) + if err != nil { + return nil, err + } + + resourceId := BackupPolicyId{ + SubscriptionId: id.SubscriptionID, + ResourceGroup: id.ResourceGroup, + } + + if resourceId.SubscriptionId == "" { + return nil, fmt.Errorf("ID was missing the 'subscriptions' element") + } + + if resourceId.ResourceGroup == "" { + return nil, fmt.Errorf("ID was missing the 'resourceGroups' element") + } + + if resourceId.BackupVaultName, err = id.PopSegment("backupVaults"); err != nil { + return nil, err + } + if resourceId.Name, err = id.PopSegment("backupPolicies"); err != nil { + return nil, err + } + + if err := id.ValidateNoEmptySegments(input); err != nil { + return nil, err + } + + return &resourceId, nil +} diff --git a/azurerm/internal/services/dataprotection/parse/backup_policy_test.go b/azurerm/internal/services/dataprotection/parse/backup_policy_test.go new file mode 100644 index 000000000000..a03bd97356bb --- /dev/null +++ b/azurerm/internal/services/dataprotection/parse/backup_policy_test.go @@ -0,0 +1,128 @@ +package parse + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "testing" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/resourceid" +) + +var _ resourceid.Formatter = BackupPolicyId{} + +func TestBackupPolicyIDFormatter(t *testing.T) { + actual := NewBackupPolicyID("12345678-1234-9876-4563-123456789012", "resourceGroup1", "vault1", "backupPolicy1").ID() + expected := "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1/backupPolicies/backupPolicy1" + if actual != expected { + t.Fatalf("Expected %q but got %q", expected, actual) + } +} + +func TestBackupPolicyID(t *testing.T) { + testData := []struct { + Input string + Error bool + Expected *BackupPolicyId + }{ + + { + // empty + Input: "", + Error: true, + }, + + { + // missing SubscriptionId + Input: "/", + Error: true, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Error: true, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Error: true, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", + Error: true, + }, + + { + // missing BackupVaultName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/", + Error: true, + }, + + { + // missing value for BackupVaultName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/", + Error: true, + }, + + { + // missing Name + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1/", + Error: true, + }, + + { + // missing value for Name + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1/backupPolicies/", + Error: true, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1/backupPolicies/backupPolicy1", + Expected: &BackupPolicyId{ + SubscriptionId: "12345678-1234-9876-4563-123456789012", + ResourceGroup: "resourceGroup1", + BackupVaultName: "vault1", + Name: "backupPolicy1", + }, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESOURCEGROUP1/PROVIDERS/MICROSOFT.DATAPROTECTION/BACKUPVAULTS/VAULT1/BACKUPPOLICIES/BACKUPPOLICY1", + Error: true, + }, + } + + for _, v := range testData { + t.Logf("[DEBUG] Testing %q", v.Input) + + actual, err := BackupPolicyID(v.Input) + if err != nil { + if v.Error { + continue + } + + t.Fatalf("Expect a value but got an error: %s", err) + } + if v.Error { + t.Fatal("Expect an error but didn't get one") + } + + if actual.SubscriptionId != v.Expected.SubscriptionId { + t.Fatalf("Expected %q but got %q for SubscriptionId", v.Expected.SubscriptionId, actual.SubscriptionId) + } + if actual.ResourceGroup != v.Expected.ResourceGroup { + t.Fatalf("Expected %q but got %q for ResourceGroup", v.Expected.ResourceGroup, actual.ResourceGroup) + } + if actual.BackupVaultName != v.Expected.BackupVaultName { + t.Fatalf("Expected %q but got %q for BackupVaultName", v.Expected.BackupVaultName, actual.BackupVaultName) + } + if actual.Name != v.Expected.Name { + t.Fatalf("Expected %q but got %q for Name", v.Expected.Name, actual.Name) + } + } +} diff --git a/azurerm/internal/services/dataprotection/registration.go b/azurerm/internal/services/dataprotection/registration.go index b8aeea610230..8c55f5457a30 100644 --- a/azurerm/internal/services/dataprotection/registration.go +++ b/azurerm/internal/services/dataprotection/registration.go @@ -24,6 +24,7 @@ func (r Registration) SupportedDataSources() map[string]*schema.Resource { // SupportedResources returns the supported Resources supported by this Service func (r Registration) SupportedResources() map[string]*schema.Resource { return map[string]*schema.Resource{ - "azurerm_data_protection_backup_vault": resourceDataProtectionBackupVault(), + "azurerm_data_protection_backup_vault": resourceDataProtectionBackupVault(), + "azurerm_data_protection_backup_policy_postgresql": resourceDataProtectionBackupPolicyPostgreSql(), } } diff --git a/azurerm/internal/services/dataprotection/resourceids.go b/azurerm/internal/services/dataprotection/resourceids.go index 44d74aee76d5..369f71ce6120 100644 --- a/azurerm/internal/services/dataprotection/resourceids.go +++ b/azurerm/internal/services/dataprotection/resourceids.go @@ -1,3 +1,4 @@ package dataprotection //go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=BackupVault -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1 +//go:generate go run ../../tools/generator-resource-id/main.go -path=./ -name=BackupPolicy -id=/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1/backupPolicies/backupPolicy1 diff --git a/azurerm/internal/services/dataprotection/validate/backup_policy_id.go b/azurerm/internal/services/dataprotection/validate/backup_policy_id.go new file mode 100644 index 000000000000..903e7bad3ca4 --- /dev/null +++ b/azurerm/internal/services/dataprotection/validate/backup_policy_id.go @@ -0,0 +1,23 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import ( + "fmt" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/dataprotection/parse" +) + +func BackupPolicyID(input interface{}, key string) (warnings []string, errors []error) { + v, ok := input.(string) + if !ok { + errors = append(errors, fmt.Errorf("expected %q to be a string", key)) + return + } + + if _, err := parse.BackupPolicyID(v); err != nil { + errors = append(errors, err) + } + + return +} diff --git a/azurerm/internal/services/dataprotection/validate/backup_policy_id_test.go b/azurerm/internal/services/dataprotection/validate/backup_policy_id_test.go new file mode 100644 index 000000000000..33353158919c --- /dev/null +++ b/azurerm/internal/services/dataprotection/validate/backup_policy_id_test.go @@ -0,0 +1,88 @@ +package validate + +// NOTE: this file is generated via 'go:generate' - manual changes will be overwritten + +import "testing" + +func TestBackupPolicyID(t *testing.T) { + cases := []struct { + Input string + Valid bool + }{ + + { + // empty + Input: "", + Valid: false, + }, + + { + // missing SubscriptionId + Input: "/", + Valid: false, + }, + + { + // missing value for SubscriptionId + Input: "/subscriptions/", + Valid: false, + }, + + { + // missing ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/", + Valid: false, + }, + + { + // missing value for ResourceGroup + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/", + Valid: false, + }, + + { + // missing BackupVaultName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/", + Valid: false, + }, + + { + // missing value for BackupVaultName + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/", + Valid: false, + }, + + { + // missing Name + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1/", + Valid: false, + }, + + { + // missing value for Name + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1/backupPolicies/", + Valid: false, + }, + + { + // valid + Input: "/subscriptions/12345678-1234-9876-4563-123456789012/resourceGroups/resourceGroup1/providers/Microsoft.DataProtection/backupVaults/vault1/backupPolicies/backupPolicy1", + Valid: true, + }, + + { + // upper-cased + Input: "/SUBSCRIPTIONS/12345678-1234-9876-4563-123456789012/RESOURCEGROUPS/RESOURCEGROUP1/PROVIDERS/MICROSOFT.DATAPROTECTION/BACKUPVAULTS/VAULT1/BACKUPPOLICIES/BACKUPPOLICY1", + Valid: false, + }, + } + for _, tc := range cases { + t.Logf("[DEBUG] Testing Value %s", tc.Input) + _, errors := BackupPolicyID(tc.Input, "test") + valid := len(errors) == 0 + + if tc.Valid != valid { + t.Fatalf("Expected %t but got %t", tc.Valid, valid) + } + } +} diff --git a/website/docs/r/data_protection_backup_policy_postgresql.html.markdown b/website/docs/r/data_protection_backup_policy_postgresql.html.markdown new file mode 100644 index 000000000000..d9f307048618 --- /dev/null +++ b/website/docs/r/data_protection_backup_policy_postgresql.html.markdown @@ -0,0 +1,154 @@ +--- +subcategory: "DataProtection" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_data_protection_backup_policy_postgresql" +description: |- + Manages a Backup Policy Postgre Sql. +--- + +# azurerm_data_protection_backup_policy_postgresql + +Manages a Backup Policy Postgre Sql. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "rg" { + name = "example-resources" + location = "West Europe" +} + +resource "azurerm_data_protection_backup_vault" "example" { + name = "example-backup-vault" + resource_group_name = azurerm_resource_group.rg.name + location = azurerm_resource_group.rg.location + datastore_type = "VaultStore" + redundancy = "LocallyRedundant" +} + +resource "azurerm_data_protection_backup_policy_postgresql" "example" { + name = "example-backup-policy" + resource_group_name = azurerm_resource_group.rg.name + vault_name = azurerm_data_protection_backup_vault.example.name + + backup_rules { + name = "backup" + repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] + } + default_retention_duration = "P4M" + retention_rules { + name = "weekly" + duration = "P6M" + tagging_priority = 20 + tagging_criteria { + absolute_criteria = "FirstOfWeek" + } + } + + retention_rules { + name = "thursday" + duration = "P1W" + tagging_priority = 25 + tagging_criteria { + days_of_the_week = ["Thursday"] + schedule_times = ["2021-05-23T02:30:00Z"] + } + } + + retention_rules { + name = "monthly" + duration = "P1D" + tagging_priority = 30 + tagging_criteria { + weeks_of_the_month = ["First", "Last"] + days_of_the_week = ["Tuesday"] + schedule_times = ["2021-05-23T02:30:00Z"] + } + } +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `name` - (Required) The name which should be used for this Backup Policy Postgre Sql. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `resource_group_name` - (Required) The name of the Resource Group where the Backup Policy Postgre Sql should exist. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `vault_name` - (Required) The name of the Backup Vault where the Backup Policy Postgre Sql should exist. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `backup_rules` - (Required) A `backup_rules` block as defined below. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `default_retention_duration` - (Required) The duration of default retention rule. It should follow `ISO 8601` duration format. Changing this forces a new Backup Policy Postgre Sql to be created. + +--- + +* `retention_rules` - (Optional) One or more `retention_rules` blocks as defined below. Changing this forces a new Backup Policy Postgre Sql to be created. + +--- + +A `backup_rules` block supports the following: + +* `name` - (Required) The name which should be used for this backup rule. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `repeating_time_intervals` - (Required) Specifies a list of repeating time interval. It should follow `ISO 8601` repeating time interval . Changing this forces a new Backup Policy Postgre Sql to be created. + +--- + +A `retention_rules` block supports the following: + +* `name` - (Required) The name which should be used for this retention rule. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `duration` - (Required) Duration of deletion after given timespan. It should follow `ISO 8601` duration format. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `tagging_criteria` - (Required) A `tagging_criteria` block as defined below. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `tagging_priority` - (Required) Retention Tag priority. Changing this forces a new Backup Policy Postgre Sql to be created. + +--- + +A `tagging_criteria` block supports the following: + +* `absolute_criteria` - (Optional) Possible values are `AllBackup`, `FirstOfDay`, `FirstOfWeek`, `FirstOfMonth` and `FirstOfYear`. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `days_of_month` - (Optional) One or more `days_of_month` blocks as defined above. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `days_of_the_week` - (Optional) Possible values are `Monday`, `Tuesday`, `Thursday`, `Friday`, `Saturday` and `Sunday`. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `months_of_year` - (Optional) Possible values are `January`, `February`, `March`, `April`, `May`, `June`, `July`, `August`, `September`, `October`, `November` and `December`. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `schedule_times` - (Optional) Specifies a list of schedule times for backup. It should follow `RFC3339` time format. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `weeks_of_the_month` - (Optional) Possible values are `First`, `Second`, `Third`, `Fourth` and `Last`. Changing this forces a new Backup Policy Postgre Sql to be created. + +--- + +A `days_of_month` block is day of the month from 1 to 28 otherwise last of month, it supports the following: + +* `date` - (Optional) Date of the month. Changing this forces a new Backup Policy Postgre Sql to be created. + +* `is_last` - (Optional) Whether Date is last date of month. Changing this forces a new Backup Policy Postgre Sql to be created. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the Backup Policy Postgre Sql. + +## Timeouts + +The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: + +* `create` - (Defaults to 30 minutes) Used when creating the Backup Policy Postgre Sql. +* `read` - (Defaults to 5 minutes) Used when retrieving the Backup Policy Postgre Sql. +* `update` - (Defaults to 30 minutes) Used when updating the Backup Policy Postgre Sql. +* `delete` - (Defaults to 30 minutes) Used when deleting the Backup Policy Postgre Sql. + +## Import + +Backup Policy Postgre Sqls can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_data_protection_backup_policy_postgresql.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.DataProtection/backupVaults/vault1/backupPolicies/backupPolicy1 +``` From 324303a5e25c59a722f97dcc350e5017e4e36fab Mon Sep 17 00:00:00 2001 From: henglu Date: Tue, 8 Jun 2021 11:37:47 +0800 Subject: [PATCH 2/4] rename some properties and remove unnecessary properties --- ...ction_backup_policy_postgresql_resource.go | 190 ++++++------------ ..._backup_policy_postgresql_resource_test.go | 53 +++-- .../services/dataprotection/registration.go | 2 +- ...ion_backup_policy_postgresql.html.markdown | 85 ++++---- 4 files changed, 124 insertions(+), 206 deletions(-) diff --git a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go index f4b84c0dfcc0..51ba69a22020 100644 --- a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go +++ b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go @@ -20,11 +20,11 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -func resourceDataProtectionBackupPolicyPostgreSql() *schema.Resource { +func resourceDataProtectionBackupPolicyPostgreSQL() *schema.Resource { return &schema.Resource{ - Create: resourceDataProtectionBackupPolicyPostgreSqlCreate, - Read: resourceDataProtectionBackupPolicyPostgreSqlRead, - Delete: resourceDataProtectionBackupPolicyPostgreSqlDelete, + Create: resourceDataProtectionBackupPolicyPostgreSQLCreate, + Read: resourceDataProtectionBackupPolicyPostgreSQLRead, + Delete: resourceDataProtectionBackupPolicyPostgreSQLDelete, Timeouts: &schema.ResourceTimeout{ Create: schema.DefaultTimeout(30 * time.Minute), @@ -57,19 +57,13 @@ func resourceDataProtectionBackupPolicyPostgreSql() *schema.Resource { ForceNew: true, }, - "backup_rules": { + "backup_rule": { Type: schema.TypeList, Required: true, ForceNew: true, MaxItems: 1, Elem: &schema.Resource{ Schema: map[string]*schema.Schema{ - "name": { - Type: schema.TypeString, - Required: true, - ForceNew: true, - }, - "repeating_time_intervals": { Type: schema.TypeList, Required: true, @@ -89,7 +83,7 @@ func resourceDataProtectionBackupPolicyPostgreSql() *schema.Resource { ForceNew: true, }, - "retention_rules": { + "retention_rule": { Type: schema.TypeList, Optional: true, ForceNew: true, @@ -127,29 +121,7 @@ func resourceDataProtectionBackupPolicyPostgreSql() *schema.Resource { }, false), }, - "days_of_month": { - Type: schema.TypeSet, - Optional: true, - ForceNew: true, - MinItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "date": { - Type: schema.TypeInt, - Optional: true, - ForceNew: true, - }, - - "is_last": { - Type: schema.TypeBool, - Optional: true, - ForceNew: true, - }, - }, - }, - }, - - "days_of_the_week": { + "days_of_week": { Type: schema.TypeSet, Optional: true, ForceNew: true, @@ -171,7 +143,7 @@ func resourceDataProtectionBackupPolicyPostgreSql() *schema.Resource { }, }, - "schedule_times": { + "scheduled_backup_times": { Type: schema.TypeSet, Optional: true, ForceNew: true, @@ -182,7 +154,7 @@ func resourceDataProtectionBackupPolicyPostgreSql() *schema.Resource { }, }, - "weeks_of_the_month": { + "weeks_of_month": { Type: schema.TypeSet, Optional: true, ForceNew: true, @@ -213,7 +185,8 @@ func resourceDataProtectionBackupPolicyPostgreSql() *schema.Resource { }, } } -func resourceDataProtectionBackupPolicyPostgreSqlCreate(d *schema.ResourceData, meta interface{}) error { + +func resourceDataProtectionBackupPolicyPostgreSQLCreate(d *schema.ResourceData, meta interface{}) error { subscriptionId := meta.(*clients.Client).Account.SubscriptionId client := meta.(*clients.Client).DataProtection.BackupPolicyClient ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) @@ -235,11 +208,11 @@ func resourceDataProtectionBackupPolicyPostgreSqlCreate(d *schema.ResourceData, return tf.ImportAsExistsError("azurerm_data_protection_backup_policy_postgresql", id.ID()) } - taggingCriteria := expandBackupPolicyPostgreSqlTaggingCriteriaArray(d.Get("retention_rules").([]interface{})) + taggingCriteria := expandBackupPolicyPostgreSQLTaggingCriteriaArray(d.Get("retention_rule").([]interface{})) policyRules := make([]dataprotection.BasicBasePolicyRule, 0) - policyRules = append(policyRules, expandBackupPolicyPostgreSqlAzureBackupRuleArray(d.Get("backup_rules").([]interface{}), taggingCriteria)...) - policyRules = append(policyRules, expandBackupPolicyPostgreSqlDefaultAzureRetentionRule(d.Get("default_retention_duration"))) - policyRules = append(policyRules, expandBackupPolicyPostgreSqlAzureRetentionRuleArray(d.Get("retention_rules").([]interface{}))...) + policyRules = append(policyRules, expandBackupPolicyPostgreSQLAzureBackupRuleArray(d.Get("backup_rule").([]interface{}), taggingCriteria)...) + policyRules = append(policyRules, expandBackupPolicyPostgreSQLDefaultAzureRetentionRule(d.Get("default_retention_duration"))) + policyRules = append(policyRules, expandBackupPolicyPostgreSQLAzureRetentionRuleArray(d.Get("retention_rule").([]interface{}))...) parameters := dataprotection.BaseBackupPolicyResource{ Properties: &dataprotection.BackupPolicy{ PolicyRules: &policyRules, @@ -253,10 +226,10 @@ func resourceDataProtectionBackupPolicyPostgreSqlCreate(d *schema.ResourceData, } d.SetId(id.ID()) - return resourceDataProtectionBackupPolicyPostgreSqlRead(d, meta) + return resourceDataProtectionBackupPolicyPostgreSQLRead(d, meta) } -func resourceDataProtectionBackupPolicyPostgreSqlRead(d *schema.ResourceData, meta interface{}) error { +func resourceDataProtectionBackupPolicyPostgreSQLRead(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).DataProtection.BackupPolicyClient ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() @@ -280,21 +253,21 @@ func resourceDataProtectionBackupPolicyPostgreSqlRead(d *schema.ResourceData, me d.Set("vault_name", id.BackupVaultName) if resp.Properties != nil { if props, ok := resp.Properties.AsBackupPolicy(); ok { - if err := d.Set("backup_rules", flattenBackupPolicyPostgreSqlBackupRuleArray(props.PolicyRules)); err != nil { - return fmt.Errorf("setting `backup_rules`: %+v", err) + if err := d.Set("backup_rule", flattenBackupPolicyPostgreSQLBackupRuleArray(props.PolicyRules)); err != nil { + return fmt.Errorf("setting `backup_rule`: %+v", err) } - if err := d.Set("default_retention_duration", flattenBackupPolicyPostgreSqlDefaultRetentionRuleDuration(props.PolicyRules)); err != nil { + if err := d.Set("default_retention_duration", flattenBackupPolicyPostgreSQLDefaultRetentionRuleDuration(props.PolicyRules)); err != nil { return fmt.Errorf("setting `default_retention_duration`: %+v", err) } - if err := d.Set("retention_rules", flattenBackupPolicyPostgreSqlRetentionRuleArray(props.PolicyRules)); err != nil { - return fmt.Errorf("setting `retention_rules`: %+v", err) + if err := d.Set("retention_rule", flattenBackupPolicyPostgreSQLRetentionRuleArray(props.PolicyRules)); err != nil { + return fmt.Errorf("setting `retention_rule`: %+v", err) } } } return nil } -func resourceDataProtectionBackupPolicyPostgreSqlDelete(d *schema.ResourceData, meta interface{}) error { +func resourceDataProtectionBackupPolicyPostgreSQLDelete(d *schema.ResourceData, meta interface{}) error { client := meta.(*clients.Client).DataProtection.BackupPolicyClient ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() @@ -314,12 +287,12 @@ func resourceDataProtectionBackupPolicyPostgreSqlDelete(d *schema.ResourceData, return nil } -func expandBackupPolicyPostgreSqlAzureBackupRuleArray(input []interface{}, taggingCriteria *[]dataprotection.TaggingCriteria) []dataprotection.BasicBasePolicyRule { +func expandBackupPolicyPostgreSQLAzureBackupRuleArray(input []interface{}, taggingCriteria *[]dataprotection.TaggingCriteria) []dataprotection.BasicBasePolicyRule { results := make([]dataprotection.BasicBasePolicyRule, 0) for _, item := range input { v := item.(map[string]interface{}) results = append(results, dataprotection.AzureBackupRule{ - Name: utils.String(v["name"].(string)), + Name: utils.String("BackupWeekly"), ObjectType: dataprotection.ObjectTypeAzureBackupRule, DataStore: &dataprotection.DataStoreInfoBase{ DataStoreType: dataprotection.VaultStore, @@ -341,7 +314,7 @@ func expandBackupPolicyPostgreSqlAzureBackupRuleArray(input []interface{}, taggi return results } -func expandBackupPolicyPostgreSqlAzureRetentionRuleArray(input []interface{}) []dataprotection.BasicBasePolicyRule { +func expandBackupPolicyPostgreSQLAzureRetentionRuleArray(input []interface{}) []dataprotection.BasicBasePolicyRule { results := make([]dataprotection.BasicBasePolicyRule, 0) for _, item := range input { v := item.(map[string]interface{}) @@ -367,7 +340,7 @@ func expandBackupPolicyPostgreSqlAzureRetentionRuleArray(input []interface{}) [] return results } -func expandBackupPolicyPostgreSqlDefaultAzureRetentionRule(input interface{}) dataprotection.BasicBasePolicyRule { +func expandBackupPolicyPostgreSQLDefaultAzureRetentionRule(input interface{}) dataprotection.BasicBasePolicyRule { return dataprotection.AzureRetentionRule{ Name: utils.String("Default"), ObjectType: dataprotection.ObjectTypeAzureRetentionRule, @@ -388,7 +361,7 @@ func expandBackupPolicyPostgreSqlDefaultAzureRetentionRule(input interface{}) da } } -func expandBackupPolicyPostgreSqlTaggingCriteriaArray(input []interface{}) *[]dataprotection.TaggingCriteria { +func expandBackupPolicyPostgreSQLTaggingCriteriaArray(input []interface{}) *[]dataprotection.TaggingCriteria { results := []dataprotection.TaggingCriteria{ { Criteria: nil, @@ -403,7 +376,7 @@ func expandBackupPolicyPostgreSqlTaggingCriteriaArray(input []interface{}) *[]da for _, item := range input { v := item.(map[string]interface{}) results = append(results, dataprotection.TaggingCriteria{ - Criteria: expandBackupPolicyPostgreSqlCriteriaArray(v["tagging_criteria"].([]interface{})), + Criteria: expandBackupPolicyPostgreSQLCriteriaArray(v["tagging_criteria"].([]interface{})), IsDefault: utils.Bool(false), TaggingPriority: utils.Int64(int64(v["tagging_priority"].(int))), TagInfo: &dataprotection.RetentionTag{ @@ -415,7 +388,7 @@ func expandBackupPolicyPostgreSqlTaggingCriteriaArray(input []interface{}) *[]da return &results } -func expandBackupPolicyPostgreSqlCriteriaArray(input []interface{}) *[]dataprotection.BasicBackupCriteria { +func expandBackupPolicyPostgreSQLCriteriaArray(input []interface{}) *[]dataprotection.BasicBackupCriteria { results := make([]dataprotection.BasicBackupCriteria, 0) for _, item := range input { v := item.(map[string]interface{}) @@ -424,23 +397,11 @@ func expandBackupPolicyPostgreSqlCriteriaArray(input []interface{}) *[]dataprote absoluteCriteria = []dataprotection.AbsoluteMarker{dataprotection.AbsoluteMarker(absoluteCriteriaRaw)} } - var daysOfMonth []dataprotection.Day - if v["days_of_month"].(*schema.Set).Len() > 0 { - daysOfMonth = make([]dataprotection.Day, 0) - for _, value := range v["days_of_month"].(*schema.Set).List() { - v := value.(map[string]interface{}) - daysOfMonth = append(daysOfMonth, dataprotection.Day{ - Date: utils.Int32(int32(v["date"].(int))), - IsLast: utils.Bool(v["is_last"].(bool)), - }) - } - } - - var daysOfTheWeek []dataprotection.DayOfWeek - if v["days_of_the_week"].(*schema.Set).Len() > 0 { - daysOfTheWeek = make([]dataprotection.DayOfWeek, 0) - for _, value := range v["days_of_the_week"].(*schema.Set).List() { - daysOfTheWeek = append(daysOfTheWeek, dataprotection.DayOfWeek(value.(string))) + var daysOfWeek []dataprotection.DayOfWeek + if v["days_of_week"].(*schema.Set).Len() > 0 { + daysOfWeek = make([]dataprotection.DayOfWeek, 0) + for _, value := range v["days_of_week"].(*schema.Set).List() { + daysOfWeek = append(daysOfWeek, dataprotection.DayOfWeek(value.(string))) } } @@ -452,46 +413,42 @@ func expandBackupPolicyPostgreSqlCriteriaArray(input []interface{}) *[]dataprote } } - var weeksOfTheMonth []dataprotection.WeekNumber - if v["weeks_of_the_month"].(*schema.Set).Len() > 0 { - weeksOfTheMonth = make([]dataprotection.WeekNumber, 0) - for _, value := range v["weeks_of_the_month"].(*schema.Set).List() { - weeksOfTheMonth = append(weeksOfTheMonth, dataprotection.WeekNumber(value.(string))) + var weeksOfMonth []dataprotection.WeekNumber + if v["weeks_of_month"].(*schema.Set).Len() > 0 { + weeksOfMonth = make([]dataprotection.WeekNumber, 0) + for _, value := range v["weeks_of_month"].(*schema.Set).List() { + weeksOfMonth = append(weeksOfMonth, dataprotection.WeekNumber(value.(string))) } } var scheduleTimes []date.Time - if v["schedule_times"].(*schema.Set).Len() > 0 { + if v["scheduled_backup_times"].(*schema.Set).Len() > 0 { scheduleTimes = make([]date.Time, 0) - for _, value := range v["schedule_times"].(*schema.Set).List() { + for _, value := range v["scheduled_backup_times"].(*schema.Set).List() { t, _ := time.Parse(time.RFC3339, value.(string)) scheduleTimes = append(scheduleTimes, date.Time{Time: t}) } } results = append(results, dataprotection.ScheduleBasedBackupCriteria{ AbsoluteCriteria: &absoluteCriteria, - DaysOfMonth: &daysOfMonth, - DaysOfTheWeek: &daysOfTheWeek, + DaysOfMonth: nil, + DaysOfTheWeek: &daysOfWeek, MonthsOfYear: &monthsOfYear, ScheduleTimes: &scheduleTimes, - WeeksOfTheMonth: &weeksOfTheMonth, + WeeksOfTheMonth: &weeksOfMonth, ObjectType: dataprotection.ObjectTypeScheduleBasedBackupCriteria, }) } return &results } -func flattenBackupPolicyPostgreSqlBackupRuleArray(input *[]dataprotection.BasicBasePolicyRule) []interface{} { +func flattenBackupPolicyPostgreSQLBackupRuleArray(input *[]dataprotection.BasicBasePolicyRule) []interface{} { results := make([]interface{}, 0) if input == nil { return results } for _, item := range *input { if backupRule, ok := item.AsAzureBackupRule(); ok { - var name string - if backupRule.Name != nil { - name = *backupRule.Name - } intervals := make([]interface{}, 0) if backupRule.Trigger != nil { if scheduleBasedTrigger, ok := backupRule.Trigger.AsScheduleBasedTriggerContext(); ok { @@ -501,7 +458,6 @@ func flattenBackupPolicyPostgreSqlBackupRuleArray(input *[]dataprotection.BasicB } } results = append(results, map[string]interface{}{ - "name": name, "repeating_time_intervals": intervals, }) } @@ -509,7 +465,7 @@ func flattenBackupPolicyPostgreSqlBackupRuleArray(input *[]dataprotection.BasicB return results } -func flattenBackupPolicyPostgreSqlDefaultRetentionRuleDuration(input *[]dataprotection.BasicBasePolicyRule) interface{} { +func flattenBackupPolicyPostgreSQLDefaultRetentionRuleDuration(input *[]dataprotection.BasicBasePolicyRule) interface{} { if input == nil { return nil } @@ -526,7 +482,7 @@ func flattenBackupPolicyPostgreSqlDefaultRetentionRuleDuration(input *[]dataprot return nil } -func flattenBackupPolicyPostgreSqlRetentionRuleArray(input *[]dataprotection.BasicBasePolicyRule) []interface{} { +func flattenBackupPolicyPostgreSQLRetentionRuleArray(input *[]dataprotection.BasicBasePolicyRule) []interface{} { results := make([]interface{}, 0) if input == nil { return results @@ -554,7 +510,7 @@ func flattenBackupPolicyPostgreSqlRetentionRuleArray(input *[]dataprotection.Bas for _, criteria := range taggingCriterias { if criteria.TagInfo != nil && criteria.TagInfo.TagName != nil && strings.EqualFold(*criteria.TagInfo.TagName, name) { taggingPriority = *criteria.TaggingPriority - taggingCriteria = flattenBackupPolicyPostgreSqlBackupCriteriaArray(criteria.Criteria) + taggingCriteria = flattenBackupPolicyPostgreSQLBackupCriteriaArray(criteria.Criteria) } } var duration string @@ -574,7 +530,7 @@ func flattenBackupPolicyPostgreSqlRetentionRuleArray(input *[]dataprotection.Bas return results } -func flattenBackupPolicyPostgreSqlBackupCriteriaArray(input *[]dataprotection.BasicBackupCriteria) []interface{} { +func flattenBackupPolicyPostgreSQLBackupCriteriaArray(input *[]dataprotection.BasicBackupCriteria) []interface{} { results := make([]interface{}, 0) if input == nil { return results @@ -586,11 +542,11 @@ func flattenBackupPolicyPostgreSqlBackupCriteriaArray(input *[]dataprotection.Ba if criteria.AbsoluteCriteria != nil && len(*criteria.AbsoluteCriteria) > 0 { absoluteCriteria = string((*criteria.AbsoluteCriteria)[0]) } - var daysOfTheWeek []string + var daysOfWeek []string if criteria.DaysOfTheWeek != nil { - daysOfTheWeek = make([]string, 0) + daysOfWeek = make([]string, 0) for _, item := range *criteria.DaysOfTheWeek { - daysOfTheWeek = append(daysOfTheWeek, (string)(item)) + daysOfWeek = append(daysOfWeek, (string)(item)) } } var monthsOfYear []string @@ -600,11 +556,11 @@ func flattenBackupPolicyPostgreSqlBackupCriteriaArray(input *[]dataprotection.Ba monthsOfYear = append(monthsOfYear, (string)(item)) } } - var weeksOfTheMonth []string + var weeksOfMonth []string if criteria.WeeksOfTheMonth != nil { - weeksOfTheMonth = make([]string, 0) + weeksOfMonth = make([]string, 0) for _, item := range *criteria.WeeksOfTheMonth { - weeksOfTheMonth = append(weeksOfTheMonth, (string)(item)) + weeksOfMonth = append(weeksOfMonth, (string)(item)) } } var scheduleTimes []string @@ -616,37 +572,13 @@ func flattenBackupPolicyPostgreSqlBackupCriteriaArray(input *[]dataprotection.Ba } results = append(results, map[string]interface{}{ - "absolute_criteria": absoluteCriteria, - "days_of_month": flattenBackupPolicyPostgreSqlDayArray(criteria.DaysOfMonth), - "days_of_the_week": daysOfTheWeek, - "months_of_year": monthsOfYear, - "weeks_of_the_month": weeksOfTheMonth, - "schedule_times": scheduleTimes, + "absolute_criteria": absoluteCriteria, + "days_of_week": daysOfWeek, + "months_of_year": monthsOfYear, + "weeks_of_month": weeksOfMonth, + "scheduled_backup_times": scheduleTimes, }) } } return results } - -func flattenBackupPolicyPostgreSqlDayArray(input *[]dataprotection.Day) []interface{} { - results := make([]interface{}, 0) - if input == nil { - return results - } - - for _, item := range *input { - var d int32 - if item.Date != nil { - d = *item.Date - } - var isLast bool - if item.IsLast != nil { - isLast = *item.IsLast - } - results = append(results, map[string]interface{}{ - "date": d, - "is_last": isLast, - }) - } - return results -} diff --git a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go index 5420b9651dda..282b6c5f85f1 100644 --- a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go +++ b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go @@ -14,11 +14,11 @@ import ( "github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils" ) -type DataProtectionBackupPolicyPostgreSqlResource struct{} +type DataProtectionBackupPolicyPostgreSQLResource struct{} -func TestAccDataProtectionBackupPolicyPostgreSql_basic(t *testing.T) { +func TestAccDataProtectionBackupPolicyPostgreSQL_basic(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_data_protection_backup_policy_postgresql", "test") - r := DataProtectionBackupPolicyPostgreSqlResource{} + r := DataProtectionBackupPolicyPostgreSQLResource{} data.ResourceTest(t, r, []resource.TestStep{ { Config: r.basic(data), @@ -30,9 +30,9 @@ func TestAccDataProtectionBackupPolicyPostgreSql_basic(t *testing.T) { }) } -func TestAccDataProtectionBackupPolicyPostgreSql_requiresImport(t *testing.T) { +func TestAccDataProtectionBackupPolicyPostgreSQL_requiresImport(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_data_protection_backup_policy_postgresql", "test") - r := DataProtectionBackupPolicyPostgreSqlResource{} + r := DataProtectionBackupPolicyPostgreSQLResource{} data.ResourceTest(t, r, []resource.TestStep{ { Config: r.basic(data), @@ -44,9 +44,9 @@ func TestAccDataProtectionBackupPolicyPostgreSql_requiresImport(t *testing.T) { }) } -func TestAccDataProtectionBackupPolicyPostgreSql_complete(t *testing.T) { +func TestAccDataProtectionBackupPolicyPostgreSQL_complete(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_data_protection_backup_policy_postgresql", "test") - r := DataProtectionBackupPolicyPostgreSqlResource{} + r := DataProtectionBackupPolicyPostgreSQLResource{} data.ResourceTest(t, r, []resource.TestStep{ { Config: r.complete(data), @@ -58,9 +58,9 @@ func TestAccDataProtectionBackupPolicyPostgreSql_complete(t *testing.T) { }) } -func TestAccDataProtectionBackupPolicyPostgreSql_update(t *testing.T) { +func TestAccDataProtectionBackupPolicyPostgreSQL_update(t *testing.T) { data := acceptance.BuildTestData(t, "azurerm_data_protection_backup_policy_postgresql", "test") - r := DataProtectionBackupPolicyPostgreSqlResource{} + r := DataProtectionBackupPolicyPostgreSQLResource{} data.ResourceTest(t, r, []resource.TestStep{ { Config: r.basic(data), @@ -86,7 +86,7 @@ func TestAccDataProtectionBackupPolicyPostgreSql_update(t *testing.T) { }) } -func (r DataProtectionBackupPolicyPostgreSqlResource) Exists(ctx context.Context, client *clients.Client, state *terraform.InstanceState) (*bool, error) { +func (r DataProtectionBackupPolicyPostgreSQLResource) Exists(ctx context.Context, client *clients.Client, state *terraform.InstanceState) (*bool, error) { id, err := parse.BackupPolicyID(state.ID) if err != nil { return nil, err @@ -101,7 +101,7 @@ func (r DataProtectionBackupPolicyPostgreSqlResource) Exists(ctx context.Context return utils.Bool(true), nil } -func (r DataProtectionBackupPolicyPostgreSqlResource) template(data acceptance.TestData) string { +func (r DataProtectionBackupPolicyPostgreSQLResource) template(data acceptance.TestData) string { return fmt.Sprintf(` provider "azurerm" { features {} @@ -122,7 +122,7 @@ resource "azurerm_data_protection_backup_vault" "test" { `, data.RandomInteger, data.Locations.Primary, data.RandomInteger) } -func (r DataProtectionBackupPolicyPostgreSqlResource) basic(data acceptance.TestData) string { +func (r DataProtectionBackupPolicyPostgreSQLResource) basic(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` %s @@ -132,8 +132,7 @@ resource "azurerm_data_protection_backup_policy_postgresql" "test" { resource_group_name = azurerm_resource_group.test.name vault_name = azurerm_data_protection_backup_vault.test.name - backup_rules { - name = "backup" + backup_rule { repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] } default_retention_duration = "P4M" @@ -141,7 +140,7 @@ resource "azurerm_data_protection_backup_policy_postgresql" "test" { `, template, data.RandomInteger) } -func (r DataProtectionBackupPolicyPostgreSqlResource) requiresImport(data acceptance.TestData) string { +func (r DataProtectionBackupPolicyPostgreSQLResource) requiresImport(data acceptance.TestData) string { config := r.basic(data) return fmt.Sprintf(` %s @@ -150,8 +149,7 @@ resource "azurerm_data_protection_backup_policy_postgresql" "import" { name = azurerm_data_protection_backup_policy_postgresql.test.name resource_group_name = azurerm_data_protection_backup_policy_postgresql.test.resource_group_name vault_name = azurerm_data_protection_backup_policy_postgresql.test.vault_name - backup_rules { - name = "backup" + backup_rule { repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] } default_retention_duration = "P4M" @@ -159,7 +157,7 @@ resource "azurerm_data_protection_backup_policy_postgresql" "import" { `, config) } -func (r DataProtectionBackupPolicyPostgreSqlResource) complete(data acceptance.TestData) string { +func (r DataProtectionBackupPolicyPostgreSQLResource) complete(data acceptance.TestData) string { template := r.template(data) return fmt.Sprintf(` %s @@ -169,12 +167,11 @@ resource "azurerm_data_protection_backup_policy_postgresql" "test" { resource_group_name = azurerm_resource_group.test.name vault_name = azurerm_data_protection_backup_vault.test.name - backup_rules { - name = "backup" + backup_rule { repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] } default_retention_duration = "P4M" - retention_rules { + retention_rule { name = "weekly" duration = "P6M" tagging_priority = 20 @@ -183,24 +180,24 @@ resource "azurerm_data_protection_backup_policy_postgresql" "test" { } } - retention_rules { + retention_rule { name = "thursday" duration = "P1W" tagging_priority = 25 tagging_criteria { - days_of_the_week = ["Thursday"] - schedule_times = ["2021-05-23T02:30:00Z"] + days_of_week = ["Thursday"] + scheduled_backup_times = ["2021-05-23T02:30:00Z"] } } - retention_rules { + retention_rule { name = "monthly" duration = "P1D" tagging_priority = 30 tagging_criteria { - weeks_of_the_month = ["First", "Last"] - days_of_the_week = ["Tuesday"] - schedule_times = ["2021-05-23T02:30:00Z"] + weeks_of_month = ["First", "Last"] + days_of_week = ["Tuesday"] + scheduled_backup_times = ["2021-05-23T02:30:00Z"] } } } diff --git a/azurerm/internal/services/dataprotection/registration.go b/azurerm/internal/services/dataprotection/registration.go index 8c55f5457a30..1e5a2d9364c4 100644 --- a/azurerm/internal/services/dataprotection/registration.go +++ b/azurerm/internal/services/dataprotection/registration.go @@ -25,6 +25,6 @@ func (r Registration) SupportedDataSources() map[string]*schema.Resource { func (r Registration) SupportedResources() map[string]*schema.Resource { return map[string]*schema.Resource{ "azurerm_data_protection_backup_vault": resourceDataProtectionBackupVault(), - "azurerm_data_protection_backup_policy_postgresql": resourceDataProtectionBackupPolicyPostgreSql(), + "azurerm_data_protection_backup_policy_postgresql": resourceDataProtectionBackupPolicyPostgreSQL(), } } diff --git a/website/docs/r/data_protection_backup_policy_postgresql.html.markdown b/website/docs/r/data_protection_backup_policy_postgresql.html.markdown index d9f307048618..bad1cb1e9856 100644 --- a/website/docs/r/data_protection_backup_policy_postgresql.html.markdown +++ b/website/docs/r/data_protection_backup_policy_postgresql.html.markdown @@ -3,12 +3,12 @@ subcategory: "DataProtection" layout: "azurerm" page_title: "Azure Resource Manager: azurerm_data_protection_backup_policy_postgresql" description: |- - Manages a Backup Policy Postgre Sql. + Manages a Backup Policy to back up PostgreSQL. --- # azurerm_data_protection_backup_policy_postgresql -Manages a Backup Policy Postgre Sql. +Manages a Backup Policy to back up PostgreSQL. ## Example Usage @@ -31,12 +31,13 @@ resource "azurerm_data_protection_backup_policy_postgresql" "example" { resource_group_name = azurerm_resource_group.rg.name vault_name = azurerm_data_protection_backup_vault.example.name - backup_rules { - name = "backup" + backup_rule { repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] } + default_retention_duration = "P4M" - retention_rules { + + retention_rule { name = "weekly" duration = "P6M" tagging_priority = 20 @@ -45,24 +46,24 @@ resource "azurerm_data_protection_backup_policy_postgresql" "example" { } } - retention_rules { + retention_rule { name = "thursday" duration = "P1W" tagging_priority = 25 tagging_criteria { - days_of_the_week = ["Thursday"] - schedule_times = ["2021-05-23T02:30:00Z"] + days_of_week = ["Thursday"] + scheduled_backup_times = ["2021-05-23T02:30:00Z"] } } - retention_rules { + retention_rule { name = "monthly" duration = "P1D" - tagging_priority = 30 + tagging_priority = 15 tagging_criteria { - weeks_of_the_month = ["First", "Last"] - days_of_the_week = ["Tuesday"] - schedule_times = ["2021-05-23T02:30:00Z"] + weeks_of_month = ["First", "Last"] + days_of_week = ["Tuesday"] + scheduled_backup_times = ["2021-05-23T02:30:00Z"] } } } @@ -72,37 +73,35 @@ resource "azurerm_data_protection_backup_policy_postgresql" "example" { The following arguments are supported: -* `name` - (Required) The name which should be used for this Backup Policy Postgre Sql. Changing this forces a new Backup Policy Postgre Sql to be created. +* `name` - (Required) The name which should be used for this Backup Policy PostgreSQL. Changing this forces a new Backup Policy PostgreSQL to be created. -* `resource_group_name` - (Required) The name of the Resource Group where the Backup Policy Postgre Sql should exist. Changing this forces a new Backup Policy Postgre Sql to be created. +* `resource_group_name` - (Required) The name of the Resource Group where the Backup Policy PostgreSQL should exist. Changing this forces a new Backup Policy PostgreSQL to be created. -* `vault_name` - (Required) The name of the Backup Vault where the Backup Policy Postgre Sql should exist. Changing this forces a new Backup Policy Postgre Sql to be created. +* `vault_name` - (Required) The name of the Backup Vault where the Backup Policy PostgreSQL should exist. Changing this forces a new Backup Policy PostgreSQL to be created. -* `backup_rules` - (Required) A `backup_rules` block as defined below. Changing this forces a new Backup Policy Postgre Sql to be created. +* `backup_rule` - (Required) A `backup_rule` block as defined below. Changing this forces a new Backup Policy PostgreSQL to be created. -* `default_retention_duration` - (Required) The duration of default retention rule. It should follow `ISO 8601` duration format. Changing this forces a new Backup Policy Postgre Sql to be created. +* `default_retention_duration` - (Required) The duration of default retention rule. It should follow `ISO 8601` duration format. Changing this forces a new Backup Policy PostgreSQL to be created. --- -* `retention_rules` - (Optional) One or more `retention_rules` blocks as defined below. Changing this forces a new Backup Policy Postgre Sql to be created. +* `retention_rule` - (Optional) One or more `retention_rule` blocks as defined below. Changing this forces a new Backup Policy PostgreSQL to be created. --- -A `backup_rules` block supports the following: - -* `name` - (Required) The name which should be used for this backup rule. Changing this forces a new Backup Policy Postgre Sql to be created. +A `backup_rule` block supports the following: -* `repeating_time_intervals` - (Required) Specifies a list of repeating time interval. It should follow `ISO 8601` repeating time interval . Changing this forces a new Backup Policy Postgre Sql to be created. +* `repeating_time_intervals` - (Required) Specifies a list of repeating time interval. It supports weekly back. It should follow `ISO 8601` repeating time interval. Changing this forces a new Backup Policy PostgreSQL to be created. --- -A `retention_rules` block supports the following: +A `retention_rule` block supports the following: -* `name` - (Required) The name which should be used for this retention rule. Changing this forces a new Backup Policy Postgre Sql to be created. +* `name` - (Required) The name which should be used for this retention rule. Changing this forces a new Backup Policy PostgreSQL to be created. -* `duration` - (Required) Duration of deletion after given timespan. It should follow `ISO 8601` duration format. Changing this forces a new Backup Policy Postgre Sql to be created. +* `duration` - (Required) Duration after which the backup is deleted. It should follow `ISO 8601` duration format. Changing this forces a new Backup Policy PostgreSQL to be created. -* `tagging_criteria` - (Required) A `tagging_criteria` block as defined below. Changing this forces a new Backup Policy Postgre Sql to be created. +* `tagging_criteria` - (Required) A `tagging_criteria` block as defined below. Changing this forces a new Backup Policy PostgreSQL to be created. * `tagging_priority` - (Required) Retention Tag priority. Changing this forces a new Backup Policy Postgre Sql to be created. @@ -110,44 +109,34 @@ A `retention_rules` block supports the following: A `tagging_criteria` block supports the following: -* `absolute_criteria` - (Optional) Possible values are `AllBackup`, `FirstOfDay`, `FirstOfWeek`, `FirstOfMonth` and `FirstOfYear`. Changing this forces a new Backup Policy Postgre Sql to be created. - -* `days_of_month` - (Optional) One or more `days_of_month` blocks as defined above. Changing this forces a new Backup Policy Postgre Sql to be created. - -* `days_of_the_week` - (Optional) Possible values are `Monday`, `Tuesday`, `Thursday`, `Friday`, `Saturday` and `Sunday`. Changing this forces a new Backup Policy Postgre Sql to be created. +* `absolute_criteria` - (Optional) Possible values are `AllBackup`, `FirstOfDay`, `FirstOfWeek`, `FirstOfMonth` and `FirstOfYear`. These values mean the first successful backup of the day/week/month/year. Changing this forces a new Backup Policy PostgreSQL to be created. -* `months_of_year` - (Optional) Possible values are `January`, `February`, `March`, `April`, `May`, `June`, `July`, `August`, `September`, `October`, `November` and `December`. Changing this forces a new Backup Policy Postgre Sql to be created. - -* `schedule_times` - (Optional) Specifies a list of schedule times for backup. It should follow `RFC3339` time format. Changing this forces a new Backup Policy Postgre Sql to be created. - -* `weeks_of_the_month` - (Optional) Possible values are `First`, `Second`, `Third`, `Fourth` and `Last`. Changing this forces a new Backup Policy Postgre Sql to be created. - ---- +* `days_of_week` - (Optional) Possible values are `Monday`, `Tuesday`, `Thursday`, `Friday`, `Saturday` and `Sunday`. Changing this forces a new Backup Policy PostgreSQL to be created. -A `days_of_month` block is day of the month from 1 to 28 otherwise last of month, it supports the following: +* `months_of_year` - (Optional) Possible values are `January`, `February`, `March`, `April`, `May`, `June`, `July`, `August`, `September`, `October`, `November` and `December`. Changing this forces a new Backup Policy PostgreSQL to be created. -* `date` - (Optional) Date of the month. Changing this forces a new Backup Policy Postgre Sql to be created. +* `scheduled_backup_times` - (Optional) Specifies a list of backup times for backup in the `RFC3339` format. Changing this forces a new Backup Policy Postgre Sql to be created. -* `is_last` - (Optional) Whether Date is last date of month. Changing this forces a new Backup Policy Postgre Sql to be created. +* `weeks_of_month` - (Optional) Possible values are `First`, `Second`, `Third`, `Fourth` and `Last`. Changing this forces a new Backup Policy PostgreSQL to be created. ## Attributes Reference In addition to the Arguments listed above - the following Attributes are exported: -* `id` - The ID of the Backup Policy Postgre Sql. +* `id` - The ID of the Backup Policy PostgreSQL. ## Timeouts The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/docs/configuration/resources.html#timeouts) for certain actions: -* `create` - (Defaults to 30 minutes) Used when creating the Backup Policy Postgre Sql. -* `read` - (Defaults to 5 minutes) Used when retrieving the Backup Policy Postgre Sql. -* `update` - (Defaults to 30 minutes) Used when updating the Backup Policy Postgre Sql. -* `delete` - (Defaults to 30 minutes) Used when deleting the Backup Policy Postgre Sql. +* `create` - (Defaults to 30 minutes) Used when creating the Backup Policy PostgreSQL. +* `read` - (Defaults to 5 minutes) Used when retrieving the Backup Policy PostgreSQL. +* `update` - (Defaults to 30 minutes) Used when updating the Backup Policy PostgreSQL. +* `delete` - (Defaults to 30 minutes) Used when deleting the Backup Policy PostgreSQL. ## Import -Backup Policy Postgre Sqls can be imported using the `resource id`, e.g. +Backup Policy PostgreSQLs can be imported using the `resource id`, e.g. ```shell terraform import azurerm_data_protection_backup_policy_postgresql.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.DataProtection/backupVaults/vault1/backupPolicies/backupPolicy1 From c85084fcd2cde68f012ec8aa45905848e2aec03b Mon Sep 17 00:00:00 2001 From: henglu Date: Fri, 11 Jun 2021 09:49:52 +0800 Subject: [PATCH 3/4] rename backup_rule to backup_repeating_time_intervals --- ...ction_backup_policy_postgresql_resource.go | 73 +++++++------------ ..._backup_policy_postgresql_resource_test.go | 19 ++--- ...ion_backup_policy_postgresql.html.markdown | 14 +--- 3 files changed, 38 insertions(+), 68 deletions(-) diff --git a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go index 51ba69a22020..0c93471fd3b5 100644 --- a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go +++ b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go @@ -57,23 +57,13 @@ func resourceDataProtectionBackupPolicyPostgreSQL() *schema.Resource { ForceNew: true, }, - "backup_rule": { + "backup_repeating_time_intervals": { Type: schema.TypeList, Required: true, ForceNew: true, - MaxItems: 1, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "repeating_time_intervals": { - Type: schema.TypeList, - Required: true, - ForceNew: true, - MinItems: 1, - Elem: &schema.Schema{ - Type: schema.TypeString, - }, - }, - }, + MinItems: 1, + Elem: &schema.Schema{ + Type: schema.TypeString, }, }, @@ -210,7 +200,7 @@ func resourceDataProtectionBackupPolicyPostgreSQLCreate(d *schema.ResourceData, taggingCriteria := expandBackupPolicyPostgreSQLTaggingCriteriaArray(d.Get("retention_rule").([]interface{})) policyRules := make([]dataprotection.BasicBasePolicyRule, 0) - policyRules = append(policyRules, expandBackupPolicyPostgreSQLAzureBackupRuleArray(d.Get("backup_rule").([]interface{}), taggingCriteria)...) + policyRules = append(policyRules, expandBackupPolicyPostgreSQLAzureBackupRuleArray(d.Get("backup_repeating_time_intervals").([]interface{}), taggingCriteria)...) policyRules = append(policyRules, expandBackupPolicyPostgreSQLDefaultAzureRetentionRule(d.Get("default_retention_duration"))) policyRules = append(policyRules, expandBackupPolicyPostgreSQLAzureRetentionRuleArray(d.Get("retention_rule").([]interface{}))...) parameters := dataprotection.BaseBackupPolicyResource{ @@ -253,7 +243,7 @@ func resourceDataProtectionBackupPolicyPostgreSQLRead(d *schema.ResourceData, me d.Set("vault_name", id.BackupVaultName) if resp.Properties != nil { if props, ok := resp.Properties.AsBackupPolicy(); ok { - if err := d.Set("backup_rule", flattenBackupPolicyPostgreSQLBackupRuleArray(props.PolicyRules)); err != nil { + if err := d.Set("backup_repeating_time_intervals", flattenBackupPolicyPostgreSQLBackupRuleArray(props.PolicyRules)); err != nil { return fmt.Errorf("setting `backup_rule`: %+v", err) } if err := d.Set("default_retention_duration", flattenBackupPolicyPostgreSQLDefaultRetentionRuleDuration(props.PolicyRules)); err != nil { @@ -289,28 +279,26 @@ func resourceDataProtectionBackupPolicyPostgreSQLDelete(d *schema.ResourceData, func expandBackupPolicyPostgreSQLAzureBackupRuleArray(input []interface{}, taggingCriteria *[]dataprotection.TaggingCriteria) []dataprotection.BasicBasePolicyRule { results := make([]dataprotection.BasicBasePolicyRule, 0) - for _, item := range input { - v := item.(map[string]interface{}) - results = append(results, dataprotection.AzureBackupRule{ - Name: utils.String("BackupWeekly"), - ObjectType: dataprotection.ObjectTypeAzureBackupRule, - DataStore: &dataprotection.DataStoreInfoBase{ - DataStoreType: dataprotection.VaultStore, - ObjectType: utils.String("DataStoreInfoBase"), - }, - BackupParameters: &dataprotection.AzureBackupParams{ - BackupType: utils.String("Full"), - ObjectType: dataprotection.ObjectTypeAzureBackupParams, - }, - Trigger: dataprotection.ScheduleBasedTriggerContext{ - Schedule: &dataprotection.BackupSchedule{ - RepeatingTimeIntervals: utils.ExpandStringSlice(v["repeating_time_intervals"].([]interface{})), - }, - TaggingCriteria: taggingCriteria, - ObjectType: dataprotection.ObjectTypeScheduleBasedTriggerContext, + results = append(results, dataprotection.AzureBackupRule{ + Name: utils.String("BackupIntervals"), + ObjectType: dataprotection.ObjectTypeAzureBackupRule, + DataStore: &dataprotection.DataStoreInfoBase{ + DataStoreType: dataprotection.VaultStore, + ObjectType: utils.String("DataStoreInfoBase"), + }, + BackupParameters: &dataprotection.AzureBackupParams{ + BackupType: utils.String("Full"), + ObjectType: dataprotection.ObjectTypeAzureBackupParams, + }, + Trigger: dataprotection.ScheduleBasedTriggerContext{ + Schedule: &dataprotection.BackupSchedule{ + RepeatingTimeIntervals: utils.ExpandStringSlice(input), }, - }) - } + TaggingCriteria: taggingCriteria, + ObjectType: dataprotection.ObjectTypeScheduleBasedTriggerContext, + }, + }) + return results } @@ -443,26 +431,21 @@ func expandBackupPolicyPostgreSQLCriteriaArray(input []interface{}) *[]dataprote } func flattenBackupPolicyPostgreSQLBackupRuleArray(input *[]dataprotection.BasicBasePolicyRule) []interface{} { - results := make([]interface{}, 0) if input == nil { - return results + return make([]interface{}, 0) } for _, item := range *input { if backupRule, ok := item.AsAzureBackupRule(); ok { - intervals := make([]interface{}, 0) if backupRule.Trigger != nil { if scheduleBasedTrigger, ok := backupRule.Trigger.AsScheduleBasedTriggerContext(); ok { if scheduleBasedTrigger.Schedule != nil { - intervals = utils.FlattenStringSlice(scheduleBasedTrigger.Schedule.RepeatingTimeIntervals) + return utils.FlattenStringSlice(scheduleBasedTrigger.Schedule.RepeatingTimeIntervals) } } } - results = append(results, map[string]interface{}{ - "repeating_time_intervals": intervals, - }) } } - return results + return make([]interface{}, 0) } func flattenBackupPolicyPostgreSQLDefaultRetentionRuleDuration(input *[]dataprotection.BasicBasePolicyRule) interface{} { diff --git a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go index 282b6c5f85f1..6f2a776bea51 100644 --- a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go +++ b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go @@ -132,10 +132,8 @@ resource "azurerm_data_protection_backup_policy_postgresql" "test" { resource_group_name = azurerm_resource_group.test.name vault_name = azurerm_data_protection_backup_vault.test.name - backup_rule { - repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] - } - default_retention_duration = "P4M" + backup_repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] + default_retention_duration = "P4M" } `, template, data.RandomInteger) } @@ -149,10 +147,9 @@ resource "azurerm_data_protection_backup_policy_postgresql" "import" { name = azurerm_data_protection_backup_policy_postgresql.test.name resource_group_name = azurerm_data_protection_backup_policy_postgresql.test.resource_group_name vault_name = azurerm_data_protection_backup_policy_postgresql.test.vault_name - backup_rule { - repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] - } - default_retention_duration = "P4M" + + backup_repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] + default_retention_duration = "P4M" } `, config) } @@ -167,10 +164,8 @@ resource "azurerm_data_protection_backup_policy_postgresql" "test" { resource_group_name = azurerm_resource_group.test.name vault_name = azurerm_data_protection_backup_vault.test.name - backup_rule { - repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] - } - default_retention_duration = "P4M" + backup_repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] + default_retention_duration = "P4M" retention_rule { name = "weekly" duration = "P6M" diff --git a/website/docs/r/data_protection_backup_policy_postgresql.html.markdown b/website/docs/r/data_protection_backup_policy_postgresql.html.markdown index bad1cb1e9856..0a39885bc5c7 100644 --- a/website/docs/r/data_protection_backup_policy_postgresql.html.markdown +++ b/website/docs/r/data_protection_backup_policy_postgresql.html.markdown @@ -31,9 +31,7 @@ resource "azurerm_data_protection_backup_policy_postgresql" "example" { resource_group_name = azurerm_resource_group.rg.name vault_name = azurerm_data_protection_backup_vault.example.name - backup_rule { - repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] - } + backup_repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] default_retention_duration = "P4M" @@ -79,8 +77,8 @@ The following arguments are supported: * `vault_name` - (Required) The name of the Backup Vault where the Backup Policy PostgreSQL should exist. Changing this forces a new Backup Policy PostgreSQL to be created. -* `backup_rule` - (Required) A `backup_rule` block as defined below. Changing this forces a new Backup Policy PostgreSQL to be created. - +* `backup_repeating_time_intervals` - (Required) Specifies a list of repeating time interval. It supports weekly back. It should follow `ISO 8601` repeating time interval. Changing this forces a new Backup Policy PostgreSQL to be created. + * `default_retention_duration` - (Required) The duration of default retention rule. It should follow `ISO 8601` duration format. Changing this forces a new Backup Policy PostgreSQL to be created. --- @@ -89,12 +87,6 @@ The following arguments are supported: --- -A `backup_rule` block supports the following: - -* `repeating_time_intervals` - (Required) Specifies a list of repeating time interval. It supports weekly back. It should follow `ISO 8601` repeating time interval. Changing this forces a new Backup Policy PostgreSQL to be created. - ---- - A `retention_rule` block supports the following: * `name` - (Required) The name which should be used for this retention rule. Changing this forces a new Backup Policy PostgreSQL to be created. From a5e00385218ca8b3772e4a7ecf3bfa67755d440c Mon Sep 17 00:00:00 2001 From: ms-henglu Date: Tue, 15 Jun 2021 09:48:15 +0800 Subject: [PATCH 4/4] rename tagging_prioriy and tagging_crieria to priority and crieria --- ...ction_backup_policy_postgresql_resource.go | 16 +++++----- ..._backup_policy_postgresql_resource_test.go | 24 +++++++-------- ...ion_backup_policy_postgresql.html.markdown | 30 +++++++++---------- 3 files changed, 35 insertions(+), 35 deletions(-) diff --git a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go index 0c93471fd3b5..e4f2620795da 100644 --- a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go +++ b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource.go @@ -91,7 +91,7 @@ func resourceDataProtectionBackupPolicyPostgreSQL() *schema.Resource { ForceNew: true, }, - "tagging_criteria": { + "criteria": { Type: schema.TypeList, Required: true, ForceNew: true, @@ -164,7 +164,7 @@ func resourceDataProtectionBackupPolicyPostgreSQL() *schema.Resource { }, }, - "tagging_priority": { + "priority": { Type: schema.TypeInt, Required: true, ForceNew: true, @@ -364,9 +364,9 @@ func expandBackupPolicyPostgreSQLTaggingCriteriaArray(input []interface{}) *[]da for _, item := range input { v := item.(map[string]interface{}) results = append(results, dataprotection.TaggingCriteria{ - Criteria: expandBackupPolicyPostgreSQLCriteriaArray(v["tagging_criteria"].([]interface{})), + Criteria: expandBackupPolicyPostgreSQLCriteriaArray(v["criteria"].([]interface{})), IsDefault: utils.Bool(false), - TaggingPriority: utils.Int64(int64(v["tagging_priority"].(int))), + TaggingPriority: utils.Int64(int64(v["priority"].(int))), TagInfo: &dataprotection.RetentionTag{ ID: utils.String(v["name"].(string) + "_"), TagName: utils.String(v["name"].(string)), @@ -503,10 +503,10 @@ func flattenBackupPolicyPostgreSQLRetentionRuleArray(input *[]dataprotection.Bas } } results = append(results, map[string]interface{}{ - "name": name, - "tagging_priority": taggingPriority, - "tagging_criteria": taggingCriteria, - "duration": duration, + "name": name, + "priority": taggingPriority, + "criteria": taggingCriteria, + "duration": duration, }) } } diff --git a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go index 6f2a776bea51..7c9201cb8ac6 100644 --- a/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go +++ b/azurerm/internal/services/dataprotection/data_protection_backup_policy_postgresql_resource_test.go @@ -167,29 +167,29 @@ resource "azurerm_data_protection_backup_policy_postgresql" "test" { backup_repeating_time_intervals = ["R/2021-05-23T02:30:00+00:00/P1W"] default_retention_duration = "P4M" retention_rule { - name = "weekly" - duration = "P6M" - tagging_priority = 20 - tagging_criteria { + name = "weekly" + duration = "P6M" + priority = 20 + criteria { absolute_criteria = "FirstOfWeek" } } retention_rule { - name = "thursday" - duration = "P1W" - tagging_priority = 25 - tagging_criteria { + name = "thursday" + duration = "P1W" + priority = 25 + criteria { days_of_week = ["Thursday"] scheduled_backup_times = ["2021-05-23T02:30:00Z"] } } retention_rule { - name = "monthly" - duration = "P1D" - tagging_priority = 30 - tagging_criteria { + name = "monthly" + duration = "P1D" + priority = 30 + criteria { weeks_of_month = ["First", "Last"] days_of_week = ["Tuesday"] scheduled_backup_times = ["2021-05-23T02:30:00Z"] diff --git a/website/docs/r/data_protection_backup_policy_postgresql.html.markdown b/website/docs/r/data_protection_backup_policy_postgresql.html.markdown index 0a39885bc5c7..d5ef14dede16 100644 --- a/website/docs/r/data_protection_backup_policy_postgresql.html.markdown +++ b/website/docs/r/data_protection_backup_policy_postgresql.html.markdown @@ -36,29 +36,29 @@ resource "azurerm_data_protection_backup_policy_postgresql" "example" { default_retention_duration = "P4M" retention_rule { - name = "weekly" - duration = "P6M" - tagging_priority = 20 - tagging_criteria { + name = "weekly" + duration = "P6M" + priority = 20 + criteria { absolute_criteria = "FirstOfWeek" } } retention_rule { - name = "thursday" - duration = "P1W" - tagging_priority = 25 - tagging_criteria { + name = "thursday" + duration = "P1W" + priority = 25 + criteria { days_of_week = ["Thursday"] scheduled_backup_times = ["2021-05-23T02:30:00Z"] } } retention_rule { - name = "monthly" - duration = "P1D" - tagging_priority = 15 - tagging_criteria { + name = "monthly" + duration = "P1D" + priority = 15 + criteria { weeks_of_month = ["First", "Last"] days_of_week = ["Tuesday"] scheduled_backup_times = ["2021-05-23T02:30:00Z"] @@ -93,13 +93,13 @@ A `retention_rule` block supports the following: * `duration` - (Required) Duration after which the backup is deleted. It should follow `ISO 8601` duration format. Changing this forces a new Backup Policy PostgreSQL to be created. -* `tagging_criteria` - (Required) A `tagging_criteria` block as defined below. Changing this forces a new Backup Policy PostgreSQL to be created. +* `criteria` - (Required) A `criteria` block as defined below. Changing this forces a new Backup Policy PostgreSQL to be created. -* `tagging_priority` - (Required) Retention Tag priority. Changing this forces a new Backup Policy Postgre Sql to be created. +* `priority` - (Required) Specifies the priority of the rule. The priority number must be unique for each rule. The lower the priority number, the higher the priority of the rule. Changing this forces a new Backup Policy Postgre Sql to be created. --- -A `tagging_criteria` block supports the following: +A `criteria` block supports the following: * `absolute_criteria` - (Optional) Possible values are `AllBackup`, `FirstOfDay`, `FirstOfWeek`, `FirstOfMonth` and `FirstOfYear`. These values mean the first successful backup of the day/week/month/year. Changing this forces a new Backup Policy PostgreSQL to be created.