Skip to content

Commit

Permalink
New Resource: `azurerm_mssql_managed_instance_vulnerability_assessmen…
Browse files Browse the repository at this point in the history
…t` (#16639)
  • Loading branch information
mbfrahry authored May 5, 2022
1 parent ad01896 commit b8e2445
Show file tree
Hide file tree
Showing 10 changed files with 747 additions and 0 deletions.
5 changes: 5 additions & 0 deletions internal/services/mssql/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type Client struct {
LongTermRetentionPoliciesClient *sql.LongTermRetentionPoliciesClient
ManagedDatabasesClient *sql.ManagedDatabasesClient
ManagedInstancesClient *sql.ManagedInstancesClient
ManagedInstanceVulnerabilityAssessmentsClient *sql.ManagedInstanceVulnerabilityAssessmentsClient
OutboundFirewallRulesClient *sql.OutboundFirewallRulesClient
ManagedInstanceAdministratorsClient *sql.ManagedInstanceAdministratorsClient
ManagedInstanceAzureADOnlyAuthenticationsClient *sql.ManagedInstanceAzureADOnlyAuthenticationsClient
Expand Down Expand Up @@ -96,6 +97,9 @@ func NewClient(o *common.ClientOptions) *Client {
managedInstanceAzureADOnlyAuthenticationsClient := sql.NewManagedInstanceAzureADOnlyAuthenticationsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&managedInstanceAzureADOnlyAuthenticationsClient.Client, o.ResourceManagerAuthorizer)

managedInstanceVulnerabilityAssessmentsClient := sql.NewManagedInstanceVulnerabilityAssessmentsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&managedInstanceVulnerabilityAssessmentsClient.Client, o.ResourceManagerAuthorizer)

outboundFirewallRulesClient := sql.NewOutboundFirewallRulesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId)
o.ConfigureClient(&outboundFirewallRulesClient.Client, o.ResourceManagerAuthorizer)

Expand Down Expand Up @@ -157,6 +161,7 @@ func NewClient(o *common.ClientOptions) *Client {
ManagedInstanceAdministratorsClient: &managedInstancesAdministratorsClient,
ManagedInstanceAzureADOnlyAuthenticationsClient: &managedInstanceAzureADOnlyAuthenticationsClient,
ManagedInstancesClient: &managedInstancesClient,
ManagedInstanceVulnerabilityAssessmentsClient: &managedInstanceVulnerabilityAssessmentsClient,
OutboundFirewallRulesClient: &outboundFirewallRulesClient,
ReplicationLinksClient: &replicationLinksClient,
RestorableDroppedDatabasesClient: &restorableDroppedDatabasesClient,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
package mssql

import (
"fmt"
"log"
"time"

"github.com/Azure/azure-sdk-for-go/services/preview/sql/mgmt/v5.0/sql"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/validate"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)

func resourceMsSqlManagedInstanceVulnerabilityAssessment() *pluginsdk.Resource {
return &pluginsdk.Resource{
Create: resourceMsSqlManagedInstanceVulnerabilityAssessmentCreateUpdate,
Read: resourceMsSqlManagedInstanceVulnerabilityAssessmentRead,
Update: resourceMsSqlManagedInstanceVulnerabilityAssessmentCreateUpdate,
Delete: resourceMsSqlManagedInstanceVulnerabilityAssessmentDelete,

Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
_, err := parse.ManagedInstanceVulnerabilityAssessmentID(id)
return err
}),

Timeouts: &pluginsdk.ResourceTimeout{
Create: pluginsdk.DefaultTimeout(60 * time.Minute),
Read: pluginsdk.DefaultTimeout(5 * time.Minute),
Update: pluginsdk.DefaultTimeout(60 * time.Minute),
Delete: pluginsdk.DefaultTimeout(60 * time.Minute),
},

Schema: map[string]*pluginsdk.Schema{
"managed_instance_id": {
Type: pluginsdk.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validate.ManagedInstanceID,
},

"storage_container_path": {
Type: pluginsdk.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},

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

"storage_container_sas_key": {
Type: pluginsdk.TypeString,
Optional: true,
Sensitive: true,
ValidateFunc: validation.StringIsNotEmpty,
},

"recurring_scans": {
Type: pluginsdk.TypeList,
Optional: true,
Computed: true,
MaxItems: 1,
Elem: &pluginsdk.Resource{
Schema: map[string]*pluginsdk.Schema{
"email_subscription_admins": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: true,
},

"emails": {
Type: pluginsdk.TypeList,
Optional: true,
Elem: &pluginsdk.Schema{
Type: pluginsdk.TypeString,
ValidateFunc: validation.StringIsNotEmpty,
},
},

"enabled": {
Type: pluginsdk.TypeBool,
Optional: true,
Default: false,
},
},
},
},
},
}
}

func resourceMsSqlManagedInstanceVulnerabilityAssessmentCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).MSSQL.ManagedInstanceVulnerabilityAssessmentsClient
ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d)
defer cancel()

instanceId, err := parse.ManagedInstanceID(d.Get("managed_instance_id").(string))
if err != nil {
return err
}

id := parse.NewManagedInstanceVulnerabilityAssessmentID(instanceId.SubscriptionId, instanceId.ResourceGroup, instanceId.Name, "default")

vulnerabilityAssessment := sql.ManagedInstanceVulnerabilityAssessment{
ManagedInstanceVulnerabilityAssessmentProperties: &sql.ManagedInstanceVulnerabilityAssessmentProperties{
StorageContainerPath: utils.String(d.Get("storage_container_path").(string)),
StorageAccountAccessKey: utils.String(d.Get("storage_account_access_key").(string)),
StorageContainerSasKey: utils.String(d.Get("storage_container_sas_key").(string)),
RecurringScans: expandRecurringScans(d),
},
}

