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:

  • XyChart: displays data using X and Y axes. Line charts, bar charts, stacked area charts, and heatmap charts created through the Google Cloud console are instances of this widget. 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.

    SLO charts are also instances of the XyChart widget, but creating SLO charts by using the API is not supported.

  • 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.

  • CollapsibleGroup: displays a collection of widgets. You can collapse the view of a group. To include these widgets on a dashboard, the dashboard must have a MosaicLayout.

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

  • LogsPanel: displays project-scoped log entries that are stored in the current Google Cloud project. You can configure the widget to show log entries stored in Google Cloud projects accessible through the current metrics scope.

  • 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.

  • 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:

{
  "category": "CUSTOM",
  "dashboardFilters": [
    {
      "filterType": "RESOURCE_LABEL",
      "labelKey": "zone",
      "stringValue": "us-central1-b",
      "templateVariable": "my_zone_temp_var"
    },
    {
      "filterType": "RESOURCE_LABEL",
      "labelKey": "project_id",
      "stringValue": "my-project-id",
      "templateVariable": ""
    }
  ],
  "displayName": "Illustrate Template Variables",
  ...

In the displayed JSON, the first entry in the dashboardFilters structure is for a template variable with the name my_zone_temp_var. The second entry is for a dashboard-wide filter. For these filters, which apply to all dashboard widgets, the value of the templateVariable field is set to a zero-length string, "".

The data structure for a template variable doesn't list the widgets to which it applies. Instead, when you associate a widget with a template variable, the widget's query is modified to include a reference to the variable. When you use Monitoring Query Language (MQL) to configure a chart, append a pipe and the variable to the query string:


"timeSeriesQueryLanguage": "fetch gce_instance::compute.googleapis.com/instance/cpu/utilization\n|
           every 1m\n| ${my_zone_temp_var}\n"

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

"prometheusQuery" :
  "compute_googleapis_com:instance_cpu_utilization {project_id=\"my-project\", ${my_zone_temp_var}}\n"

The previous example illustrates how to filter a PromQL-defined widget to only display the time series that are in the Google Cloud project my-project and that match a template variable.

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\" ${my_zone_temp_var}"

The following JSON illustrates show the query strings in the context of the full definition of the chart:

{
  ...
  "displayName": "Illustrate Template Variables",
  "mosaicLayout": {
    "columns": 12,
    "tiles": [
      {
        "height": 4,
        "widget": {
          "title": "MQL",
          "xyChart": {
            "chartOptions": {
              "mode": "COLOR"
            },
            "dataSets": [
              {
                "plotType": "LINE",
                "targetAxis": "Y1",
                "timeSeriesQuery": {
                  "timeSeriesQueryLanguage": "fetch gce_instance::compute.googleapis.com/instance/cpu/utilization\n| every 1m\n| ${my_zone_temp_var} \n"
                }
              }
            ],
            "timeshiftDuration": "0s",
            "yAxis": {
              "label": "y1Axis",
              "scale": "LINEAR"
            }
          }
        },
        "width": 6,
        "xPos": 0,
        "yPos": 0
      },
      {
        "height": 4,
        "widget": {
          "title": "LTS",
          "xyChart": {
            "chartOptions": {
              "mode": "COLOR"
            },
            "dataSets": [
              {
                "minAlignmentPeriod": "60s",
                "plotType": "LINE",
                "targetAxis": "Y1",
                "timeSeriesQuery": {
                  "apiSource": "DEFAULT_CLOUD",
                  "timeSeriesFilter": {
                    "aggregation": {
                      "alignmentPeriod": "60s",
                      "crossSeriesReducer": "REDUCE_NONE",
                      "perSeriesAligner": "ALIGN_MEAN"
                    },
                    "filter": "metric.type=\"compute.googleapis.com/instance/cpu/utilization\" resource.type=\"gce_instance\" ${my_zone_temp_var}"
                  }
                }
              }
            ],
            "timeshiftDuration": "0s",
            "yAxis": {
              "label": "y1Axis",
              "scale": "LINEAR"
            }
          }
        },
        "width": 6,
        "xPos": 6,
        "yPos": 0
      }
    ]
  }
}

Specify the data to display

Any widget that displays data retrieved from a time series has a TimeSeriesQuery object embedded in it. This object specifies the time-series data to be used in the widget.

You can specify the time-series data to display as follows:

If you created your dashboard widgets through the Google Cloud console, then you are already familiar with metrics and time series.

For information about metrics and time series, see Metrics, time series, and resources.

You might also find the following guides helpful:

While these guides are written for creating dashboards by using the Google Cloud console, the concepts also apply to creating widgets by using the Cloud Monitoring API.

Setup for examples

This section describes the conventions and setup used for invoking the Cloud Monitoring API by using the curl tool. The examples on this document access the API by using the curl tool to send HTTP requests to REST endpoints. To set the variables used in the example invocations, use the following information.

Authentication

  1. Create an environment variable to hold the ID of your Google Cloud project. These examples use PROJECT_ID:

    PROJECT_ID=a-gcp-project-12345
    
  2. Authenticate to Google Cloud CLI:

    gcloud auth login
    
  3. Optionally, you can avoid having to specify your project ID with each command by setting it as the default by using gcloud CLI:

    gcloud config set project ${PROJECT_ID}
    
  4. Create an authorization token and capture it in an environment variable. These examples call the variable ACCESS_TOKEN:

    ACCESS_TOKEN=`gcloud auth print-access-token`
    

    You have to periodically refresh the access token. If commands that worked suddenly report that you're unauthenticated, re-issue this command.

  5. To verify that you got an access token, echo the ACCESS_TOKEN variable:

    echo ${ACCESS_TOKEN}
    ya29.ImW8Bz56I04cN4qj6LF....
    
  6. Create an environment variable to hold the ID of your dashboard. These examples use the variable DASHBOARD_ID.

Invoke curl

Each curl invocation includes a set of arguments, followed by the URL of a resource. The common arguments include values specified by the PROJECT_ID, DASHBOARD_ID and ACCESS_TOKEN environment variables. You might also have to specify other arguments, for example, to specify the type of the HTTP request (for instance, -X DELETE).

Each curl invocation has this general structure:

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

For example, to list all the custom dashboards in your project, issue the following request:

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

The following illustrates the response of this command for one Google Cloud project:

{
  "dashboards": [
    {
      "name": "projects/123456789000/dashboards/c2ab1f1c-b8b9-1234-9c48-c7745802b659",
      "displayName": "Grid-layout example",
      "etag": "76a95cc500a7c7d6b3799709c13afe91",
      "gridLayout": {
        "widgets": [
          {
            "text": {
              "content": "Text Widget 1",
              "format": "RAW"
            }
          },
          {
            "text": {
              "content": "**Text Widget 2**",
              "format": "MARKDOWN"
            }
          },
          {
            "text": {
              "content": "_Text Widget 3_",
              "format": "MARKDOWN"
            }
          }
        ]
      }
    },
    {
      "name": "projects/123456789000/dashboards/cae85db7-6920-4e67-a45c-97a94c0e2679",
      "displayName": "Row-layout example",
      "etag": "a600be01afe0b37762cd7a9b92fc3e7e",
      "rowLayout": {
        "rows": [
          {
            "widgets": [
              {
                "text": {
                  "content": "Text Widget 1",
                  "format": "RAW"
                }
              },
              {
                "text": {
                  "content": "**Text Widget 2**",
                  "format": "MARKDOWN"
                }
              },
              {
                "text": {
                  "content": "_Text Widget 3_",
                  "format": "MARKDOWN"
                }
              }
            ]
          }
        ]
      }
    }
  ]
}

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 now manage your dashboard through the Google Cloud console.

For additional dashboard configurations, see Sample 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