diff --git a/azurerm/internal/services/sentinel/registration.go b/azurerm/internal/services/sentinel/registration.go index 12c04e0816a6..54aed0199016 100644 --- a/azurerm/internal/services/sentinel/registration.go +++ b/azurerm/internal/services/sentinel/registration.go @@ -36,6 +36,7 @@ func (r Registration) SupportedResources() map[string]*schema.Resource { "azurerm_sentinel_data_connector_azure_active_directory": resourceSentinelDataConnectorAzureActiveDirectory(), "azurerm_sentinel_data_connector_azure_advanced_threat_protection": resourceSentinelDataConnectorAzureAdvancedThreatProtection(), "azurerm_sentinel_data_connector_azure_security_center": resourceSentinelDataConnectorAzureSecurityCenter(), + "azurerm_sentinel_data_connector_microsoft_cloud_app_security": resourceSentinelDataConnectorMicrosoftCloudAppSecurity(), "azurerm_sentinel_data_connector_office_365": resourceSentinelDataConnectorOffice365(), "azurerm_sentinel_data_connector_threat_intelligence": resourceSentinelDataConnectorThreatIntelligence(), } diff --git a/azurerm/internal/services/sentinel/sentinel_data_connector_microsoft_cloud_app_security.go b/azurerm/internal/services/sentinel/sentinel_data_connector_microsoft_cloud_app_security.go new file mode 100644 index 000000000000..a70062b0e07f --- /dev/null +++ b/azurerm/internal/services/sentinel/sentinel_data_connector_microsoft_cloud_app_security.go @@ -0,0 +1,232 @@ +package sentinel + +import ( + "fmt" + "log" + "strings" + "time" + + "github.com/Azure/azure-sdk-for-go/services/preview/securityinsight/mgmt/2019-01-01-preview/securityinsight" + "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" + loganalyticsParse "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/loganalytics/parse" + loganalyticsValidate "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/loganalytics/validate" + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/sentinel/parse" + 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 resourceSentinelDataConnectorMicrosoftCloudAppSecurity() *schema.Resource { + return &schema.Resource{ + Create: resourceSentinelDataConnectorMicrosoftCloudAppSecurityCreateUpdate, + Read: resourceSentinelDataConnectorMicrosoftCloudAppSecurityRead, + Update: resourceSentinelDataConnectorMicrosoftCloudAppSecurityCreateUpdate, + Delete: resourceSentinelDataConnectorMicrosoftCloudAppSecurityDelete, + + Importer: azSchema.ValidateResourceIDPriorToImportThen(func(id string) error { + _, err := parse.DataConnectorID(id) + return err + }, importSentinelDataConnector(securityinsight.DataConnectorKindMicrosoftCloudAppSecurity)), + + 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{ + "name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: validation.StringIsNotEmpty, + }, + + "log_analytics_workspace_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + ValidateFunc: loganalyticsValidate.LogAnalyticsWorkspaceID, + }, + + "tenant_id": { + Type: schema.TypeString, + Optional: true, + Computed: true, + ValidateFunc: validation.IsUUID, + }, + + "alerts_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + + "discovery_logs_enabled": { + Type: schema.TypeBool, + Optional: true, + Default: true, + }, + }, + } +} + +func resourceSentinelDataConnectorMicrosoftCloudAppSecurityCreateUpdate(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Sentinel.DataConnectorsClient + ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d) + defer cancel() + + workspaceId, err := loganalyticsParse.LogAnalyticsWorkspaceID(d.Get("log_analytics_workspace_id").(string)) + if err != nil { + return err + } + name := d.Get("name").(string) + id := parse.NewDataConnectorID(workspaceId.SubscriptionId, workspaceId.ResourceGroup, workspaceId.WorkspaceName, name) + + if d.IsNewResource() { + resp, err := client.Get(ctx, id.ResourceGroup, OperationalInsightsResourceProvider, id.WorkspaceName, name) + if err != nil { + if !utils.ResponseWasNotFound(resp.Response) { + return fmt.Errorf("checking for existing %s: %+v", id, err) + } + } + + if !utils.ResponseWasNotFound(resp.Response) { + return tf.ImportAsExistsError("azurerm_sentinel_data_connector_microsoft_cloud_app_security", id.ID()) + } + } + + tenantId := d.Get("tenant_id").(string) + if tenantId == "" { + tenantId = meta.(*clients.Client).Account.TenantId + } + + alertsEnabled := d.Get("alerts_enabled").(bool) + discoveryLogsEnabled := d.Get("discovery_logs_enabled").(bool) + + // Service will not create the DC in case non of the toggle is enabled. + if !alertsEnabled && !discoveryLogsEnabled { + return fmt.Errorf("either `alerts_enabled` or `discovery_logs_enabled` should be `true`") + } + + alertState := securityinsight.Enabled + if !alertsEnabled { + alertState = securityinsight.Disabled + } + + discoveryLogsState := securityinsight.Enabled + if !discoveryLogsEnabled { + discoveryLogsState = securityinsight.Disabled + } + + param := securityinsight.MCASDataConnector{ + Name: &name, + MCASDataConnectorProperties: &securityinsight.MCASDataConnectorProperties{ + TenantID: &tenantId, + DataTypes: &securityinsight.MCASDataConnectorDataTypes{ + Alerts: &securityinsight.AlertsDataTypeOfDataConnectorAlerts{ + State: alertState, + }, + DiscoveryLogs: &securityinsight.MCASDataConnectorDataTypesDiscoveryLogs{ + State: discoveryLogsState, + }, + }, + }, + Kind: securityinsight.KindMicrosoftCloudAppSecurity, + } + + // Service avoid concurrent updates of this resource via checking the "etag" to guarantee it is the same value as last Read. + // TODO: following code can be removed once the issue below is fixed: + // https://github.com/Azure/azure-rest-api-specs/issues/13203 + if !d.IsNewResource() { + resp, err := client.Get(ctx, id.ResourceGroup, OperationalInsightsResourceProvider, id.WorkspaceName, name) + if err != nil { + return fmt.Errorf("retrieving %s: %+v", id, err) + } + + dc, ok := resp.Value.(securityinsight.MCASDataConnector) + if !ok { + return fmt.Errorf("%s was not a Microsoft Cloud App Security Data Connector", id) + } + param.Etag = dc.Etag + } + + if _, err = client.CreateOrUpdate(ctx, id.ResourceGroup, OperationalInsightsResourceProvider, id.WorkspaceName, id.Name, param); err != nil { + return fmt.Errorf("creating %s: %+v", id, err) + } + + d.SetId(id.ID()) + + return resourceSentinelDataConnectorMicrosoftCloudAppSecurityRead(d, meta) +} + +func resourceSentinelDataConnectorMicrosoftCloudAppSecurityRead(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Sentinel.DataConnectorsClient + ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.DataConnectorID(d.Id()) + if err != nil { + return err + } + workspaceId := loganalyticsParse.NewLogAnalyticsWorkspaceID(id.SubscriptionId, id.ResourceGroup, id.WorkspaceName) + + resp, err := client.Get(ctx, id.ResourceGroup, OperationalInsightsResourceProvider, id.WorkspaceName, id.Name) + if err != nil { + if utils.ResponseWasNotFound(resp.Response) { + log.Printf("[DEBUG] %s was not found - removing from state!", id) + d.SetId("") + return nil + } + + return fmt.Errorf("retrieving %s: %+v", id, err) + } + + dc, ok := resp.Value.(securityinsight.MCASDataConnector) + if !ok { + return fmt.Errorf("%s was not a Microsoft Cloud App Security Data Connector", id) + } + + d.Set("name", id.Name) + d.Set("log_analytics_workspace_id", workspaceId.ID()) + d.Set("tenant_id", dc.TenantID) + + var ( + alertsEnabled bool + discoveryLogsEnabled bool + ) + if dt := dc.DataTypes; dt != nil { + if alert := dt.Alerts; alert != nil { + alertsEnabled = strings.EqualFold(string(alert.State), string(securityinsight.Enabled)) + } + + if discoveryLogs := dt.DiscoveryLogs; discoveryLogs != nil { + discoveryLogsEnabled = strings.EqualFold(string(discoveryLogs.State), string(securityinsight.Enabled)) + } + } + d.Set("discovery_logs_enabled", discoveryLogsEnabled) + d.Set("alerts_enabled", alertsEnabled) + + return nil +} + +func resourceSentinelDataConnectorMicrosoftCloudAppSecurityDelete(d *schema.ResourceData, meta interface{}) error { + client := meta.(*clients.Client).Sentinel.DataConnectorsClient + ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) + defer cancel() + + id, err := parse.DataConnectorID(d.Id()) + if err != nil { + return err + } + + if _, err = client.Delete(ctx, id.ResourceGroup, OperationalInsightsResourceProvider, id.WorkspaceName, id.Name); err != nil { + return fmt.Errorf("deleting %s: %+v", id, err) + } + + return nil +} diff --git a/azurerm/internal/services/sentinel/sentinel_data_connector_microsoft_cloud_app_security_test.go b/azurerm/internal/services/sentinel/sentinel_data_connector_microsoft_cloud_app_security_test.go new file mode 100644 index 000000000000..73d753f22d54 --- /dev/null +++ b/azurerm/internal/services/sentinel/sentinel_data_connector_microsoft_cloud_app_security_test.go @@ -0,0 +1,187 @@ +package sentinel_test + +import ( + "context" + "fmt" + "testing" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/sentinel" + + "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/sentinel/parse" + + "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/utils" +) + +type SentinelDataConnectorMicrosoftCloudAppSecurityResource struct{} + +func TestAccAzureRMSentinelDataConnectorMicrosoftCloudAppSecurity_basic(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_sentinel_data_connector_microsoft_cloud_app_security", "test") + r := SentinelDataConnectorMicrosoftCloudAppSecurityResource{} + + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccAzureRMSentinelDataConnectorMicrosoftCloudAppSecurity_complete(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_sentinel_data_connector_microsoft_cloud_app_security", "test") + r := SentinelDataConnectorMicrosoftCloudAppSecurityResource{} + + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.complete(data, true, true), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + }) +} + +func TestAccAzureRMSentinelDataConnectorMicrosoftCloudAppSecurity_update(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_sentinel_data_connector_microsoft_cloud_app_security", "test") + r := SentinelDataConnectorMicrosoftCloudAppSecurityResource{} + + 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, true, false), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.complete(data, false, true), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.ImportStep(), + { + Config: r.complete(data, true, true), + 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 TestAccAzureRMSentinelDataConnectorMicrosoftCloudAppSecurity_requiresImport(t *testing.T) { + data := acceptance.BuildTestData(t, "azurerm_sentinel_data_connector_microsoft_cloud_app_security", "test") + r := SentinelDataConnectorMicrosoftCloudAppSecurityResource{} + + data.ResourceTest(t, r, []resource.TestStep{ + { + Config: r.basic(data), + Check: resource.ComposeTestCheckFunc( + check.That(data.ResourceName).ExistsInAzure(r), + ), + }, + data.RequiresImportErrorStep(r.requiresImport), + }) +} + +func (r SentinelDataConnectorMicrosoftCloudAppSecurityResource) Exists(ctx context.Context, clients *clients.Client, state *terraform.InstanceState) (*bool, error) { + client := clients.Sentinel.DataConnectorsClient + + id, err := parse.DataConnectorID(state.ID) + if err != nil { + return nil, err + } + + if resp, err := client.Get(ctx, id.ResourceGroup, sentinel.OperationalInsightsResourceProvider, id.WorkspaceName, id.Name); err != nil { + if utils.ResponseWasNotFound(resp.Response) { + return utils.Bool(false), nil + } + return nil, fmt.Errorf("retrieving %s: %+v", id, err) + } + + return utils.Bool(true), nil +} + +func (r SentinelDataConnectorMicrosoftCloudAppSecurityResource) basic(data acceptance.TestData) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +resource "azurerm_sentinel_data_connector_microsoft_cloud_app_security" "test" { + name = "accTestDC-%d" + log_analytics_workspace_id = azurerm_log_analytics_workspace.test.id +} +`, template, data.RandomInteger) +} + +func (r SentinelDataConnectorMicrosoftCloudAppSecurityResource) complete(data acceptance.TestData, alertsEnabled, discoveryLogsEnabled bool) string { + template := r.template(data) + return fmt.Sprintf(` +%s + +data "azurerm_client_config" "test" {} + +resource "azurerm_sentinel_data_connector_microsoft_cloud_app_security" "test" { + name = "accTestDC-%d" + log_analytics_workspace_id = azurerm_log_analytics_workspace.test.id + tenant_id = data.azurerm_client_config.test.tenant_id + alerts_enabled = %t + discovery_logs_enabled = %t +} +`, template, data.RandomInteger, alertsEnabled, discoveryLogsEnabled) +} + +func (r SentinelDataConnectorMicrosoftCloudAppSecurityResource) requiresImport(data acceptance.TestData) string { + template := r.basic(data) + return fmt.Sprintf(` +%s + +resource "azurerm_sentinel_data_connector_microsoft_cloud_app_security" "import" { + name = azurerm_sentinel_data_connector_microsoft_cloud_app_security.test.name + log_analytics_workspace_id = azurerm_sentinel_data_connector_microsoft_cloud_app_security.test.log_analytics_workspace_id +} +`, template) +} + +func (r SentinelDataConnectorMicrosoftCloudAppSecurityResource) template(data acceptance.TestData) string { + return fmt.Sprintf(` +provider "azurerm" { + features {} +} + +resource "azurerm_resource_group" "test" { + name = "acctestRG-sentinel-%d" + location = "%s" +} + +resource "azurerm_log_analytics_workspace" "test" { + name = "acctestLAW-%d" + location = azurerm_resource_group.test.location + resource_group_name = azurerm_resource_group.test.name + sku = "PerGB2018" +} +`, data.RandomInteger, data.Locations.Primary, data.RandomInteger) +} diff --git a/website/docs/r/sentinel_data_connector_microsoft_cloud_app_security.html.markdown b/website/docs/r/sentinel_data_connector_microsoft_cloud_app_security.html.markdown new file mode 100644 index 000000000000..1269886f5325 --- /dev/null +++ b/website/docs/r/sentinel_data_connector_microsoft_cloud_app_security.html.markdown @@ -0,0 +1,75 @@ +--- +subcategory: "Sentinel" +layout: "azurerm" +page_title: "Azure Resource Manager: azurerm_sentinel_data_connector_microsoft_cloud_app_security" +description: |- + Manages a Microsoft Cloud App Security Data Connector. +--- + +# azurerm_sentinel_data_connector_microsoft_cloud_app_security + +Manages a Microsoft Cloud App Security Data Connector. + + !> **NOTE:** This resource requires that [Enterprise Mobility + Security E5](https://www.microsoft.com/en-us/microsoft-365/enterprise-mobility-security) is enabled on the tenant being connected to. + +## Example Usage + +```hcl +resource "azurerm_resource_group" "example" { + name = "example-rg" + location = "west europe" +} + +resource "azurerm_log_analytics_workspace" "example" { + name = "example-workspace" + location = azurerm_resource_group.example.location + resource_group_name = azurerm_resource_group.example.name + sku = "PerGB2018" +} + +resource "azurerm_sentinel_data_connector_microsoft_cloud_app_security" "example" { + name = "example" + log_analytics_workspace_id = azurerm_log_analytics_workspace.example.id +} +``` + +## Arguments Reference + +The following arguments are supported: + +* `log_analytics_workspace_id` - (Required) The ID of the Log Analytics Workspace that this Microsoft Cloud App Security Data Connector resides in. Changing this forces a new Microsoft Cloud App Security Data Connector to be created. + +* `name` - (Required) The name which should be used for this Microsoft Cloud App Security Data Connector. Changing this forces a new Microsoft Cloud App Security Data Connector to be created. + +--- + +* `alerts_enabled` - (Optional) Should the alerts be enabled? Defaults to `true`. + +* `discovery_logs_enabled` - (Optional) Should the Discovery Logs be enabled? Defaults to `true`. + +-> **NOTE**: One of either `alerts_enabled` or `discovery_logs_enabled` has to be specified. + +* `tenant_id` - (Optional) The ID of the Tenant that this Microsoft Cloud App Security Data Connector connects to. Changing this forces a new Microsoft Cloud App Security Data Connector to be created. + +## Attributes Reference + +In addition to the Arguments listed above - the following Attributes are exported: + +* `id` - The ID of the Microsoft Cloud App Security Data Connector. + +## 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 Microsoft Cloud App Security Data Connector. +* `read` - (Defaults to 5 minutes) Used when retrieving the Microsoft Cloud App Security Data Connector. +* `update` - (Defaults to 30 minutes) Used when updating the Microsoft Cloud App Security Data Connector. +* `delete` - (Defaults to 30 minutes) Used when deleting the Microsoft Cloud App Security Data Connector. + +## Import + +Microsoft Cloud App Security Data Connectors can be imported using the `resource id`, e.g. + +```shell +terraform import azurerm_sentinel_data_connector_microsoft_cloud_app_security.example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.OperationalInsights/workspaces/workspace1/providers/Microsoft.SecurityInsights/dataConnectors/dc1 +```