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
importbase64importjsonimportosfromgoogleapiclientimportdiscoveryPROJECT_ID=os.getenv("GCP_PROJECT")PROJECT_NAME=f"projects/{PROJECT_ID}"defstop_billing(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})")returnifPROJECT_IDisNone:print("No project specified with environment variable")returnbilling=discovery.build("cloudbilling","v1",cache_discovery=False,)projects=billing.projects()billing_enabled=__is_billing_enabled(PROJECT_NAME,projects)ifbilling_enabled:__disable_billing_for_project(PROJECT_NAME,projects)else:print("Billing already disabled")def__is_billing_enabled(project_name,projects):""" Determine whether billing is enabled for a project @param {string} project_name Name of project to check if billing is enabled @return {bool} Whether project has billing enabled or not """try:res=projects.getBillingInfo(name=project_name).execute()returnres["billingEnabled"]exceptKeyError:# If billingEnabled isn't part of the return, billing is not enabledreturnFalseexceptException:print("Unable to determine if billing is enabled on specified project, assuming billing is enabled")returnTruedef__disable_billing_for_project(project_name,projects):""" Disable billing for a project by removing its billing account @param {string} project_name Name of project disable billing on """body={"billingAccountName":""}# Disable billingtry:res=projects.updateBillingInfo(name=project_name,body=body).execute()print(f"Billing disabled: {json.dumps(res)}")exceptException:print("Failed to disable billing, possibly 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"]],["最后更新时间 (UTC):2025-05-05。"],[[["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."]]],[]]