Powershell to ElasticSearch to find ElastAlert

I recently worked on an interesting project where I needed to use a powershell script to query ElasticSearch to find a document that was inserted via ElastAlert.

The purpose of this exercise was to determine whether or not a service had been marked down recently, which would determine whether an operation ran that might take down the passive node in an active/passive HA configuration.

The following script snippet will search ElasticSearch for any entries in the past 1 week with the specified rule name with more than 0 hits and matches.

    $Rule_Name = "Rule name here"

    $Es_Endpoint = "elastic_search_dns_endpoint"
    $Es_Index    = "elastalert_writeback_index"
    $Es_Type     = "elastalert_status"

    $Body = @{
      "query" = @{
        "bool" = @{
          "filter" = @(
            @{  
              "term" = @{
                "rule_name" = $Rule_Name;
              }   
            };  
            @{  
              "range" = @{
                "hits" = @{
                  "gt" = 0 
                }   
              }   
            };
            @{  
              "range" = @{
                "matches" = @{
                  "gt" = 0 
                }   
              }   
            };    
            @{  
              "range" = @{
                "@timestamp" = @{
                  "gt" = "now-1w"
                }   
              }   
            }   
          )   
        }   
      }   
    }   

    $Json_Body = $Body | ConvertTo-Json -Depth 10

    # Un-comment as needed for troubleshooting
    # Write-Output $Json_Body

    $Response = Invoke-RestMethod -Method POST -URI https://$Es_Endpoint/$Es_Index/_search  -Body $Json_Body -ContentType 'application/json'

    # Un-comment these as needed for troubleshooting
    # Write-Output ($Response | Format-List | Out-String)
    # Write-Output ($Response.hits.total | Out-String)

    if ($Response.hits.total -gt 0) {
      $Restore = 0 
    }   

Once the query returns, the script checks to see if the number of hits exceeds 0, which means at least one entry satisfied the query parameters. Based on this response, action can then be taken on the HA service in question.


Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *