Thursday, April 16, 2020

Extracting Prometheus Metric Names from Grafana

Had the need to extract all our Prometheus metric names out of our Grafana dashboards to determine what was in use and what was not. The PowerShell script below will use the Grafana API to pull back all the dashboards within a specific folder and with a partial name, enumerate the dashboards, extract the expressions, then extract the metric name(s):

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$boards = Invoke-WebRequest "https://[url]/api/search?query=hyper&folderIds=2308" -Method Get | Select -ExpandProperty Content | ConvertFrom-Json

foreach($board in $boards){
    
    $boardinfo = Invoke-WebRequest ("https://[url]/api/dashboards/uid/{0}" -f $board.uid) -Method Get | Select -ExpandProperty Content | ConvertFrom-Json

    $graphs  = @()
    $graphs  = ($boardinfo.dashboard.panels | Where-Object type -eq row).panels
    $graphs += ($boardinfo.dashboard.panels | Where-Object type -notmatch "row")

    $result = Select-String "(?<=\()(\w*)(?=\{)" -input $graphs.targets.expr -AllMatches | Foreach-Object {$_.matches} | Sort-Object Value | Select-Object -ExpandProperty Value -Unique

    [PSCustomObject]@{
        Title = $board.title
        Count = $result.count
        Metrics = $result        
    }

}

No comments:

Post a Comment