_, err = client.CreateOrUpdate(ctx, id.ResourceGroup, id.ManagedInstanceName, vulnerabilityAssessment)
if err != nil {
return fmt.Errorf("updataing %s: %v", id.ID(), err)
}

d.SetId(id.ID())

return resourceMsSqlManagedInstanceVulnerabilityAssessmentRead(d, meta)
}

func resourceMsSqlManagedInstanceVulnerabilityAssessmentRead(d *pluginsdk.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).MSSQL.ManagedInstanceVulnerabilityAssessmentsClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

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

result, err := client.Get(ctx, id.ResourceGroup, id.ManagedInstanceName)
if err != nil {
if utils.ResponseWasNotFound(result.Response) {
log.Printf("[WARN] %s not found", id.ID())
d.SetId("")
return nil
}

return fmt.Errorf("making read request: %+v", err)
}

if props := result.ManagedInstanceVulnerabilityAssessmentProperties; props != nil {
d.Set("storage_container_path", props.StorageContainerPath)

if props.RecurringScans != nil {
if err := d.Set("recurring_scans", flattenRecurringScans(props.RecurringScans)); err != nil {
return fmt.Errorf("setting `recurring_scans`: %+v", err)
}
}
}

return nil
}

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

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

_, err = client.Delete(ctx, id.ResourceGroup, id.ManagedInstanceName)
if err != nil {
return fmt.Errorf("deleting Managed Instance Vulnerability Assessment %s: %+v", id.ID(), err)
}

return nil
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
package mssql_test

import (
"context"
"fmt"
"testing"

"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance"
"github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check"
"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
"github.com/hashicorp/terraform-provider-azurerm/internal/services/mssql/parse"
"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
"github.com/hashicorp/terraform-provider-azurerm/utils"
)

type MsSqlManagedInstanceVulnerabilityAssessmentResource struct{}

func TestAccAzureRMMssqlManagedInstanceVulnerabilityAssessment_basic(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_mssql_managed_instance_vulnerability_assessment", "test")
r := MsSqlManagedInstanceVulnerabilityAssessmentResource{}

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep("storage_account_access_key"),
})
}

func TestAccAzureRMMssqlManagedInstanceVulnerabilityAssessment_update(t *testing.T) {
data := acceptance.BuildTestData(t, "azurerm_mssql_managed_instance_vulnerability_assessment", "test")
r := MsSqlManagedInstanceVulnerabilityAssessmentResource{}

data.ResourceTest(t, r, []acceptance.TestStep{
{
Config: r.basic(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep("storage_account_access_key"),
{
Config: r.update(data),
Check: acceptance.ComposeTestCheckFunc(
check.That(data.ResourceName).ExistsInAzure(r),
),
},
data.ImportStep("storage_account_access_key"),
})
}

func (MsSqlManagedInstanceVulnerabilityAssessmentResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) {
id, err := parse.ManagedInstanceVulnerabilityAssessmentID(state.ID)
if err != nil {
return nil, err
}

resp, err := client.MSSQL.ManagedInstanceVulnerabilityAssessmentsClient.Get(ctx, id.ResourceGroup, id.ManagedInstanceName)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
return nil, fmt.Errorf("%s does not exist", id.ID())
}

return nil, fmt.Errorf("reading %s: %v", id.ID(), err)
}

return utils.Bool(resp.ID != nil), nil
}

func (r MsSqlManagedInstanceVulnerabilityAssessmentResource) basic(data acceptance.TestData) string {
return fmt.Sprintf(`
%[1]s
resource "azurerm_storage_account" "test" {
name = "accsa%[2]d"
resource_group_name = azurerm_resource_group.test.name
location = "%[3]s"
account_tier = "Standard"
account_replication_type = "GRS"
}
resource "azurerm_storage_container" "test" {
name = "acctestsc%[2]d"
storage_account_name = azurerm_storage_account.test.name
container_access_type = "private"
}
resource "azurerm_mssql_managed_instance_vulnerability_assessment" "test" {
managed_instance_id = azurerm_mssql_managed_instance.test.id
storage_container_path = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/"
storage_account_access_key = azurerm_storage_account.test.primary_access_key
}
`, MsSqlManagedInstanceResource{}.basic(data), data.RandomInteger, data.RandomString)
}

func (r MsSqlManagedInstanceVulnerabilityAssessmentResource) update(data acceptance.TestData) string {
return fmt.Sprintf(`
%[1]s
resource "azurerm_storage_account" "test" {
name = "accsa%[2]d"
resource_group_name = azurerm_resource_group.test.name
location = "%[3]s"
account_tier = "Standard"
account_replication_type = "GRS"
}
resource "azurerm_storage_container" "test" {
name = "acctestsc%[2]d"
storage_account_name = azurerm_storage_account.test.name
container_access_type = "private"
}
resource "azurerm_mssql_managed_instance_vulnerability_assessment" "test" {
managed_instance_id = azurerm_mssql_managed_instance.test.id
storage_container_path = "${azurerm_storage_account.test.primary_blob_endpoint}${azurerm_storage_container.test.name}/"
storage_account_access_key = azurerm_storage_account.test.primary_access_key
recurring_scans {
enabled = true
email_subscription_admins = true
emails = [
"[email protected]",
"[email protected]"
]
}
}
`, MsSqlManagedInstanceResource{}.basic(data), data.RandomInteger, data.RandomString)
}
Loading

0 comments on commit b8e2445

Please sign in to comment.