Skip to content

Commit

Permalink
New Data Source: azurerm_mssql_managed_database (#27026)
Browse files Browse the repository at this point in the history
* Added MSSQL Managed Database Data Source

* Grouped Imports

Removed Stray Comments

Replaced Parent Manged Instance Resource arguments with managed_instance_id

Cleanup Computed Args

Formatted Code

Updated Attributes

* Apply suggestions from code review

Co-authored-by: stephybun <[email protected]>

* Apply suggestions from code review

Co-authored-by: stephybun [email protected]

* Fixed Lint Errors

* Adjusted mssql_managed_database_data_source

* Update internal/services/mssqlmanagedinstance/mssql_managed_database_data_source_test.go

That makes sense. Thank you

Co-authored-by: stephybun <[email protected]>

* Ran terraform fmt on mssql_managed_database_data_source_test.go

---------

Co-authored-by: Amelia Wheeler <[email protected]>
Co-authored-by: stephybun <[email protected]>
  • Loading branch information
3 people authored Nov 26, 2024
1 parent ffe9ec3 commit 1196cc9
Show file tree
Hide file tree
Showing 4 changed files with 302 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package mssqlmanagedinstance

import (
"context"
"fmt"
"time"

"github.com/hashicorp/go-azure-helpers/lang/pointer"
"github.com/hashicorp/go-azure-helpers/lang/response"
"github.com/hashicorp/go-azure-helpers/resourcemanager/commonids"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-provider-azurerm/internal/sdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/mssqlmanagedinstance/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
)

type MsSqlManagedDatabaseDataSourceModel struct {
Name string `tfschema:"name"`
ResourceGroupName string `tfschema:"resource_group_name"`
ManagedInstanceName string `tfschema:"managed_instance_name"`
ManagedInstanceId string `tfschema:"managed_instance_id"`
LongTermRetentionPolicy []LongTermRetentionPolicy `tfschema:"long_term_retention_policy"`
ShortTermRetentionDays int64 `tfschema:"short_term_retention_days"`
PointInTimeRestore []PointInTimeRestore `tfschema:"point_in_time_restore"`
}

var _ sdk.DataSource = MsSqlManagedDatabaseDataSource{}

type MsSqlManagedDatabaseDataSource struct{}

func (d MsSqlManagedDatabaseDataSource) ResourceType() string {
return "azurerm_mssql_managed_database"
}

func (d MsSqlManagedDatabaseDataSource) ModelObject() interface{} {
return &MsSqlManagedDatabaseDataSourceModel{}
}

func (d MsSqlManagedDatabaseDataSource) IDValidationFunc() pluginsdk.SchemaValidateFunc {
return validate.ManagedDatabaseID
}

func (d MsSqlManagedDatabaseDataSource) Arguments() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{
"name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.ValidateMsSqlManagedInstanceDatabaseName,
},
"managed_instance_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: commonids.ValidateSqlManagedInstanceID,
},
}
}

func (d MsSqlManagedDatabaseDataSource) Attributes() map[string]*pluginsdk.Schema {
return map[string]*pluginsdk.Schema{
"managed_instance_name": {
Type: pluginsdk.TypeString,
Computed: true,
},
"resource_group_name": {
Type: pluginsdk.TypeString,
Computed: true,
},
"long_term_retention_policy": {
Type: pluginsdk.TypeList,
Computed: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"weekly_retention": {
Type: pluginsdk.TypeString,
Computed: true,
},

"monthly_retention": {
Type: pluginsdk.TypeString,
Computed: true,
},

"yearly_retention": {
Type: pluginsdk.TypeString,
Computed: true,
},

"week_of_year": {
Type: pluginsdk.TypeInt,
Computed: true,
},

"immutable_backups_enabled": {
Type: pluginsdk.TypeBool,
Computed: true,
},
},
},
},
"short_term_retention_days": {
Type: pluginsdk.TypeInt,
Computed: true,
},
"point_in_time_restore": {
Type: schema.TypeList,
Computed: true,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"restore_point_in_time": {
Type: pluginsdk.TypeString,
Computed: true,
},
"source_database_id": {
Type: schema.TypeString,
Computed: true,
},
},
},
},
}
}

