Cloud Monitoring has no per-certificate expiry metric for Certificate Manager, so a GCP certificate expiry alert that looks for one never fires. The April version of this guide shipped exactly that: a filter on certificatemanager.googleapis.com/certificate/expiry_seconds, which the API rejects with a 400 the moment you apply it. The alert you can trust comes from an HTTPS uptime check, because it reads the certificate the load balancer actually serves and reports the days left per hostname.
This rebuild puts that uptime metric, the Certificate Manager histogram and an audit-log metric into Terraform alert policies with a Pub/Sub channel. Then it fires a real incident against a host serving a five-day certificate and times each step, so you see the alert latency, the payload your bot receives and the two errors the first apply hits. Every command below ran in a live GCP project in November 2026 with the Google provider 8.11.0.
Pick the metric that reports cert expiry
Use monitoring.googleapis.com/uptime_check/time_until_ssl_cert_expires for paging. It’s a per-check gauge in days, written by every checker region, and it carries the check_id and host labels you need to say which certificate is about to expire. Certificate Manager’s own project/v2/certificate_expiration is a project-wide histogram with no certificate label, sampled once an hour. It can tell you that something expires soon, but not what.
Before you write any policy, list what your project really exposes, because metric names you remember from older docs may be gone. Set two shell variables first. The Monitoring API calls in this guide reuse them, and the token expires after an hour, so rerun the second line if a later call returns 401:
export PROJECT_ID="your-gcp-project-id"
export TOKEN="$(gcloud auth print-access-token)"
Then ask the Monitoring API for every metric descriptor under the Certificate Manager prefix:
curl -s -G -H "Authorization: Bearer ${TOKEN}" \
"https://monitoring.googleapis.com/v3/projects/${PROJECT_ID}/metricDescriptors" \
--data-urlencode 'filter=metric.type = starts_with("certificatemanager.googleapis.com")' \
| jq -r '.metricDescriptors[] | [.type, .metricKind, .valueType, .launchStage] | @tsv'
Five metrics come back, and none of them is scoped to a single certificate. The two GA ones are gauges that count certificates and map entries. The other three (the expiry histogram, the active-certificate count and the observance event count) are still BETA:

The table below is what each metric reported in the lab, which is the part the docs leave you to discover. The 72-hour rule matters if you test with short-lived certificates: a two-day certificate we uploaded never appeared in the histogram at all.
| Property | Uptime check time_until_ssl_cert_expires | Certificate Manager project/v2/certificate_expiration |
|---|---|---|
| Value | Days left, as a double (4.998 for a fresh five-day cert) | Distribution of seconds left, buckets at 0, 1, 7, 30 and 180 days |
| Identifies the cert | Yes: check_id, checker_location, host | No labels at all |
| Fresh data | First point about 100 seconds after the check was created, then one per region each check period (60 seconds here) | Measured every 3600 seconds, last value repeated in between |
| What it sees | The cert the endpoint serves, wherever it was issued | Certificates in the project with a lifetime over 72 hours (the docs do not limit it to Certificate Manager) |
| Launch stage | GA | BETA |
The two are complementary rather than redundant. The uptime metric catches the case where Certificate Manager holds a healthy renewed certificate but the load balancer still serves the old one, which is the incident class a pure API check misses. The histogram catches certificates nobody added an uptime check for. If you can only afford one, page on the uptime metric and treat the histogram as a weekly hygiene signal.
Error: “The filter contains unknown resource type: certificatemanager.googleapis.com/Certificate”
This is what the old policy from this series returns on the current provider. Neither the certificatemanager.googleapis.com/Certificate resource type nor the certificate/expiry_seconds metric exists, so the API refuses the policy before anything is created:

