Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

New resource azurerm_mssql_server_extended_auditing_policy #8447

Merged
merged 5 commits into from
Sep 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
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 resourceArmMsSqlServerExtendedAuditingPolicy() *schema.Resource {
return &schema.Resource{
Create: resourceArmMsSqlServerExtendedAuditingPolicyCreateUpdate,
Read: resourceArmMsSqlServerExtendedAuditingPolicyRead,
Update: resourceArmMsSqlServerExtendedAuditingPolicyCreateUpdate,
Delete: resourceArmMsSqlServerExtendedAuditingPolicyDelete,

Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error {
_, err := parse.MssqlServerExtendedAuditingPolicyID(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{
"server_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.MsSqlServerID,
},

"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 resourceArmMsSqlServerExtendedAuditingPolicyCreateUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).MSSQL.ServerExtendedBlobAuditingPoliciesClient
ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
defer cancel()

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

serverId, err := parse.MsSqlServerID(d.Get("server_id").(string))
if err != nil {
return err
}

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

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

params := sql.ExtendedServerBlobAuditingPolicy{
ExtendedServerBlobAuditingPolicyProperties: &sql.ExtendedServerBlobAuditingPolicyProperties{
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.ExtendedServerBlobAuditingPolicyProperties.StorageAccountAccessKey = utils.String(v.(string))
}

future, err := client.CreateOrUpdate(ctx, serverId.ResourceGroup, serverId.Name, params)
if err != nil {
return fmt.Errorf("creating MsSql Server %q Extended Auditing Policy (Resource Group %q): %+v", serverId.Name, serverId.ResourceGroup, err)
}

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for creation of MsSql Server %q Extended Auditing Policy (Resource Group %q): %+v", serverId.Name, serverId.ResourceGroup, err)
}

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

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

d.SetId(*read.ID)

return resourceArmMsSqlServerExtendedAuditingPolicyRead(d, meta)
}

func resourceArmMsSqlServerExtendedAuditingPolicyRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).MSSQL.ServerExtendedBlobAuditingPoliciesClient
serverClient := meta.(*clients.Client).MSSQL.ServersClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

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

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

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

d.Set("server_id", serverResp.ID)

if props := resp.ExtendedServerBlobAuditingPolicyProperties; 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 resourceArmMsSqlServerExtendedAuditingPolicyDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).MSSQL.ServerExtendedBlobAuditingPoliciesClient
ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
defer cancel()

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

params := sql.ExtendedServerBlobAuditingPolicy{
ExtendedServerBlobAuditingPolicyProperties: &sql.ExtendedServerBlobAuditingPolicyProperties{
State: sql.BlobAuditingPolicyStateDisabled,
},
}

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

if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return fmt.Errorf("waiting for deletion of MsSql Server %q Extended Auditing Policy (Resource Group %q): %+v", id.MsSqlServer, id.ResourceGroup, err)
}

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

type MsSqlServerExtendedAuditingPolicyId struct {
MsSqlServer string
ResourceGroup string
}

func NewMsSqlDatabaseID(resourceGroup, msSqlServer, name string) MsSqlDatabaseId {
return MsSqlDatabaseId{
ResourceGroup: resourceGroup,
Expand Down Expand Up @@ -166,3 +171,28 @@ func MssqlDatabaseExtendedAuditingPolicyID(input string) (*MsSqlDatabaseExtended

return &sqlDatabaseExtendedAuditingPolicyId, nil
}

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

sqlServerExtendedAuditingPolicyId := MsSqlServerExtendedAuditingPolicyId{
ResourceGroup: id.ResourceGroup,
}

if sqlServerExtendedAuditingPolicyId.MsSqlServer, err = id.PopSegment("servers"); 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 &sqlServerExtendedAuditingPolicyId, nil
}
78 changes: 78 additions & 0 deletions azurerm/internal/services/mssql/parse/mssql_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -319,3 +319,81 @@ func TestMssqlDatabaseExtendedAuditingPolicy(t *testing.T) {
}
}
}

func TestMssqlServerExtendedAuditingPolicy(t *testing.T) {
testData := []struct {
Name string
Input string
Expected *MsSqlServerExtendedAuditingPolicyId
}{
{
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 Extended Auditing Policy",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1",
Expected: nil,
},
{
Name: "Missing Extended Auditing Policy Value",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1/extendedAuditingSettings",
Expected: nil,
},
{
Name: "Extended Auditing Policy",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1/extendedAuditingSettings/default",
Expected: &MsSqlServerExtendedAuditingPolicyId{
ResourceGroup: "resGroup1",
MsSqlServer: "sqlServer1",
},
},
{
Name: "Wrong Casing",
Input: "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resGroup1/providers/Microsoft.Sql/servers/sqlServer1/ExtendedAuditingSettings/default",
Expected: nil,
},
}

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

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

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

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)
}
}
}
1 change: 1 addition & 0 deletions azurerm/internal/services/mssql/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func (r Registration) SupportedResources() map[string]*schema.Resource {
"azurerm_mssql_database_vulnerability_assessment_rule_baseline": resourceArmMssqlDatabaseVulnerabilityAssessmentRuleBaseline(),
"azurerm_mssql_elasticpool": resourceArmMsSqlElasticPool(),
"azurerm_mssql_server": resourceArmMsSqlServer(),
"azurerm_mssql_server_extended_auditing_policy": resourceArmMsSqlServerExtendedAuditingPolicy(),
"azurerm_mssql_server_security_alert_policy": resourceArmMssqlServerSecurityAlertPolicy(),
"azurerm_mssql_server_vulnerability_assessment": resourceArmMssqlServerVulnerabilityAssessment(),
"azurerm_mssql_virtual_machine": resourceArmMsSqlVirtualMachine(),
Expand Down
Loading