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_log_analytics_datasource_windows_event #6321

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,34 @@
package loganalytics

import (
"fmt"

"github.com/Azure/azure-sdk-for-go/services/preview/operationalinsights/mgmt/2015-11-01-preview/operationalinsights"
"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/loganalytics/parse"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/timeouts"
)

func importLogAnalyticsDataSource(kind operationalinsights.DataSourceKind) func(d *schema.ResourceData, meta interface{}) (data []*schema.ResourceData, err error) {
return func(d *schema.ResourceData, meta interface{}) (data []*schema.ResourceData, err error) {
id, err := parse.LogAnalyticsDataSourceID(d.Id())
if err != nil {
return nil, err
}

client := meta.(*clients.Client).LogAnalytics.DataSourcesClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

resp, err := client.Get(ctx, id.ResourceGroup, id.Workspace, id.Name)
if err != nil {
return nil, fmt.Errorf("failed to retrieve Log Analytics Data Source %q (Resource Group %q / Workspace: %q): %+v", id.Name, id.ResourceGroup, id.Workspace, err)
}

if resp.Kind != kind {
return nil, fmt.Errorf(`Log Analytics Data Source "kind" mismatch, expected "%s", got "%s"`, kind, resp.Kind)
}
return []*schema.ResourceData{d}, nil
}
}
1 change: 1 addition & 0 deletions azurerm/internal/services/loganalytics/registration.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func (r Registration) SupportedResources() map[string]*schema.Resource {
"azurerm_log_analytics_linked_service": resourceArmLogAnalyticsLinkedService(),
"azurerm_log_analytics_solution": resourceArmLogAnalyticsSolution(),
"azurerm_log_analytics_workspace": resourceArmLogAnalyticsWorkspace(),
"azurerm_log_analytics_datasource_windows_event": resourceArmLogAnalyticsDataSourceWindowsEvent(),
"azurerm_log_analytics_datasource_windows_performance_counter": resourceArmLogAnalyticsDataSourceWindowsPerformanceCounter(),
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
package loganalytics

import (
"encoding/json"
"fmt"
"log"
"time"

"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/set"

"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/tf/state"

"github.com/Azure/azure-sdk-for-go/services/preview/operationalinsights/mgmt/2015-11-01-preview/operationalinsights"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/loganalytics/parse"

"github.com/hashicorp/terraform-plugin-sdk/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/helper/structure"
"github.com/hashicorp/terraform-plugin-sdk/helper/validation"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/suppress"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/tf"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/clients"
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 resourceArmLogAnalyticsDataSourceWindowsEvent() *schema.Resource {
return &schema.Resource{
Create: resourceArmLogAnalyticsDataSourceWindowsEventCreateUpdate,
Read: resourceArmLogAnalyticsDataSourceWindowsEventRead,
Update: resourceArmLogAnalyticsDataSourceWindowsEventCreateUpdate,
Delete: resourceArmLogAnalyticsDataSourceWindowsEventDelete,

Importer: azSchema.ValidateResourceIDPriorToImportThen(func(id string) error {
_, err := parse.LogAnalyticsDataSourceID(id)
return err
}, importLogAnalyticsDataSource(operationalinsights.WindowsEvent)),

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

"resource_group_name": azure.SchemaResourceGroupName(),

"workspace_name": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
DiffSuppressFunc: suppress.CaseDifference,
ValidateFunc: ValidateAzureRmLogAnalyticsWorkspaceName,
},

"event_log_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringIsNotEmpty,
},

"event_types": {
Type: schema.TypeSet,
Required: true,
MinItems: 1,
Set: set.HashStringIgnoreCase,
Elem: &schema.Schema{
Type: schema.TypeString,
// API backend accepts event_types case-insensitively
ValidateFunc: validation.StringInSlice([]string{"error", "warning", "information"}, true),
StateFunc: state.IgnoreCase,
DiffSuppressFunc: suppress.CaseDifference,
},
},
},
}
}

type dataSourceWindowsEvent struct {
EventLogName string `json:"eventLogName"`
EventTypes []dataSourceWindowsEventEventType `json:"eventTypes"`
}

type dataSourceWindowsEventEventType struct {
EventType string `json:"eventType"`
}

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

name := d.Get("name").(string)
resourceGroup := d.Get("resource_group_name").(string)
workspaceName := d.Get("workspace_name").(string)

if d.IsNewResource() {
resp, err := client.Get(ctx, resourceGroup, workspaceName, name)
if err != nil {
if !utils.ResponseWasNotFound(resp.Response) {
return fmt.Errorf("failed to check for existing Log Analytics Data Source Windows Event %q (Resource Group %q / Workspace: %q): %+v", name, resourceGroup, workspaceName, err)
}
}

if !utils.ResponseWasNotFound(resp.Response) {
return tf.ImportAsExistsError("azurerm_log_analytics_datasource_windows_event", *resp.ID)
}
}

params := operationalinsights.DataSource{
Kind: operationalinsights.WindowsEvent,
Properties: &dataSourceWindowsEvent{
EventLogName: d.Get("event_log_name").(string),
EventTypes: expandLogAnalyticsDataSourceWindowsEventEventType(d.Get("event_types").(*schema.Set).List()),
},
}

if _, err := client.CreateOrUpdate(ctx, resourceGroup, workspaceName, name, params); err != nil {
return fmt.Errorf("failed to create Log Analytics DataSource Windows Event %q (Resource Group %q / Workspace: %q): %+v", name, resourceGroup, workspaceName, err)
}

resp, err := client.Get(ctx, resourceGroup, workspaceName, name)
if err != nil {
return fmt.Errorf("Error retrieving Log Analytics Data Source Windows Event %q (Resource Group %q / Workspace: %q): %+v", name, resourceGroup, workspaceName, err)
}
if resp.ID == nil || *resp.ID == "" {
return fmt.Errorf("Cannot read Log Analytics Data Source Windows Event %q (Resource Group %q) ID", name, resourceGroup)
}
d.SetId(*resp.ID)

return resourceArmLogAnalyticsDataSourceWindowsEventRead(d, meta)
}

func resourceArmLogAnalyticsDataSourceWindowsEventRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*clients.Client).LogAnalytics.DataSourcesClient
ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
defer cancel()

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

resp, err := client.Get(ctx, id.ResourceGroup, id.Workspace, id.Name)
if err != nil {
if utils.ResponseWasNotFound(resp.Response) {
log.Printf("[DEBUG] Log Analytics Data Source Windows Event %q was not found in Resource Group %q in Workspace %q - removing from state!", id.Name, id.ResourceGroup, id.Workspace)
d.SetId("")
return nil
}

return fmt.Errorf("failed to retrieve Log Analytics Data Source Windows Event %q (Resource Group %q / Workspace: %q): %+v", id.Name, id.ResourceGroup, id.Workspace, err)
}

d.Set("name", resp.Name)
d.Set("resource_group_name", id.ResourceGroup)
d.Set("workspace_name", id.Workspace)
if props := resp.Properties; props != nil {
propStr, err := structure.FlattenJsonToString(props.(map[string]interface{}))
if err != nil {
return fmt.Errorf("failed to flatten properties map to json for Log Analytics DataSource Windows Event %q (Resource Group %q / Workspace: %q): %+v", id.Name, id.ResourceGroup, id.Workspace, err)
}

prop := dataSourceWindowsEvent{}
if err := json.Unmarshal([]byte(propStr), &prop); err != nil {
return fmt.Errorf("failed to decode properties json for Log Analytics DataSource Windows Event %q (Resource Group %q / Workspace: %q): %+v", id.Name, id.ResourceGroup, id.Workspace, err)
}

d.Set("event_log_name", prop.EventLogName)
d.Set("event_types", flattenLogAnalyticsDataSourceWindowsEventEventType(prop.EventTypes))
}

return nil
}

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

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

if _, err := client.Delete(ctx, id.ResourceGroup, id.Workspace, id.Name); err != nil {
return fmt.Errorf("failed to delete Log Analytics DataSource Windows Event %q (Resource Group %q / Workspace: %q): %+v", id.Name, id.ResourceGroup, id.Workspace, err)
}

return nil
}

func flattenLogAnalyticsDataSourceWindowsEventEventType(eventTypes []dataSourceWindowsEventEventType) []interface{} {
output := make([]interface{}, 0)
for _, e := range eventTypes {
output = append(output, e.EventType)
}
return output
}

func expandLogAnalyticsDataSourceWindowsEventEventType(input []interface{}) []dataSourceWindowsEventEventType {
output := []dataSourceWindowsEventEventType{}
for _, eventType := range input {
output = append(output, dataSourceWindowsEventEventType{eventType.(string)})
}
return output
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ func resourceArmLogAnalyticsDataSourceWindowsPerformanceCounter() *schema.Resour
Update: resourceArmLogAnalyticsDataSourceWindowsPerformanceCounterCreateUpdate,
Delete: resourceArmLogAnalyticsDataSourceWindowsPerformanceCounterDelete,

Importer: azSchema.ValidateResourceIDPriorToImport(func(id string) error {
Importer: azSchema.ValidateResourceIDPriorToImportThen(func(id string) error {
_, err := parse.LogAnalyticsDataSourceID(id)
return err
}),
}, importLogAnalyticsDataSource(operationalinsights.WindowsPerformanceCounter)),

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(30 * time.Minute),
Expand Down
Loading