If an older module in your repo still carries that filter, it has never alerted, because the policy was never created. Check with gcloud monitoring policies list before you assume you are covered. Then replace it with the uptime condition below, or with resource.type = "certificatemanager.googleapis.com/Project" if you want the histogram.
Build the alert policies with Terraform
One main.tf holds everything: a Pub/Sub topic and subscription, a notification channel, an HTTPS uptime check, uptime policies at 30 and 7 days, the histogram policy and a log-based metric with its policy. Pub/Sub is the channel here because it hands a bot the full incident as JSON and costs nothing to test. Email or PagerDuty channels slot into notification_channels the same way, so you can add yours later without touching the conditions.
Enable the four APIs the module touches. The command is safe to rerun on a project where they are already on:
gcloud services enable monitoring.googleapis.com certificatemanager.googleapis.com \
pubsub.googleapis.com logging.googleapis.com
The provider reads the project from the environment, so point it at the same project the gcloud commands use:
export CLOUDSDK_CORE_PROJECT="${PROJECT_ID}"
mkdir -p cert-monitoring && cd cert-monitoring
vim main.tf
Start the file with the provider pin, the inputs and the notification path. The depends_on on the IAM binding is there because of the first error further down:
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "~> 8.11"
}
}
}
provider "google" {
default_labels = {
team = "platform"
}
}
variable "monitored_host" {
type = string
}
variable "runbook_url_base" {
type = string
default = "https://git.example.com/platform/runbooks/-/blob/main"
}
data "google_project" "this" {}
resource "google_pubsub_topic" "cert_alerts" {
name = "cert-alerts"
}
resource "google_pubsub_subscription" "cert_alerts_pull" {
name = "cert-alerts-pull"
topic = google_pubsub_topic.cert_alerts.id
}
resource "google_pubsub_topic_iam_member" "monitoring_publisher" {
topic = google_pubsub_topic.cert_alerts.id
role = "roles/pubsub.publisher"
member = "serviceAccount:service-${data.google_project.this.number}@gcp-sa-monitoring-notification.iam.gserviceaccount.com"
# the notification service agent only exists after the project's first channel
depends_on = [google_monitoring_notification_channel.pubsub]
}
resource "google_monitoring_notification_channel" "pubsub" {
display_name = "cert-alerts Pub/Sub"
type = "pubsub"
labels = {
topic = google_pubsub_topic.cert_alerts.id
}
}
Next in the same file come the uptime check and the two expiry policies built on it. A few choices in this block are deliberate:
validate_ssl = false, because the metric is still written and the lab host serves a self-signed certREDUCE_MINgrouped by host, so three regions open one incident, not threeduration = "0s", since days-left only ever falls and waiting adds nothing- a
documentationblock that puts the runbook link in every notification
resource "google_monitoring_uptime_check_config" "https" {
display_name = "HTTPS ${var.monitored_host}"
timeout = "10s"
period = "60s"
http_check {
path = "/"
port = 443
use_ssl = true
validate_ssl = false
}
monitored_resource {
type = "uptime_url"
labels = {
host = var.monitored_host
project_id = data.google_project.this.project_id
}
}
selected_regions = ["USA_OREGON", "EUROPE", "ASIA_PACIFIC"]
}
resource "google_monitoring_alert_policy" "uptime_cert_expiry" {
for_each = { "30d" = 30, "7d" = 7 }
display_name = "TLS cert on ${var.monitored_host} expires in < ${each.key}"
combiner = "OR"
severity = each.value <= 7 ? "CRITICAL" : "WARNING"
conditions {
display_name = "time_until_ssl_cert_expires < ${each.value} days"
condition_threshold {
filter = "resource.type = \"uptime_url\" AND metric.type = \"monitoring.googleapis.com/uptime_check/time_until_ssl_cert_expires\" AND metric.label.check_id = \"${google_monitoring_uptime_check_config.https.uptime_check_id}\""
comparison = "COMPARISON_LT"
threshold_value = each.value
duration = "0s"
aggregations {
alignment_period = "300s"
per_series_aligner = "ALIGN_MIN"
cross_series_reducer = "REDUCE_MIN"
group_by_fields = ["resource.label.host"]
}
trigger {
count = 1
}
}
}
notification_channels = [google_monitoring_notification_channel.pubsub.id]
documentation {
subject = "TLS cert on $${resource.label.host} expires in < ${each.key}"
content = "Runbook: ${var.runbook_url_base}/cert-rotation.md"
mime_type = "text/markdown"
}
}
Turn validate_ssl on in production unless your certificates rely on the AIA extension, which the uptime docs say validation does not support. With validation on, an expired or mismatched certificate also fails the check itself. You can alert on that with check_passed, which gives you a second, louder signal on the day a certificate actually lapses.
The histogram policy follows. A distribution cannot take ALIGN_MIN, so it aligns on the 5th percentile instead. The alignment period matches the one-hour sampling, so each window holds one real measurement rather than a stretch of repeated ones:
resource "google_monitoring_alert_policy" "certmanager_expiry" {
display_name = "Certificate Manager: a cert expires in < 30d"
combiner = "OR"
severity = "WARNING"
conditions {
display_name = "5th percentile of certificate_expiration < 30 days"
condition_threshold {
filter = "resource.type = \"certificatemanager.googleapis.com/Project\" AND metric.type = \"certificatemanager.googleapis.com/project/v2/certificate_expiration\""
comparison = "COMPARISON_LT"
threshold_value = 30 * 24 * 60 * 60
duration = "0s"
aggregations {
alignment_period = "3600s"
per_series_aligner = "ALIGN_PERCENTILE_05"
}
}
}
notification_channels = [google_monitoring_notification_channel.pubsub.id]
documentation {
content = "Runbook: ${var.runbook_url_base}/cert-rotation.md. The metric has no per-certificate label: list certs with gcloud certificate-manager certificates list and compare expireTime."
mime_type = "text/markdown"
}
}
The last block is the audit-log metric and its policy, which get their own section below:
resource "google_logging_metric" "certmgr_changes" {
name = "certmgr/cert_changes"
filter = "resource.type=\"audited_resource\" AND protoPayload.serviceName=\"certificatemanager.googleapis.com\" AND protoPayload.methodName=~\"\\.(Update|Delete)(Certificate|CertificateMap|CertificateMapEntry|DnsAuthorization)$\" AND operation.first=true"
metric_descriptor {
metric_kind = "DELTA"
value_type = "INT64"
labels {
key = "method"
value_type = "STRING"
}
}
label_extractors = {
"method" = "REGEXP_EXTRACT(protoPayload.methodName, \"CertificateManager\\\\.(\\\\w+)$\")"
}
}
resource "google_monitoring_alert_policy" "certmgr_changes" {
display_name = "Certificate Manager: cert, map or entry changed"
combiner = "OR"
severity = "WARNING"
conditions {
display_name = "certmgr/cert_changes > 0"
condition_threshold {
filter = "resource.type = \"audited_resource\" AND metric.type = \"logging.googleapis.com/user/${google_logging_metric.certmgr_changes.name}\""
comparison = "COMPARISON_GT"
threshold_value = 0
duration = "0s"
aggregations {
alignment_period = "60s"
per_series_aligner = "ALIGN_COUNT"
}
}
}
alert_strategy {
auto_close = "1800s"
}
notification_channels = [google_monitoring_notification_channel.pubsub.id]
documentation {
content = "Runbook: ${var.runbook_url_base}/cert-change-review.md"
mime_type = "text/markdown"
}
}
Save the file, then initialise it and apply it against the host you want to watch. We used a test VM’s address, written here as 203.0.113.10; if you are building the lab too, create that VM with the commands at the start of the next section before you apply. In production, use the hostname your clients connect to, so the check sees the same certificate they do:
tofu init
tofu apply -auto-approve -var monitored_host=203.0.113.10
We ran it with OpenTofu, which installed provider 8.11.0 from the ~> 8.11 pin. Plain terraform init and terraform apply take the same file unchanged. The first apply ran for 15 seconds and stopped on the IAM error below; the retry and the log-based metric added later were separate, smaller applies.
Error: “Service account service-PROJECT_NUMBER@gcp-sa-monitoring-notification.iam.gserviceaccount.com does not exist”
On a project that has never had a Pub/Sub notification channel, the first apply fails on the IAM binding. Monitoring creates its notification service agent only when the first Pub/Sub channel is added, and without an ordering hint Terraform creates the binding and the channel in parallel:

A second apply succeeds because the channel now exists, but a pipeline should not depend on a retry. The depends_on = [google_monitoring_notification_channel.pubsub] line in the file above fixes the order, and a plan against the lab after adding it reported no changes.
Trigger a real cert-expiry alert
To see the alert fire without waiting a month, serve a certificate that is already inside the threshold. You want to watch it fire once before you trust it, because a policy that applies cleanly can still never match. Our test host was a Debian 12 e2-micro with TCP 443 open to the uptime checkers:
gcloud compute instances create certlab-web --zone=europe-west1-b \
--machine-type=e2-micro --image-family=debian-12 --image-project=debian-cloud \
--tags=certlab-https
gcloud compute firewall-rules create certlab-allow-https --network=default \
--allow=tcp:443 --target-tags=certlab-https
The VM’s external address is the monitored_host value for the apply. Read it, then log in (the SSH step relies on the default network’s default-allow-ssh rule):
gcloud compute instances describe certlab-web --zone=europe-west1-b \
--format='get(networkInterfaces[0].accessConfigs[0].natIP)'
gcloud compute ssh certlab-web --zone=europe-west1-b
On the VM, install nginx and give it a TLS server block that reads the certificate from /etc/nginx/tls:
sudo apt-get update && sudo apt-get install -y nginx
sudo vim /etc/nginx/sites-enabled/tls.conf
One server block is enough, because the check only needs a handshake and a 200:
server {
listen 443 ssl;
ssl_certificate /etc/nginx/tls/lab.crt;
ssl_certificate_key /etc/nginx/tls/lab.key;
location / { return 200 "ok\n"; }
}
Then generate a five-day self-signed certificate where that block expects it and restart nginx:
sudo mkdir -p /etc/nginx/tls
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 5 \
-subj "/CN=shop.example.com" -addext "subjectAltName=DNS:shop.example.com" \
-keyout /etc/nginx/tls/lab.key -out /etc/nginx/tls/lab.crt
sudo systemctl restart nginx
Five days is under both thresholds, so both uptime policies should open an incident. Once the policies exist, list the incidents with the GA gcloud monitoring alerts command group:
gcloud monitoring alerts list \
--format="table(name.basename(),state,openTime,closeTime,policy.displayName)"
This listing was taken at the end of the run, so it shows the whole life of each incident. The 30-day and 7-day incidents opened in the same evaluation at 09:05:52, the first 7-day one was cancelled when we replaced that policy to time a second run, and the other two closed after the rotation covered further down. The log-based change incident is still open because it only auto-closes after 30 minutes:

These are the timings we measured, all in UTC from the same lab. The step that dominates is the alert evaluation, not data collection. A certificate that is about to expire in minutes needs a different control than this one:
| Event | Time | Elapsed |
|---|---|---|
| Uptime check and policies created | 09:01:23 | 0 |
First time_until_ssl_cert_expires point (4.9986 days) | 09:03:00 | 1 min 37 s |
| 30-day and 7-day incidents open, Pub/Sub message published | 09:05:52 | 4 min 29 s |
7-day policy replaced with tofu apply -replace | 09:06:45 | 0 |
| Old incident closed as cancelled, message published | 09:08:07 | 1 min 22 s |
| New 7-day incident open | 09:10:50 | 4 min 5 s |
| Host reloaded with a 397-day cert | 09:12:07 | 0 |
| All three regions report about 397 days | by 09:14:00 | under 2 min |
| Both uptime incidents closed, messages published | 09:21:00 | 8 min 53 s |
Four to five minutes from “inside the threshold” to a message on the topic is fine for a 30-day or 7-day warning. The surprise is what a policy change does. Replacing a policy cancels its open incident and sends a closed notification that reads “Incident cancelled because the alert policy condition was deleted or modified while incident was active”. So if your bot auto-resolves tickets on closed state, it will resolve real ones during a Terraform change. Match on that text and leave those tickets open.
Read the incident payload on Pub/Sub
Each open and close event arrives as one Pub/Sub message whose data is the incident JSON, schema version 1.2. Save each pull to a file before you decode anything, because --auto-ack removes the messages from the subscription and a typo in the decoder then costs you the event. We lost the first open notification exactly that way:
gcloud pubsub subscriptions pull cert-alerts-pull --auto-ack --limit=10 --format=json > batch-1.json
gcloud pubsub subscriptions pull cert-alerts-pull --auto-ack --limit=10 --format=json > batch-2.json
The JSON output encodes message.data as URL-safe base64, and jq‘s @base64d rejected two of our five messages with “is not valid base64 data” until the - and _ characters were mapped back. This decoder handles both:
jq -r '.[].message.data | gsub("-";"+") | gsub("_";"/") | @base64d | fromjson | .incident | [.state, .incident_id, .observed_value, .documentation.subject] | @tsv' batch-1.json batch-2.json
After the rotation in the next section, two pulls held the close events for the incidents that had been open, one message each:

Monitoring prefixes the subject itself, so a close event reads [RESOLVED - Critical] TLS cert on 203.0.113.10 expires in < 7d without any template on your side. This trimmed open event shows the fields a bot routes on:
state: open or closedseverity: from the policy, Critical for the 7-day oneresource.labels.host: the hostname to fixobserved_value: days left, 4.995 heredocumentation.content: the runbook URL from the policy
Everything else in the payload describes the condition, which your bot rarely needs. The open event below keeps only those fields:
{
"version": "1.2",
"incident": {
"incident_id": "0.oexcr0myjckt",
"policy_name": "TLS cert on 203.0.113.10 expires in < 7d",
"state": "open",
"severity": "Critical",
"started_at": 1794474650,
"observed_value": "4.995",
"threshold_value": "7",
"resource": {
"labels": {
"host": "203.0.113.10",
"project_id": "your-gcp-project-id"
},
"type": "uptime_url"
},
"documentation": {
"subject": "[ALERT - Critical] TLS cert on 203.0.113.10 expires in < 7d",
"content": "Runbook: https://git.example.com/platform/runbooks/-/blob/main/cert-rotation.md"
},
"url": "https://console.cloud.google.com/monitoring/alerting/alerts/0.oexcr0myjckt?channelType=cloud-pubsub&project=your-gcp-project-id"
}
}
Use incident_id as the key for tickets. Open and close events for one incident share it, while the 30-day and 7-day policies raise separate incidents for the same certificate, so a bot keyed on hostname alone merges them and a bot keyed on message ID opens one ticket per event. Pub/Sub delivers at least once, and the incident ID is also what makes a redelivered message harmless.
Rotate the cert and watch the alert close
A rotation runbook isn’t finished until the alert clears on its own, because that is the proof the endpoint serves the new certificate. Uploading a certificate somewhere proves nothing to your users. We replaced the five-day certificate on the host with a 397-day one and reloaded nginx:
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 397 \
-subj "/CN=shop.example.com" -addext "subjectAltName=DNS:shop.example.com" \
-keyout /etc/nginx/tls/lab.key -out /etc/nginx/tls/lab.crt
sudo systemctl reload nginx
Query the raw time series to confirm every checker region sees the new expiry before you look at the incident:
curl -s -G -H "Authorization: Bearer ${TOKEN}" \
"https://monitoring.googleapis.com/v3/projects/${PROJECT_ID}/timeSeries" \
--data-urlencode 'filter=metric.type = "monitoring.googleapis.com/uptime_check/time_until_ssl_cert_expires"' \
--data-urlencode "interval.startTime=$(date -u -d '-2 min' +%FT%TZ)" \
--data-urlencode "interval.endTime=$(date -u +%FT%TZ)" \
| jq -r '.timeSeries[] | [.metric.labels.checker_location, .points[0].interval.endTime, .points[0].value.doubleValue] | @tsv'
All three regions reported about 397 days by 09:14:00, under two minutes after the 09:12:07 reload:

The incidents took much longer than the data. Both uptime incidents closed at 09:21:00, 8 minutes 53 seconds after the reload, and the close messages hit the topic in the same second with an observed_value of 396.996. That’s about seven minutes of a correct metric with an open incident. So end the runbook on the closed state from gcloud monitoring alerts list, not on the metric, and don’t page a second responder because the alert is still red five minutes after a fix.
Alert on Certificate Manager changes with a log-based metric
Certificate Manager’s audit log records API calls, not certificate state, so a log-based metric is good for catching unexpected changes and useless for catching failed ACME challenges. The old guide’s metric filtered on protoPayload.response.managed.state = "FAILED"; in the lab, the create and update entries carried only @type, labels and name in their response, so that filter can never match. The log actually holds this:
gcloud logging read 'protoPayload.serviceName="certificatemanager.googleapis.com" AND operation.first=true' \
--freshness=30m --limit=6 \
--format='table(timestamp,protoPayload.methodName.segment(-1),protoPayload.resourceName.segment(-1))'
Every long-running call writes two Admin Activity entries, one with operation.first=true and one with operation.last=true, which is why the metric in the module filters on the first one. Without that, every change counts twice:

The certmgr/cert_changes metric counts Update and Delete calls on certificates, maps, map entries and DNS authorizations, with the method name extracted into a label. We updated a certificate’s description at 09:05:28 and the incident opened at 09:10:50, so expect about five and a half minutes from the API call to the page. Point its runbook at a change review rather than a rotation: the useful question is whether the change was in a merge request.
For real ACME problems on Google-managed certificates, watch the certificate itself. The managed.state and managed.authorizationAttemptInfo fields in gcloud certificate-manager certificates describe carry the failure reason, and the audit script below catches the expiry if renewal keeps failing.
Check the Certificate Manager expiration histogram
The histogram is the one signal that covers certificates nobody wrote an uptime check for, and it is slow. To give it something to count, we uploaded self-signed certificates to Certificate Manager as lab-2day and lab-5day right after the first apply, and lab-6day at 09:12:51. They differ only in -days and the name, so the six-day one stands for all three:
openssl req -x509 -newkey rsa:2048 -nodes -days 6 \
-subj "/CN=lab6.example.com" -addext "subjectAltName=DNS:lab6.example.com" \
-keyout lab6.key -out lab6.crt
gcloud certificate-manager certificates create lab-6day \
--certificate-file=lab6.crt --private-key-file=lab6.key
Then read the raw samples. Each point is a distribution, and bucketCounts lines up with the bounds 0, 1, 7, 30 and 180 days, with an underflow bucket first. So the third number counts certificates with one to seven days left and the fifth counts 30 to 180 days:
curl -s -G -H "Authorization: Bearer ${TOKEN}" \
"https://monitoring.googleapis.com/v3/projects/${PROJECT_ID}/timeSeries" \
--data-urlencode 'filter=metric.type = "certificatemanager.googleapis.com/project/v2/certificate_expiration"' \
--data-urlencode "interval.startTime=$(date -u -d '-3 hour' +%FT%TZ)" \
--data-urlencode "interval.endTime=$(date -u +%FT%TZ)" \
| jq -r '.timeSeries[].points[] | [.interval.endTime, .value.distributionValue.count, (.value.distributionValue.bucketCounts | join(","))] | @tsv'
One sample per hour, about a minute later each time. The six-day certificate first shows up in the 09:43:56 sample, 31 minutes after the upload:

Two details change how far you can lean on this metric. The two-day certificate never appears, because the metric only counts certificates whose total lifetime is over 72 hours. And the 30 to 180 day bucket reads 2 while the project lists one certificate in that range (lab-5day, by then replaced in place with a 90-day certificate as shown further down). It also read 2 for hours before our certificates existed, so the counts are not a reliable inventory. Use the histogram to know that something is close to expiry, then find it with the audit script in the next section.
The histogram policy opened its incident at 09:46:45, 2 minutes 49 seconds after that sample and 34 minutes after the upload. Its observed_value was 216000, the 5th percentile in seconds, which is 2.5 days. The subject Monitoring generated names the project, not a certificate, so the runbook for this alert has to start with a list command. Expect up to an hour and a few minutes of lag in the worst case, which is fine against a 30-day threshold and useless for anything shorter. If the project holds Google-managed certificates, this policy will also open during their normal renewal window, so route it as a ticket rather than a page. A project with Media CDN edge cache certificates keeps it open all the time, because those never have more than 30 days left; there, lower the threshold or leave the histogram out.
Audit every project for expiring certs
Alerts only cover hosts that someone added to the module, so you also need an inventory that doesn’t depend on that. This script walks every project your account can see and prints Certificate Manager and Compute Engine certificates that expire inside the window you pass. Errors from projects where an API is disabled are dropped, so one locked-down project does not stop the run:
vim audit-certs.sh
Both list commands accept a server-side filter on expireTime, which keeps the output to the certificates that need a decision:
#!/usr/bin/env bash
# audit-certs.sh: list every certificate that expires within DAYS (default 30) in every project you can see
set -euo pipefail
DAYS="${1:-30}"
CUTOFF=$(date -u -d "+${DAYS} days" +%Y-%m-%dT%H:%M:%SZ)
for PROJECT in $(gcloud projects list --format="value(projectId)"); do
echo "=== ${PROJECT} (expiring before ${CUTOFF}) ==="
gcloud certificate-manager certificates list --project="${PROJECT}" \
--filter="expireTime<${CUTOFF}" \
--format="table(name.basename(),scope,expireTime,sanDnsnames.list())" 2>/dev/null || true
gcloud compute ssl-certificates list --project="${PROJECT}" \
--filter="expireTime<${CUTOFF}" \
--format="table(name,type,expireTime,subjectAlternativeNames.list())" 2>/dev/null || true
done
Make it executable and run it with a 30-day window:
chmod +x audit-certs.sh
./audit-certs.sh 30
Our lab project held two short-lived uploads at that point, and both show up with their SANs. The two-day certificate is listed here even though the histogram ignores it, which is the reason to keep the script alongside the metric:

Run it weekly from CI and treat any row as a finding. The script always exits 0 and prints a === header for every project, so filter those and the table headers out before you fail the job. found=$(./audit-certs.sh 30 | grep -Ev '^(===|NAME )' || true); if [ -n "$found" ]; then echo "$found"; exit 1; fi turns the build red only when a certificate is listed, prints the rows, and behaves the same under set -o pipefail. A certificate that isn’t on the shared cert map from the shared load balancer cert map setup or under the Private CA chain is drift, and the Terraform and ArgoCD inventory guardrails are where it gets onboarded or exempted.
Rotate a Google-managed certificate
Google-managed certificates renew themselves, and the timing matters for your thresholds. Per the Google-managed certificate docs, renewal starts when about one third of the validity is left: about 30 days before expiry for a 90-day certificate and about 15 days for a 45-day one. Media CDN’s EDGE_CACHE certificates are only valid for 30 days and renew about 10 days before expiry. So the 30-day policy will fire on healthy managed certificates every cycle. Keep 30 days for uploaded and self-managed certificates, page on load balancer managed hostnames at 7 to 10 days, and use 7 days for edge cache hostnames. Below that line a certificate that is still not renewed really is stuck. The usual causes then are a DNS authorization record that drifted and a CAA record that does not allow Google’s CAs. This runbook is what the policy’s cert-rotation.md link should open, and you can work through it in order:
- Describe the certificate and read
managed.stateandmanaged.authorizationAttemptInfo. - Describe the DNS authorization and note the CNAME it expects.
- Resolve that CNAME from a public resolver and compare.
- Fix the record (or the CAA policy), then watch the uptime metric climb back past your managed-cert threshold.
The DNS authorization tells you exactly which record Certificate Manager expects. In the lab we created one for shop.example.com and described it:
gcloud certificate-manager dns-authorizations create lab-shop-auth --domain=shop.example.com
gcloud certificate-manager dns-authorizations describe lab-shop-auth \
--format="yaml(domain,dnsResourceRecord,type)"
The record is a CNAME under _acme-challenge pointing into authorize.certificatemanager.goog:
dnsResourceRecord:
data: dddbf581-1e61-4207-ab18-63c74b77c00f.8.authorize.certificatemanager.goog.
name: _acme-challenge.shop.example.com.
type: CNAME
domain: shop.example.com
type: FIXED_RECORD
Now check whether the public DNS agrees:
dig +short CNAME _acme-challenge.shop.example.com @1.1.1.1
An empty answer, which is what we got for the unowned example domain, means the record is missing and renewal can’t pass. A mismatched target means someone recreated the authorization without updating DNS. The wildcard certificate with DNS authorization guide has the Terraform that creates the record from the authorization, and the DNSSEC and CAA setup covers the CAA records that also block issuance.
Rotate a self-managed certificate in place
A self-managed certificate in Certificate Manager can be replaced in place, so the map entries that reference it keep pointing at the same resource and nothing on the load balancer changes. In the lab the replacement for lab-5day was a 90-day self-signed certificate for the same name:
openssl req -x509 -newkey rsa:2048 -nodes -days 90 \
-subj "/CN=lab5.example.com" -addext "subjectAltName=DNS:lab5.example.com" \
-keyout lab5b.key -out lab5b.crt
Upload the new certificate and key over the existing name, then read back the expiry:
gcloud certificate-manager certificates update lab-5day \
--certificate-file=lab5b.crt --private-key-file=lab5b.key
gcloud certificate-manager certificates describe lab-5day --format="value(expireTime,updateTime)"
We started the update at 09:12:38, and the expiry moved from five days out to the new certificate’s 90 days with an updateTime under four seconds later:
Updated certificate [lab-5day].
2027-02-10T09:12:38Z 2026-11-12T09:12:41.871507954Z
That update is also an UpdateCertificate audit entry, so the change alert fires for planned rotations too. Expect it, and close it against the change ticket. For certificates on the financial load balancer, the issuing side lives in the Private CA setup for financial services; this in-place update is the last step after the new certificate is issued and its chain verified.
Update SPKI pins before a new-key rotation
A same-key rotation keeps the pin valid; a new-key rotation breaks every client that pins the old key unless the new pin shipped first. Compute the pin from the new certificate before it goes anywhere near the load balancer:
openssl x509 -in lab5b.crt -pubkey -noout | openssl pkey -pubin -outform der \
| openssl dgst -sha256 -binary | openssl enc -base64
The output is the base64 SHA-256 of the public key, the value clients compare against:
lZtCqG881aJ9yaOv0L4ooHUl7haXOhoYJjM49GIuP7Q=
Ship a client build that accepts both the current and the next pin, and wait until telemetry shows most active installs on it. Then rotate, and remove the old pin in a later build. Skip the wait and every client still on the old build fails closed the moment the load balancer serves the new key. The SPKI pinning guide for Private CA has the client side of that sequence.
Revoke a compromised certificate
Revocation only exists for certificates you issue from CA Service; Google-managed and uploaded certificates have no revoke call in Certificate Manager, so removing them from service is the control. In order:
- Find every cert map entry and target proxy that references the certificate.
- Private CA: revoke with
gcloud privateca certificates revoke. - Uploaded cert: replace it in place with a new key, as in the previous section.
- Google-managed cert: point the map entry at a replacement, then delete the old certificate.
- Tighten CAA if the issuing CA itself is the problem.
The map entry update and the certificate delete or update are Certificate Manager writes, so those steps fire the change alert. The Private CA revocation and the CAA change do not, so note their times by hand. Here the alert is useful rather than noise. The incident timeline becomes the evidence for the post-mortem, so you don’t have to reconstruct who changed what from chat logs afterwards.
Write the post-mortem
Every cert incident is either a runbook gap or a monitoring gap, and the template forces you to name which. Keep it next to the runbooks in the repo the alert’s documentation link points at:
# Cert incident post-mortem: YYYY-MM-DD
## Summary
- Window: first alert (incident_id) to recovery
- Impact: hostnames, clients, error rate
- Severity: P1 to P4
## Timeline (UTC)
- cert inside threshold / alert opened / acknowledged / fixed / alert closed
## Root cause
- what failed (DNS authorization, CAA, expired upload, LB still on old cert)
- why monitoring did not catch it earlier
## Actions
- [ ] runbook change, owner, due date
- [ ] monitoring change, owner, due date
Pull the timeline from gcloud monitoring alerts list and the audit log rather than from memory, because the open and close times are already there to the second. If the alert fired late or not at all, the action belongs under monitoring, and the module in this guide is where you fix it.
Clean up the lab
If you followed along with a throwaway project, the module goes in one command and the hand-made pieces after it, one delete per resource:
tofu destroy -auto-approve -var monitored_host=203.0.113.10
gcloud certificate-manager certificates delete lab-2day --quiet
gcloud certificate-manager certificates delete lab-5day --quiet
gcloud certificate-manager certificates delete lab-6day --quiet
gcloud certificate-manager dns-authorizations delete lab-shop-auth --quiet
gcloud compute instances delete certlab-web --zone=europe-west1-b --quiet
gcloud compute firewall-rules delete certlab-allow-https --quiet
In our run the destroy removed 10 resources and a follow-up sweep of notification channels, policies, uptime checks, Pub/Sub topics, log metrics, certificates, DNS authorizations, instances and firewall rules found none of the lab’s resources left. Keep the module itself in your platform repo, because the alerts are only useful while they exist: the zero-incident rotation demo runs against exactly these policies, and a rotation that finishes with the 30-day incident closed and nothing else paged is the result to aim for.