const{CloudBillingClient}=require('@google-cloud/billing');const{InstancesClient}=require('@google-cloud/compute');constPROJECT_ID=process.env.GOOGLE_CLOUD_PROJECT;constPROJECT_NAME=`projects/${PROJECT_ID}`;constbilling=newCloudBillingClient();exports.stopBilling=asyncpubsubEvent=>{constpubsubData=JSON.parse(Buffer.from(pubsubEvent.data,'base64').toString());if(pubsubData.costAmount<=pubsubData.budgetAmount){return`No action necessary. (Current cost: ${pubsubData.costAmount})`;}if(!PROJECT_ID){return'No project specified';}constbillingEnabled=await_isBillingEnabled(PROJECT_NAME);if(billingEnabled){return_disableBillingForProject(PROJECT_NAME);}else{return'Billing already disabled';}};/** * Determine whether billing is enabled for a project * @param {string} projectName Name of project to check if billing is enabled * @return {bool} Whether project has billing enabled or not */const_isBillingEnabled=asyncprojectName=>{try{const[res]=awaitbilling.getProjectBillingInfo({name:projectName});returnres.billingEnabled;}catch(e){console.log('Unable to determine if billing is enabled on specified project, assuming billing is enabled');returntrue;}};/** * Disable billing for a project by removing its billing account * @param {string} projectName Name of project disable billing on * @return {string} Text containing response from disabling billing */const_disableBillingForProject=asyncprojectName=>{const[res]=awaitbilling.updateProjectBillingInfo({name:projectName,resource:{billingAccountName:''},// Disable billing});return`Billing disabled: ${JSON.stringify(res)}`;};
Python
# WARNING: The following action, if not in simulation mode, will disable billing# for the project, potentially stopping all services and causing outages.# Ensure thorough testing and understanding before enabling live deactivation.importbase64importjsonimportosimporturllib.requestfromcloudevents.http.eventimportCloudEventimportfunctions_frameworkfromgoogle.api_coreimportexceptionsfromgoogle.cloudimportbilling_v1fromgoogle.cloudimportloggingbilling_client=billing_v1.CloudBillingClient()defget_project_id()-> str:"""Retrieves the Google Cloud Project ID. This function first attempts to get the project ID from the `GOOGLE_CLOUD_PROJECT` environment variable. If the environment variable is not set or is None, it then attempts to retrieve the project ID from the Google Cloud metadata server. Returns: str: The Google Cloud Project ID. Raises: ValueError: If the project ID cannot be determined either from the environment variable or the metadata server. """# Read the environment variable, usually set manuallyproject_id=os.getenv("GOOGLE_CLOUD_PROJECT")ifproject_idisnotNone:returnproject_id# Otherwise, get the `project-id`` from the Metadata serverurl="http://metadata.google.internal/computeMetadata/v1/project/project-id"req=urllib.request.Request(url)req.add_header("Metadata-Flavor","Google")project_id=urllib.request.urlopen(req).read().decode()ifproject_idisNone:raiseValueError("project-id metadata not found.")returnproject_id@functions_framework.cloud_eventdefstop_billing(cloud_event:CloudEvent)-> None:# TODO(developer): As stoping billing is a destructive action# for your project, change the following constant to False# after you validate with a test budget.SIMULATE_DEACTIVATION=TruePROJECT_ID=get_project_id()PROJECT_NAME=f"projects/{PROJECT_ID}"event_data=base64.b64decode(cloud_event.data["message"]["data"]).decode("utf-8")event_dict=json.loads(event_data)cost_amount=event_dict["costAmount"]budget_amount=event_dict["budgetAmount"]print(f"Cost: {cost_amount} Budget: {budget_amount}")ifcost_amount <=budget_amount:print("No action required. Current cost is within budget.")returnprint(f"Disabling billing for project '{PROJECT_NAME}'...")is_billing_enabled=_is_billing_enabled(PROJECT_NAME)ifis_billing_enabled:_disable_billing_for_project(PROJECT_NAME,SIMULATE_DEACTIVATION)else:print("Billing is already disabled.")def_is_billing_enabled(project_name:str)-> bool:"""Determine whether billing is enabled for a project. Args: project_name: Name of project to check if billing is enabled. Returns: Whether project has billing enabled or not. """try:print(f"Getting billing info for project '{project_name}'...")response=billing_client.get_project_billing_info(name=project_name)returnresponse.billing_enabledexceptExceptionase:print(f'Error getting billing info: {e}')print("Unable to determine if billing is enabled on specified project, ""assuming billing is enabled.")returnTruedef_disable_billing_for_project(project_name:str,simulate_deactivation:bool,)-> None:"""Disable billing for a project by removing its billing account. Args: project_name: Name of project to disable billing. simulate_deactivation: If True, it won't actually disable billing. Useful to validate with test budgets. """# Log this operation in Cloud Logginglogging_client=logging.Client()logger=logging_client.logger(name="disable-billing")ifsimulate_deactivation:entry_text="Billing disabled. (Simulated)"print(entry_text)logger.log_text(entry_text,severity="CRITICAL")return# Find more information about `updateBillingInfo` API method here:# https://cloud.google.com/billing/docs/reference/rest/v1/projects/updateBillingInfotry:# To disable billing set the `billing_account_name` field to emptyproject_billing_info=billing_v1.ProjectBillingInfo(billing_account_name="")response=billing_client.update_project_billing_info(name=project_name,project_billing_info=project_billing_info)entry_text=f"Billing disabled: {response}"print(entry_text)logger.log_text(entry_text,severity="CRITICAL")exceptexceptions.PermissionDenied:print("Failed to disable billing, check permissions.")
[[["容易理解","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-08-18 (世界標準時間)。"],[[["This tutorial guides you through automatically disabling Cloud Billing for a project when its costs meet or exceed a predefined budget, effectively shutting down all Google Cloud services within that project."],["Disabling Cloud Billing is a permanent action that can lead to resource deletion, and while it can be re-enabled, there's no guarantee of recovering the services or data that were deleted."],["Setting up the automated billing disablement requires enabling the Cloud Billing API, creating a budget for the project, and configuring programmatic budget notifications."],["A Cloud Run function is essential, being configured to interact with the Cloud Billing API to disable billing, triggered by Pub/Sub topic notifications from the project's budget."],["The function requires appropriate service account permissions to modify billing and project services, and following this process doesn't ensure costs will be limited to the budget due to billing delays."]]],[]]