프로젝트에서 결제를 사용 중지하면 모든 서비스가 중지되고 모든 리소스가 결과적으로 삭제됩니다. 보다 세밀한 대응이 필요한 경우에는 선택적으로 리소스를 제어할 수 있습니다. 예를 들어 일부 Compute Engine 리소스를 중지하고 Cloud Storage 리소스는 그대로 두는 것이 가능합니다. 일부 리소스만 중지하면 환경을 완전히 사용 중지하지 않고도 비용을 줄일 수 있습니다.
다음 예시의 프로젝트에서는 여러 Compute Engine 가상 머신(VM)으로 연구를 실행하고 결과를 Cloud Storage 버킷에 저장합니다. 예산 알림을 트리거로 사용하여 예산이 초과되면 Cloud Run 함수가 모든 Compute Engine 인스턴스를 종료하지만 저장된 결과에는 영향을 미치지 않습니다.
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}")
진입점을 실행할 올바른 함수로 설정합니다.
Node.js
진입점을 limitUse로 설정합니다.
Python
진입점을 limit_use로 설정합니다.
자동으로 설정된 환경 변수 목록을 검토하고 가상 머신을 실행하는 프로젝트에 GCP_PROJECT 변수를 수동으로 설정해야 하는지 여부를 확인합니다.
ZONE 매개변수를 설정합니다. 이 파라미터는 예산이 초과될 때 인스턴스가 중지되는 영역입니다.
배포를 클릭합니다.
서비스 계정 권한 구성
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-03-06(UTC)"],[[["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."]]],[]]