func (d MsSqlManagedDatabaseDataSource) Read() sdk.ResourceFunc {
return sdk.ResourceFunc{
Timeout: 5 * time.Minute,
Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error {
client := metadata.Client.MSSQLManagedInstance.ManagedDatabasesClient
subscriptionId := metadata.Client.Account.SubscriptionId
longTermRetentionClient := metadata.Client.MSSQLManagedInstance.ManagedInstancesLongTermRetentionPoliciesClient
shortTermRetentionClient := metadata.Client.MSSQLManagedInstance.ManagedInstancesShortTermRetentionPoliciesClient

var state MsSqlManagedDatabaseDataSourceModel
if err := metadata.Decode(&state); err != nil {
return fmt.Errorf("decoding: %+v)", err)
}

managedInstanceId, err := commonids.ParseSqlManagedInstanceID(state.ManagedInstanceId)
if err != nil {
return err
}

id := commonids.NewSqlManagedInstanceDatabaseID(subscriptionId, managedInstanceId.ResourceGroupName, managedInstanceId.ManagedInstanceName, state.Name)
resp, err := client.Get(ctx, id)
if err != nil {
if response.WasNotFound(resp.HttpResponse) {
return fmt.Errorf("%s was not found", id)
}
return fmt.Errorf("retrieving %s: %v", id, err)
}

model := MsSqlManagedDatabaseDataSourceModel{
Name: id.DatabaseName,
ManagedInstanceName: managedInstanceId.ManagedInstanceName,
ResourceGroupName: id.ResourceGroupName,
ManagedInstanceId: managedInstanceId.ID(),
}

ltrResp, err := longTermRetentionClient.Get(ctx, id)
if err != nil {
return fmt.Errorf("retrieving Long Term Retention Policy for %s: %v", id, err)
}

if ltrResp.Model != nil && ltrResp.Model.Properties != nil {
model.LongTermRetentionPolicy = flattenLongTermRetentionPolicy(*ltrResp.Model.Properties)
}

shortTermRetentionResp, err := shortTermRetentionClient.Get(ctx, id)
if err != nil {
return fmt.Errorf("retrieving Short Term Retention Policy for %s: %v", id, err)
}

if shortTermRetentionResp.Model != nil && shortTermRetentionResp.Model.Properties != nil {
model.ShortTermRetentionDays = pointer.From(shortTermRetentionResp.Model.Properties.RetentionDays)
}

if v, ok := metadata.ResourceData.GetOk("point_in_time_restore"); ok {
model.PointInTimeRestore = flattenManagedDatabasePointInTimeRestore(v)
}

metadata.SetID(id)
return metadata.Encode(&model)
},
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package mssqlmanagedinstance_test

import (
"fmt"
"testing"

"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
)

type MsSqlManagedDatabaseDataSource struct{}

func TestAccDataSourceMsSqlManagedDatabase_basic(t *testing.T) {
data := acceptance.BuildTestData(t, "data.azurerm_mssql_managed_database", "test")

data.DataSourceTest(t, []acceptance.TestStep{
{
Config: MsSqlManagedDatabaseDataSource{}.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).Key("name").Exists(),
check.That(data.ResourceName).Key("managed_instance_id").Exists(),
),
},
})
}

func (d MsSqlManagedDatabaseDataSource) basic(data acceptance.TestData) string {
return fmt.Sprintf(`
%[1]s
data "azurerm_mssql_managed_database" "test" {
name = azurerm_mssql_managed_database.test.name
managed_instance_id = azurerm_mssql_managed_database.test.managed_instance_id
}
`, MsSqlManagedDatabase{}.basic(data))
}
1 change: 1 addition & 0 deletions internal/services/mssqlmanagedinstance/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func (r Registration) SupportedResources() map[string]*pluginsdk.Resource {
// DataSources returns the typed DataSources supported by this service
func (r Registration) DataSources() []sdk.DataSource {
return []sdk.DataSource{
MsSqlManagedDatabaseDataSource{},
MsSqlManagedInstanceDataSource{},
}
}
Expand Down
73 changes: 73 additions & 0 deletions website/docs/d/mssql_managed_database.html.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
---
subcategory: "Database"
layout: "azurerm"
page_title: "Azure Resource Manager: Data Source: azurerm_mssql_managed_database"
description: |-
Gets information about an existing Azure SQL Azure Managed Database.
---

# Data Source: azurerm_mssql_managed_database

Use this data source to access information about an existing Azure SQL Azure Managed Database.

## Example Usage

```hcl
data "azurerm_mssql_managed_database" "example" {
name = "example"
resource_group_name = azurerm_resource_group.example.name
managed_instance_name = azurerm_mssql_managed_instance.example.name
}
```

## Arguments Reference

The following arguments are supported:

* `name` - (Required) The name of this Azure SQL Azure Managed Database.

* `managed_instance_id` - (Required) The SQL Managed Instance ID.

## Attributes Reference

In addition to the Arguments listed above - the following Attributes are exported:

* `id` - The Azure SQL Managed Database ID.

* `long_term_retention_policy` - A `long_term_retention_policy` block as defined below.

* `resource_group_name` - The name of the Resource Group where the Azure SQL Azure Managed Instance exists.

* `managed_instance_name` - The name of the Managed Instance.

* `point_in_time_restore` - A `point_in_time_restore` block as defined below.

* `short_term_retention_days` - The backup retention period in days. This is how many days Point-in-Time Restore will be supported.

---

A `long_term_retention_policy` block exports the following:

* `immutable_backups_enabled` - Specifies if the backups are immutable.

* `monthly_retention` - The monthly retention policy for an LTR backup in an ISO 8601 format.

* `week_of_year` - The week of year to take the yearly backup.

* `weekly_retention` - The weekly retention policy for an LTR backup in an ISO 8601 format.

* `yearly_retention` - The yearly retention policy for an LTR backup in an ISO 8601 format.

---

A `point_in_time_restore` block exports the following:

* `restore_point_in_time` - The point in time for the restore from `source_database_id`.

* `source_database_id` - The source database ID that is used to restore from.

## Timeouts

The `timeouts` block allows you to specify [timeouts](https://www.terraform.io/language/resources/syntax#operation-timeouts) for certain actions:

* `read` - (Defaults to 5 minutes) Used when retrieving the Azure SQL Azure Managed Database.

0 comments on commit 1196cc9

Please sign in to comment.