const{CloudBillingClient}=require('@google-cloud/billing');const{InstancesClient}=require('@google-cloud/compute');constPROJECT_ID=process.env.GOOGLE_CLOUD_PROJECT;constPROJECT_NAME=`projects/${PROJECT_ID}`;constinstancesClient=newInstancesClient();constZONE='us-central1-a';exports.limitUse=asyncpubsubEvent=>{constpubsubData=JSON.parse(Buffer.from(pubsubEvent.data,'base64').toString());if(pubsubData.costAmount<=pubsubData.budgetAmount){return`No action necessary. (Current cost: ${pubsubData.costAmount})`;}constinstanceNames=await_listRunningInstances(PROJECT_ID,ZONE);if(!instanceNames.length){return'No running instances were found.';}await_stopInstances(PROJECT_ID,ZONE,instanceNames);return`${instanceNames.length} instance(s) stopped successfully.`;};/** * @return {Promise} Array of names of running instances */const_listRunningInstances=async(projectId,zone)=>{const[instances]=awaitinstancesClient.list({project:projectId,zone:zone,});returninstances.filter(item=>item.status==='RUNNING').map(item=>item.name);};/** * @param {Array} instanceNames Names of instance to stop * @return {Promise} Response from stopping instances */const_stopInstances=async(projectId,zone,instanceNames)=>{awaitPromise.all(instanceNames.map(instanceName=>{returninstancesClient.stop({project:projectId,zone:zone,instance:instanceName,}).then(()=>{console.log(`Instance stopped successfully: ${instanceName}`);});}));};
Python
importbase64importjsonimportosfromgoogleapiclientimportdiscoveryPROJECT_ID=os.getenv("GCP_PROJECT")PROJECT_NAME=f"projects/{PROJECT_ID}"ZONE="us-west1-b"deflimit_use(data,context):pubsub_data=base64.b64decode(data["data"]).decode("utf-8")pubsub_json=json.loads(pubsub_data)cost_amount=pubsub_json["costAmount"]budget_amount=pubsub_json["budgetAmount"]ifcost_amount <=budget_amount:print(f"No action necessary. (Current cost: {cost_amount})")returncompute=discovery.build("compute","v1",cache_discovery=False,)instances=compute.instances()instance_names=__list_running_instances(PROJECT_ID,ZONE,instances)__stop_instances(PROJECT_ID,ZONE,instance_names,instances)def__list_running_instances(project_id,zone,instances):""" @param {string} project_id ID of project that contains instances to stop @param {string} zone Zone that contains instances to stop @return {Promise} Array of names of running instances """res=instances.list(project=project_id,zone=zone).execute()if"items"notinres:return[]items=res["items"]running_names=[i["name"]foriinitemsifi["status"]=="RUNNING"]returnrunning_namesdef__stop_instances(project_id,zone,instance_names,instances):""" @param {string} project_id ID of project that contains instances to stop @param {string} zone Zone that contains instances to stop @param {Array} instance_names Names of instance to stop @return {Promise} Response from stopping instances """ifnotlen(instance_names):print("No running instances were found.")returnfornameininstance_names:instances.stop(project=project_id,zone=zone,instance=name).execute()print(f"Instance stopped successfully: {name}")
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-09 (世界標準時間)。"],[[["This guide details how to use budget notifications to manage resource usage selectively, allowing you to halt specific resources, such as Compute Engine instances, while preserving others, such as Cloud Storage."],["By setting up a Cloud Run function triggered by budget notifications, you can automatically stop Compute Engine virtual machines when a budget threshold is exceeded, thus reducing costs without fully disabling the environment."],["To get started, you'll need to enable the Cloud Billing API, create a budget, and configure programmatic budget notifications, followed by setting up a Cloud Run function with specific dependencies and code."],["The Cloud Run function code provided in Node.js and Python allows you to list and stop running instances in a designated zone, with customizable parameters for different project zones or projects."],["After deploying the function, it is crucial to configure the appropriate service account permissions to allow the Cloud Run function to modify resources and to test the function to confirm that instances are properly stopped."]]],[]]