이 문서에서는 비용이 프로젝트 예산에 도달하거나 이를 초과할 때 프로젝트에서 결제를 자동으로 사용 중지하는 방법을 설명합니다. 프로젝트에서 결제를 사용 중지하면 무료 등급 서비스를 포함한 프로젝트의 모든 Google Cloud 서비스가 종료됩니다.
예산 알림에 대한 보다 세분화된 응답은 알림으로 리소스 사용량 제어하기를 참조하세요.
Google Cloud에 지출할 수 있는 최대 금액이 정해져 있으므로 비용이 제한될 수 있습니다. 이러한 경우 예산 한도에 도달하면 모든 Google Cloud 서비스 및 사용을 종료하여 비용 발생을 중지해야 할 수 있습니다. 프로젝트에서 결제를 사용 중지하면 해당 프로젝트에서 비용이 발생하지 않도록 막는 데 효과적입니다.
제한사항
비용 발생 시점과 예산 알림 수신 시점 사이에 지연이 있으므로 모든 서비스가 중지된 시점에 기록되지 않은 사용량으로 인한 추가 비용이 발생할 수 있습니다.
이 예시의 단계를 따라도 예산보다 많은 비용을 지출하지 않는다고는 보장할 수 없습니다. 자금이 제한되어 있다면 결제 지연을 고려하여 최대 예산을 가용 자금 미만으로 설정합니다.
결제 계정에 잠긴 프로젝트에서는 결제를 사용 중지할 수 없습니다. 프로젝트 잠금 및 잠금 해제에 관한 자세한 내용은 프로젝트와 결제 계정 간의 링크 보안을 참조하세요.
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")
진입점을 실행할 올바른 함수로 설정합니다.
Node.js
진입점을 stopBilling로 설정합니다.
Python
진입점을 stop_billing로 설정합니다.
자동으로 설정된 환경 변수 목록을 검토하여 Cloud Billing을 사용 중지하려는 프로젝트에 GOOGLE_CLOUD_PROJECT 변수를 수동으로 설정해야 하는지 여부를 확인합니다.
배포를 클릭합니다.
서비스 계정 권한 구성
Cloud Run 함수는 자동으로 생성된 서비스 계정으로 실행됩니다.
결제를 사용 중지하려면 다음 단계를 완료하여 프로젝트에서 수정해야 하는 모든 서비스에 대한 권한을 서비스 계정에 부여해야 합니다.
Cloud Run 함수의 세부정보를 확인하여 올바른 서비스 계정을 확인합니다. 서비스 계정은 페이지 아래에 나열됩니다.
[[["이해하기 쉬움","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-05-01(UTC)"],[[["\u003cp\u003eThis 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.\u003c/p\u003e\n"],["\u003cp\u003eDisabling 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.\u003c/p\u003e\n"],["\u003cp\u003eSetting up the automated billing disablement requires enabling the Cloud Billing API, creating a budget for the project, and configuring programmatic budget notifications.\u003c/p\u003e\n"],["\u003cp\u003eA 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.\u003c/p\u003e\n"],["\u003cp\u003eThe 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.\u003c/p\u003e\n"]]],[],null,[]]