This document explains how to use budget notifications to selectively control resource usage.
When you disable billing on a project, all services stop and all resources are eventually deleted. If you need a more nuanced response, you can selectively control resources. For example, you can stop some Compute Engine resources while leaving Cloud Storage resources intact. Stopping only some resources reduces your costs without completely disabling your environment.
In the following example, the project runs research with a number of Compute Engine virtual machines (VMs) and stores results in Cloud Storage buckets. Using the budget notifications as the trigger, after the budget is exceeded, this Cloud Run function shuts down all Compute Engine instances, but doesn't affect the stored results.
Before you begin
Before you begin, you must complete the following tasks:
Set up a Cloud Run function
- Complete the steps in Create a Cloud Run function. Ensure that you set the Trigger type to the same Pub/Sub topic that your budget will use.
Add the following dependencies:
Node.js
Copy the following to your
package.json
file:Python
Copy the following to your
requirements.txt
file:Copy the following code into your Cloud Run function:
Node.js
Python
Set the Entry point to the correct function to execute:
Node.js
Set the Entry point to
limitUse
.Python
Set the Entry point to
limit_use
.Review the list of environment variables set automatically and determine if you need to manually set the GCP_PROJECT variable to the project running the virtual machines.
Set the ZONE parameter. This parameter is the zone where instances are stopped when the budget is exceeded.
Click DEPLOY.
Configure service account permissions
Your Cloud Run function runs as an automatically created service account. To control usage, you need to grant the service account permissions to any services on the project that it needs to modify by completing the following steps:
- Identify the correct service account by viewing the details of your Cloud Run function. The service account is listed at the bottom of the page.
Go to the IAM page in the Google Cloud console to set the appropriate permissions.
Test that instances are stopped
To ensure your function works as expected, follow the steps in Test a Cloud Run function.
If successful, your Compute Engine VMs in the Google Cloud console are stopped.
What's next
Review other programmatic notification examples to learn how to do the following: