admin
admin

Reputation: 65

Azure Monitor log analytics query using Terraform (display events)

I want to show the logs from the log analytics workspace using Terraform. I see in the doc these AZ CLI commands (Link):

Execute a simple query over past 3.5 days :

az monitor log-analytics query -w workspace-customId --analytics-query "AzureActivity | summarize count() by bin(timestamp, 1h)" -t P3DT12H

Execute a saved query in workspace :

QUERY=$(az monitor log-analytics workspace saved-search show -g resource-group --workspace-name workspace-name -n query-name --query query --output tsv)

az monitor log-analytics query -w workspace-customId --analytics-query "$QUERY"

Do you have an idea how we can do this using Terraform? (run query an az monitor)

Just show log entries and no need to create an alert.

Upvotes: 0

Views: 1645

Answers (1)

VenkateshDodda
VenkateshDodda

Reputation: 5506

You can use Provisioners in terraform in order to run the Azure monitor log analytics queries.

We have tested this in our local environment & it is working fine.

Below are the steps to Run a azure log analytics saved search query using terraform:

  1. You need to create a saved search query in your log analytics workspace.

For example, we have created a saved search query to pull the Heartbeat logs of a particular VM.

Heartbeat| where Computer contains '<NameofVirutalMachine>'|summarize count() by bin(TimeGenerated, 1h)
  1. Use the below cmdlet to save the search query in your log analytic workspace:
az monitor log-analytics workspace saved-search create -g <resourcegroupName>  --category <categoryofSavedSearch> --workspace-name <LAWorkspaceName> -n <Nameforquery> --display-name <displayName> -q "Heartbeat| where Computer contains '<NameofVM>'|summarize count() by bin(TimeGenerated, 1h)"

Refer this documentation for more information about the syntax for az monitor log-analytics workspace saved-search create cmdlet

  1. You need to install log-analytics extension in order to run the az monitor cmdlets in your local.

    az extension add --name

  2. Add the provisioner to your terraform script as shown below & run the script.

terraform {
  required_providers {
    azurerm = {
      source = "hashicorp/azurerm"
      version = "2.44.0"
    }
  }
}

provider "azurerm" {
  features {  }
}

resource "null_resource" "testexample" {

  provisioner "local-exec" {
    command = <<EOT
    $QUERY=(az monitor log-analytics workspace saved-search show -g <resourceGroupName> --workspace-name <workSpaceName> -n <NameofSavedSearch> --query query -o tsv)
    az monitor log-analytics query -w <GuidofLogAnalyticsWorkspace> --analytics-query $QUERY

    EOT
    interpreter = ["pwsh","-Command"]

}
}

Here is the sample Output for your reference:

enter image description here

Upvotes: 0

Related Questions