Create and manage dashboards by API

This document describes how you can create and manage custom dashboards and the widgets on those dashboards by using the Dashboard resource in the Cloud Monitoring API. The examples here illustrate how to manage your dashboards by using curl to invoke the API, and they show how to use the Google Cloud CLI. While you can also manage your custom dashboards through the Google Cloud console, the API provides you with a programmatic way of managing many dashboards at the same time.

The endpoint supports the following methods for managing and configuring dashboards:

You can invoke the API directly by using the curl utility or by using the Google Cloud CLI.

You can't retrieve, edit, or delete predefined dashboards.

Before you begin

When creating a dashboard, you must specify which components, or widgets, you want to display, and the layout for those widgets. You can also add permanent filters to your dashboard.

Dashboard layouts

Layouts define how the components of a dashboard are ordered. The API provides the following layouts:

  • GridLayout: divides the available space into vertical columns of equal width and arranges a set of widgets using a row-first strategy.

  • MosaicLayout: divides the available space into a grid. Each widget can occupy one or more grid blocks.

  • RowLayout: divides the available space into rows and arranges a set of widgets horizontally in each row.

  • ColumnLayout: divides the available space into vertical columns and arranges a set of widgets vertically in each column.

For example, the following shows the JSON representation of a dashboard in RowLayout with three Text widgets:

{
  "displayName": "Row-layout example",
  "rowLayout": {
    "rows": [
      {
        "widgets": [
          {
            "text": {
              "content": "Text Widget 1",
              "format": "RAW"
            }
          },
          {
            "text": {
              "content": "**Text Widget 2**",
              "format": "MARKDOWN"
            }
          },
          {
            "text": {
              "content": "_Text Widget 3_",
              "format": "MARKDOWN"
            }
          }
        ]
      }
    ]
  }
}

Dashboard widgets

A widget contains a single dashboard component and the configuration of how to present the component in the dashboard. A dashboard can have more than one widget. There are multiple types of Widget objects:

  • Chart and table widgets:

    • XyChart: displays data using X and Y axes. The following charts are instances of the XyChart widget:

    • Line charts

    • Bar charts

    • Stacked area charts

    • Heatmaps

    • Log Analytics charts

    • SLO widgets, but creating SLO charts by using the API is not supported.

    If you create a line chart, a stacked bar chart, or a stacked area chart, then you can specify that a metric refer to the left or right Y-axis. When multiple metrics are charted, you can use both Y-axes.

    • PieChart: displays the latest value of a metric, where each time series contributes one slice to the pie.

    • Scorecard: displays the latest value of a metric, and how this value relates to one or more thresholds.

    • TimeSeriesTable: displays the latest value of a metric. You can sort the table based on columns, filter the table, and add or remove columns from the display.

  • Alert chart and incident widgets:

    • AlertChart: displays a summary of a single-condition alerting policy. This widget displays data as a line chart, shows the threshold, and lists the number of open incidents.

    • IncidentList: displays a list of incidents. You can configure the widget to show incidents for specific alerting policies or for specific resource types.

  • Log and error widgets:

  • Text and organization widgets:

    To include these widgets on a dashboard, the dashboard must have a MosaicLayout.

    • CollapsibleGroup: displays a collection of widgets. You can collapse the view of a group.

    • SingleViewGroup: displays one widget in a collection of widgets. You can select which widget to display.

    • SectionHeader: creates a horizontal divider in your dashboard, and it creates an entry in the dashboard's table of contents.

    • Text: displays textual content, either as raw text or a Markdown string.

In addition to these objects, you can also add a blank placeholder to a dashboard.

For example, the following shows the JSON representation of an XyChart widget whose right Y-axis is configured:

{
  "displayName": "Demo dashboard",
  "gridLayout": {
    "widgets": [
      {
        "title": "Sample line chart",
        "xyChart": {
          "dataSets": [
            {
              "timeSeriesQuery": {
                "timeSeriesFilter": {
                  "filter": "metric.type=\"compute.googleapis.com/instance/cpu/utilization\" resource.type=\"gce_instance\"",
                  "aggregation": {
                    "perSeriesAligner": "ALIGN_MEAN",
                    "crossSeriesReducer": "REDUCE_MAX",
                    "groupByFields": [
                      "resource.label.zone"
                    ]
                  }
                },
                "unitOverride": "1"
              },
              "plotType": "LINE"
            }
          ],
          "timeshiftDuration": "0s",
          "yAxis": {
            "label": "y1Axis",
            "scale": "LINEAR"
          },
          "chartOptions": {
            "mode": "COLOR"
          }
        }
      }
    ]
  }
}

