Skip to content

Commit

Permalink
New resource azurerm_mssql_database_extended_auditing_policy (#7793)
Browse files Browse the repository at this point in the history
  • Loading branch information
yupwei68 authored Sep 10, 2020
1 parent 65534fe commit a6dc315
Show file tree
Hide file tree
Showing 13 changed files with 870 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ import (

func ExtendedAuditingSchema() *schema.Schema {
return &schema.Schema{
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Type: schema.TypeList,
Optional: true,
Computed: true,
Deprecated: "the `extended_auditing_policy` block has been moved to `azurerm_mssql_server_extended_auditing_policy` and `azurerm_mssql_database_extended_auditing_policy`. This block will be removed in version 3.0 of the provider.",
ConfigMode: schema.SchemaConfigModeAttr,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"storage_account_access_key": {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
package mssql

import (
"fmt"
"log"
"time"

"github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v3.0/sql"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"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/mssql/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/mssql/validate"
azSchema "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/utils"
)

func resourceArmMsSqlDatabaseExtendedAuditingPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceArmMsSqlDatabaseExtendedAuditingPolicyCreateUpdate,
Read: resourceArmMsSqlDatabaseExtendedAuditingPolicyRead,
Update: resourceArmMsSqlDatabaseExtendedAuditingPolicyCreateUpdate,
Delete: resourceArmMsSqlDatabaseExtendedAuditingPolicyDelete,

Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error {
_, err := parse.MssqlDatabaseExtendedAuditingPolicyID(id)
return err
}),

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),
},

Schema: map[string]*schema.Schema{
"database_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.MsSqlDatabaseID,
},

"storage_endpoint": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.IsURLWithHTTPS,
},

"storage_account_access_key": {
Type: schema.TypeString,
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringIsNotEmpty,
},

"storage_account_access_key_is_secondary": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},

"retention_in_days": {
Type: schema.TypeInt,
Optional: true,
Default: 0,
ValidateFunc: validation.IntBetween(0, 3285),
},
},
}
}

func resourceArmMsSqlDatabaseExtendedAuditingPolicyCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).MSSQL.DatabaseExtendedBlobAuditingPoliciesClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()

log.Printf("[INFO] preparing arguments for MsSql Database Extended Auditing Policy creation.")

dbId, err := parse.MsSqlDatabaseID(d.Get("database_id").(string))
if err != nil {
return err
}

if d.IsNewResource() {
existing, err := client.Get(ctx, dbId.ResourceGroup, dbId.MsSqlServer, dbId.Name)
if err != nil {
if !utils.ResponseWasNotFound(existing.Response) {
return fmt.Errorf("Failed to check for presence of existing Database %q Sql Auditing (MsSql Server %q / Resource Group %q): %s", dbId.Name, dbId.MsSqlServer, dbId.ResourceGroup, err)
}
}

// if state is not disabled, we should import it.
if existing.ID != nil && *existing.ID != "" && existing.ExtendedDatabaseBlobAuditingPolicyProperties != nil && existing.ExtendedDatabaseBlobAuditingPolicyProperties.State != sql.BlobAuditingPolicyStateDisabled {
return tf.ImportAsExistsError("azurerm_mssql_database_extended_auditing_policy", *existing.ID)
}
}

params := sql.ExtendedDatabaseBlobAuditingPolicy{
ExtendedDatabaseBlobAuditingPolicyProperties: &sql.ExtendedDatabaseBlobAuditingPolicyProperties{
State: sql.BlobAuditingPolicyStateEnabled,
StorageEndpoint: utils.String(d.Get("storage_endpoint").(string)),
IsStorageSecondaryKeyInUse: utils.Bool(d.Get("storage_account_access_key_is_secondary").(bool)),
RetentionDays: utils.Int32(int32(d.Get("retention_in_days").(int))),
},
}

if v, ok := d.GetOk("storage_account_access_key"); ok {
params.ExtendedDatabaseBlobAuditingPolicyProperties.StorageAccountAccessKey = utils.String(v.(string))
}

if _, err = client.CreateOrUpdate(ctx, dbId.ResourceGroup, dbId.MsSqlServer, dbId.Name, params); err != nil {
return fmt.Errorf("creating MsSql Database %q Extended Auditing Policy (Sql Server %q / Resource Group %q): %+v", dbId.Name, dbId.MsSqlServer, dbId.ResourceGroup, err)
}

read, err := client.Get(ctx, dbId.ResourceGroup, dbId.MsSqlServer, dbId.Name)
if err != nil {
return fmt.Errorf("retrieving MsSql Database %q Extended Auditing Policy (MsSql Server Name %q / Resource Group %q): %+v", dbId.Name, dbId.MsSqlServer, dbId.ResourceGroup, err)
}

if read.ID == nil || *read.ID == "" {
return fmt.Errorf("reading MsSql Database %q Extended Auditing Policy (MsSql Server Name %q / Resource Group %q) ID is empty or nil", dbId.Name, dbId.MsSqlServer, dbId.ResourceGroup)
}

d.SetId(*read.ID)

return resourceArmMsSqlDatabaseExtendedAuditingPolicyRead(d, meta)
}

func resourceArmMsSqlDatabaseExtendedAuditingPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).MSSQL.DatabaseExtendedBlobAuditingPoliciesClient
dbClient := meta.(*clients.Client).MSSQL.DatabasesClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

id, err := parse.MssqlDatabaseExtendedAuditingPolicyID(d.Id())
if err != nil {
return err
}

resp, err := client.Get(ctx, id.ResourceGroup, id.MsSqlServer, id.MsDBName)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
d.SetId("")
return nil
}
return fmt.Errorf("reading MsSql Database %s Extended Auditing Policy (MsSql Server Name %q / Resource Group %q): %s", id.MsDBName, id.MsSqlServer, id.ResourceGroup, err)
}

dbResp, err := dbClient.Get(ctx, id.ResourceGroup, id.MsSqlServer, id.MsDBName)
if err != nil || *dbResp.ID == "" {
return fmt.Errorf("reading MsSql Database %q ID is empty or nil(Resource Group %q): %s", id.MsSqlServer, id.ResourceGroup, err)
}

d.Set("database_id", dbResp.ID)

if props := resp.ExtendedDatabaseBlobAuditingPolicyProperties; props != nil {
d.Set("storage_endpoint", props.StorageEndpoint)
d.Set("storage_account_access_key_is_secondary", props.IsStorageSecondaryKeyInUse)
d.Set("retention_in_days", props.RetentionDays)
}

return nil
}

func resourceArmMsSqlDatabaseExtendedAuditingPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).MSSQL.DatabaseExtendedBlobAuditingPoliciesClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()

id, err := parse.MssqlDatabaseExtendedAuditingPolicyID(d.Id())
if err != nil {
return err
}

params := sql.ExtendedDatabaseBlobAuditingPolicy{
ExtendedDatabaseBlobAuditingPolicyProperties: &sql.ExtendedDatabaseBlobAuditingPolicyProperties{
State: sql.BlobAuditingPolicyStateDisabled,
},
}

if _, err := client.CreateOrUpdate(ctx, id.ResourceGroup, id.MsSqlServer, id.MsDBName, params); err != nil {
return fmt.Errorf("deleting MsSql Database %q Extended Auditing Policy( MsSql Server %q / Resource Group %q): %+v", id.MsDBName, id.MsSqlServer, id.ResourceGroup, err)
}

return nil
}
35 changes: 35 additions & 0 deletions azurerm/internal/services/mssql/parse/mssql.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ type MsSqlElasticPoolId struct {
ResourceGroup string
}

type MsSqlDatabaseExtendedAuditingPolicyId struct {
MsDBName string
MsSqlServer string
ResourceGroup string
}

