Whenever a GCP secret nears it's expiration date, it creates expiration logs in Secret Manager secret resource as mentioned here. It states one can create Log-based metrics and use them to create alerts for upcoming expirations. But the log based metric do not provide a filter for this. How can it be accomplished?
Create notifications when GCP secret nears expiry
1.2k Views Asked by Rapak AtThere are 3 best solutions below
On
The easiest way to create a logs-based metric is from the Logs Explorer page. You can use a query like the following to find all log messages where the secret will expire in 1 hour:
resource.type="secretmanager.googleapis.com/Secret"
jsonPayload.type="EXPIRES_IN_1_HOUR"
As noted in the Secret Manager expiration documentation, there are other event types you could subscribe to including:
EXPIRES_IN_30_DAYSEXPIRES_IN_7_DAYSEXPIRES_IN_1_DAYEXPIRES_IN_6_HOURSEXPIRES_IN_1_HOUREXPIRED
Then, from the Actions menu, choose "Create metric":
The metric type should be "Counter". You can provide whatever name and description you'd like. The units should be unitless (1).
You can optionally add a label. For example, if you wanted to label the metric with the secret name, you could add a label named "secret" targeting the jsonPayload.name field. If you wanted to get extra fancy, you could strip off the leading projects/.../secrets prefix using a regular expression extractor like projects/.+/secrets/(.+).
After you've created the metric, you can create an alert under Monitoring -> Alerting -> Create Policy. Choose the name of your metric (it will be logging.googleapis.com/user/NAME_YOU_CHOSE).
Set the aligner to count and the aggregator to sum, and then set the condition to be above 1.
You will need to configure notification channels to actually get alerted, but you can watch the alert fire in the web UI too.



To view logs of Secret’s Expiration, use the following log query in Logs Explorer,
We then can create an User-defined metric on this filter, follow the below steps to create counter-type logs-based metrics:
Go to the Logging > Logs-based Metrics page
Click Create Metric, select Metric Type as “Counter” and fill Name, Description and Units(can be left blank).
In Build filter column use the following query,
Click Create Metric. Refer to Creating counter metrics for more information.
After the User-defined metric is created, we now create an alert on the above metric depending on our desired Violation rules, follow the below steps to create an alerting policy on a logs-based counter metric:
I implemented the above steps with my Mail ID as a Notification Channel and was able to view the alerts without any problem.