Dashboard filters

When you design a dashboard, you might identify multiple ways to view the data the dashboard displays. For example, when a dashboard displays metrics for virtual machine (VM) instances, you might want to view metrics for all VMs and you might want to view metrics for a specific zone. In this type of situation, we recommend that you create a permanent filter and set the default value of that filter to the most commonly used view. Permanent filters can apply to some or to all dashboard widgets. When viewing the dashboard with the Google Cloud console, the dashboard toolbar displays your permanent filters and a menu that you can use to temporarily change the filter's value.

There are multiple types of permanent dashboard filters:

  • Dashboard-wide filters apply to all widgets on a dashboard that support the filter label and that don't specify a value for that label.

    For example, when a chart includes the filter zone = us-central1-a, that chart ignores a dashboard filter based on the label zone. Similarly, charts without a zone label ignore dashboard filters with this label.

  • Template variables are named variables that apply to specific widgets. Each variable is for a specific label and value. You determine which widgets a template variable applies to.

All filter types are represented with the same data structure. For more information, see DashboardFilter.

For example, the following shows the partial JSON representation of a dashboard that defines a template variable and a dashboard-wide filter:

{
  "dashboardFilters": [
      {
        "filterType": "RESOURCE_LABEL",
        "labelKey": "instance_id",
        "stringValue": "3133577226154888113",
        "templateVariable": "iid"
      },
      {
        "filterType": "RESOURCE_LABEL",
        "labelKey": "zone"
      }
    ],
  "displayName": "Illustrate Template Variables",
  ...

In the displayed JSON, the first entry in the dashboardFilters structure is for a template variable with the name iid and a dashboard-wide filter with the label key zone. The template variable is an alias of the label instance_id.

The data structure for a template variable doesn't list the widgets to which it applies. Instead, you associate a widget with a template variable by modifying the widget's query to include a reference to the variable. When the widget is displayed on the dashboard, the value of the template variable is resolved.

See the following sections for how to annotate logs panels and charts:

Logs panel

To configure a logs panel to filter the display based on the value of a template variable, add the variable to the query pane. The following example illustrates a query that filters by the value of the template variable iid:

${iid}

Before the logs panel queries for logs to display, the template variable is resolved. In this example, if the value of the template variable is "12345", then ${iid} is replaced with the statement resource.labels."instance_id"="12345".

You can also include only the value of a template variable in a query. We recommend that you only use the value as part of a filter defined with a regular expression. For example, the following query uses a regular expression to match log entries that have a JSON payload that contains the described string:

jsonPayload.message=~"Connected to instance: ${iid.value}"

If you've configured a query for the logs panel and then select the button to open the Logs Explorer, the template variables are resolved before the Logs Explorer is opened.

The following table shows how the template variable is resolved by the logs panel:

Syntax Selected
Value
Resolved logs panel expression
${iid} 12345 resource.labels."instance_id"="12345"
${iid} * ""
${iid.value} 12345 12345
${iid.value} * .*

MQL-defined charts and tables

When you use Monitoring Query Language (MQL) to configure a chart, append a pipe and the variable to the query string:

fetch gce_instance
| metric 'compute.googleapis.com/instance/cpu/utilization'
| every 1m
| ${iid}

Before the chart queries for the time series to display, the template variable is resolved. In this example, if the value of the template variable is "12345", then ${iid} is replaced with the statement filter (resource.instance_id == '12345'). This filter matches time series that have a label named resource.instance_id, and only when the value of that label is exactly 12345.

When you want to filter time series by using a regular expression, then configure the query to include only the value of the template variable. To illustrate the syntax, the following shows how to use a regular expression to determine if the value of the label resource.instance_id contains the value of the template variable iid:

fetch gce_instance
| metric 'compute.googleapis.com/instance/cpu/utilization'
| filter resource.instance_id=~"${iid.value}"
| group_by 1m, [value_utilization_mean: mean(value.utilization)]
| every 1m

The following table shows how the template variable is resolved for MQL queries:

Syntax Selected
Value
Resolved MQL expression
${iid} 12345 filter (resource.instance_id == '12345')
${iid} * filter (true)
${iid.value} 12345 12345
${iid.value} * .*

PromQL-defined charts and tables

When you define a chart using PromQL, append to the query string the variable wrapped by braces:

compute_googleapis_com:instance_cpu_utilization {
    project_id="my-project", ${iid}
}

Before the chart queries for the time series to display, the template variable is resolved. In this example, if the value of the template variable is "12345", then ${iid} is replaced with the statement instance_id == '12345'.

Similar to MQL, when you define a widget with PromQL, the query can extract only the value of the template variable. We recommend that you only use the value as part of a filter defined with a regular expression. To illustrate the syntax, the following shows how to use a regular expression to determine if the value of the label instance_id contains the value of the template variable iid:

compute_googleapis_com:instance_cpu_utilization{
    instance_id=~"${iid.value}"
}

The following table shows how the template variable is resolved for PromQL queries:

Syntax Selected
Value
Resolved PromQL expression
${iid} 12345 instance_id == '12345'
${iid} * noop_filter=~".*"
${iid.value} 12345 12345
${iid.value} * .+

Charts and tables defined with time-series filters

When you define a chart using time-series filters, append the variable to the filter string:

"filter": "metric.type=\"compute.googleapis.com/instance/cpu/utilization\"
           resource.type=\"gce_instance\" ${iid}"

Unlike MQL- and PromQL-defined charts, you can't use the value of a template variable in a time-series filter.

The following table shows how the template variable is resolved:

Syntax Selected
Value
Resolved filter expression
${iid} 12345 resource.instance_id == "12345"
${iid} * Omitted
${iid.value} 12345 Not supported
${iid.value} * Not supported

Create a dashboard

To create a new custom dashboard, invoke the dashboards.create method and provide it with the layout and the widgets to display in the dashboard.

When you create a dashboard, the API automatically generates the dashboard_id. If you want to specify a custom dashboard_id, you can set the name field of a Dashboard object. The format of the name field looks like the following:

"name": "projects/${PROJECT_ID}/dashboards/${DASHBOARD_ID}"

Protocol

To create a new dashboard, send a POST request to the Dashboard endpoint.

curl -d @my-dashboard.json -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type: application/json' -X POST https://monitoring.googleapis.com/v1/projects/${PROJECT_ID}/dashboards

gcloud

To create a dashboard in a project, use the gcloud monitoring dashboards create command.

gcloud monitoring dashboards create --config-from-file=my-dashboard.json

For example, if you want to duplicate a dashboard, do the following:

  1. Complete the steps in Get dashboard to download the definition of the original dashboard.
  2. Edit the returned JSON to remove the etag and name fields, and change the value of the displayName field.
  3. Run the command to create the dashboard.

For more information, see the gcloud monitoring dashboards create reference.

The examples create a sample dashboard by using the my-dashboard.json file. You can manage your dashboard through the Google Cloud console.

For additional dashboard configurations, see Example dashboards and layouts.

Delete dashboards

To delete a custom dashboard, invoke the dashboards.delete method and specify the dashboard you want to delete.

Protocol

To delete a custom dashboard, send a DELETE request to the Dashboard endpoint, qualified with the ID of the dashboard to delete.

curl -H "Authorization: Bearer $ACCESS_TOKEN" -X DELETE https://monitoring.googleapis.com/v1/projects/${PROJECT_ID}/dashboards/${DASHBOARD_ID}

If successful, the method returns an empty response. Otherwise, it returns an error.

gcloud

To delete a custom dashboard, use gcloud monitoring dashboards delete, and specify the fully qualified ID of the dashboard to delete:

gcloud monitoring dashboards delete projects/${PROJECT_ID}/dashboards/${DASHBOARD_ID}

For more information, see the gcloud monitoring dashboards delete reference.

List dashboards

To list all custom dashboards that belong to a project, invoke the dashboards.list method and specify the project ID.

Protocol

To list all of a project's custom dashboards, send the project ID to the Dashboard endpoint.

curl -H "Authorization: Bearer $ACCESS_TOKEN" https://monitoring.googleapis.com/v1/projects/${PROJECT_ID}/dashboards

gcloud

To list all of a project's custom dashboards, use the gcloud monitoring dashboards list command:

gcloud monitoring dashboards list

For more information, see the gcloud monitoring dashboards list reference.

The examples return the custom dashboards associated with your project.

Paginate the list response

The dashboards.list method supports pagination, which lets you take the results one page at a time instead of all at once.

Protocol

For the initial page of the results list, specify the pageSize query parameter with request:

curl -H "Authorization: Bearer $ACCESS_TOKEN" https://monitoring.googleapis.com/v1/projects/${PROJECT_ID}/dashboards?page_size=1

The method returns the first page of the list and the nextPageToken. For example:

{
  "dashboards" : [
    {
       "displayName" : "Grid Layout Example",
       "gridLayout" : {
         "widgets" : [
            { ... },
            { ... },
            { ... },
          ]
       }
    }
  ]
},
"nextPageToken": "ChYqFDEyMzkzMzUwNzg0OTE1MDI4MjM3"

For each remaining page, you must include the corresponding nextPageToken in the request.

gcloud

To specify the number of resources per page, pass the --page-size flag with the command. For example:

gcloud monitoring dashboards list --page-size=1

Get dashboard

To get a specific custom dashboard for a project, invoke the dashboards.get method, qualified with the dashboard ID.

Protocol

To get a specific custom dashboard, send the dashboard ID to the Dashboard endpoint.

curl -H "Authorization: Bearer $ACCESS_TOKEN" https://monitoring.googleapis.com/v1/projects/${PROJECT_ID}/dashboards/${DASHBOARD_ID}

The method returns a response similar to the following example:

{
  "columnLayout": {
    "columns": [
      {
        "widgets": [
          {
            "text": {
              "content": "Text Widget 1",
              "format": "RAW"
            }
          },
          {
            "text": {
              "content": "**Text Widget 2**",
              "format": "MARKDOWN"
            }
          },
          {
            "text": {
              "content": "_Text Widget 3_",
              "format": "MARKDOWN"
            }
          }
        ]
      }
    ]
  },
  "displayName": "Column-layout example",
  "etag": "cb3070baf15de7c79d78761baac3a386",
  "name": "projects/730041941835/dashboards/e4cd063e-5414-4e07-9e1e-450d6d3a531d"
}

gcloud

To get a specific custom dashboard, use the gcloud monitoring dashboards describe command and specify the dashboard ID:

gcloud monitoring dashboards describe ${DASHBOARD_ID} --format=json

The command returns the requested dashboard:

{
  "columnLayout": {
    "columns": [
      {
        "widgets": [
          {
            "text": {
              "content": "Text Widget 1",
              "format": "RAW"
            }
          },
          {
            "text": {
              "content": "**Text Widget 2**",
              "format": "MARKDOWN"
            }
          },
          {
            "text": {
              "content": "_Text Widget 3_",
              "format": "MARKDOWN"
            }
          }
        ]
      }
    ]
  },
  "displayName": "Column-layout example",
  "etag": "cb3070baf15de7c79d78761baac3a386",
  "name": "projects/730041941835/dashboards/e4cd063e-5414-4e07-9e1e-450d6d3a531d"
}

For more information, see the gcloud monitoring dashboards describe reference.

Update dashboard

To update an existing custom dashboard, invoke the dashboards.patch method. To get the current etag value, you can invoke the dashboards.get method and find it in the response.

Protocol

To update a custom dashboard, send a PATCH request to the Dashboard endpoint and supply the revised Dashboard object and the etag value from the most recent dashboards.get response.

curl -d @my-updated-dashboard.json -H "Authorization: Bearer $ACCESS_TOKEN" -H 'Content-Type: application/json' -X PATCH https://monitoring.googleapis.com/v1/projects/${PROJECT_ID}/dashboards/${DASHBOARD_ID}

gcloud

To update a custom dashboard, use gcloud monitoring dashboards update, specify the ID of the dashboard to update, and provide the changes to the dashboard.

gcloud monitoring dashboards update ${DASHBOARD_ID} --config-from-file=my-updated-dashboard.json

For more information, see the gcloud monitoring dashboards update reference.

The examples update an existing custom dashboard using the my-updated-dashboard.json file and return a copy of the updated dashboard listing. The return data includes a new etag value.

What's next