func MsSqlDatabaseID(input string) (*MsSqlDatabaseId, error) {
id, err := azure.ParseAzureResourceID(input)
if err != nil {
Expand Down Expand Up @@ -119,3 +125,32 @@ func MssqlVmID(input string) (*MssqlVmId, error) {

return &sqlvm, nil
}

func MssqlDatabaseExtendedAuditingPolicyID(input string) (*MsSqlDatabaseExtendedAuditingPolicyId, error) {
id, err := azure.ParseAzureResourceID(input)
if err != nil {
return nil, fmt.Errorf("[ERROR] Unable to parse Microsoft Sql Database Extended Auditing Policy %q: %+v", input, err)
}

sqlDatabaseExtendedAuditingPolicyId := MsSqlDatabaseExtendedAuditingPolicyId{
ResourceGroup: id.ResourceGroup,
}

if sqlDatabaseExtendedAuditingPolicyId.MsSqlServer, err = id.PopSegment("servers"); err != nil {
return nil, err
}

if sqlDatabaseExtendedAuditingPolicyId.MsDBName, err = id.PopSegment("databases"); err != nil {
return nil, err
}

if _, err = id.PopSegment("extendedAuditingSettings"); err != nil {
return nil, err
}

if err := id.ValidateNoEmptySegments(input); err != nil {
return nil, err
}

return &sqlDatabaseExtendedAuditingPolicyId, nil
}
93 changes: 93 additions & 0 deletions azurerm/internal/services/mssql/parse/mssql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,96 @@ func TestMsSqlVmID(t *testing.T) {
}
}
}

func TestMssqlDatabaseExtendedAuditingPolicy(t *testing.T) {
testData := []struct {
Name string
Input string
Expected *MsSqlDatabaseExtendedAuditingPolicyId
}{
{
Name: "Empty",
Input: "",
Expected: nil,
},
{
Name: "No Resource Groups Segment",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000",
Expected: nil,
},
{
Name: "No Resource Groups Value",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/",
Expected: nil,
},
{
Name: "Resource Group ID",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/foo/",
Expected: nil,
},
{
Name: "Missing Sql Server Value",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/",
Expected: nil,
},
{
Name: "Missing Sql Database",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1",
Expected: nil,
},
{
Name: "Missing Sql Database Value",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1/databases",
Expected: nil,
},
{
Name: "Missing Extended Auditing Policy",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1/databases/db1",
Expected: nil,
},
{
Name: "Missing Extended Auditing Policy Value",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1/databases/db1/extendedAuditingSettings",
Expected: nil,
},
{
Name: "Extended Auditing Policy",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1/databases/db1/extendedAuditingSettings/default",
Expected: &MsSqlDatabaseExtendedAuditingPolicyId{
ResourceGroup: "resGroup1",
MsSqlServer: "sqlServer1",
MsDBName: "db1",
},
},
{
Name: "Wrong Casing",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1/databases/db1/ExtendedAuditingSettings/default",
Expected: nil,
},
}

for _, v := range testData {
t.Logf("[DEBUG] Testing %q", v.Name)

actual, err := MssqlDatabaseExtendedAuditingPolicyID(v.Input)
if err != nil {
if v.Expected == nil {
continue
}

t.Fatalf("Expected a value but got an error: %s", err)
}

if actual.MsDBName != v.Expected.MsDBName {
t.Fatalf("Expected %q but got %q for DB Name", v.Expected.MsDBName, actual.MsDBName)
}

if actual.MsSqlServer != v.Expected.MsSqlServer {
t.Fatalf("Expected %q but got %q for Server Name", v.Expected.MsSqlServer, actual.MsSqlServer)
}

if actual.ResourceGroup != v.Expected.ResourceGroup {
t.Fatalf("Expected %q but got %q for Resource Group", v.Expected.ResourceGroup, actual.ResourceGroup)
}
}
}
3 changes: 2 additions & 1 deletion azurerm/internal/services/mssql/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ 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_mssql_database": resourceArmMsSqlDatabase(),
"azurerm_mssql_database": resourceArmMsSqlDatabase(),
"azurerm_mssql_database_extended_auditing_policy": resourceArmMsSqlDatabaseExtendedAuditingPolicy(),
"azurerm_mssql_database_vulnerability_assessment_rule_baseline": resourceArmMssqlDatabaseVulnerabilityAssessmentRuleBaseline(),
"azurerm_mssql_elasticpool": resourceArmMsSqlElasticPool(),
"azurerm_mssql_server": resourceArmMsSqlServer(),
Expand Down
Loading

0 comments on commit a6dc315

Please sign in to comment.