קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
במאמר הזה נסביר איך להשתמש בהתראות לגבי תקציבים בשביל שליטה סלקטיבית בשימוש במשאבים.
כשמשביתים את החיוב בפרויקט, כל השירותים מופסקים, ובסופו של דבר כל המשאבים נמחקים. אם אתם לא רוצים להגיב בצורה כל כך גורפת, אתם יכולים לשלוט במשאבים באופן סלקטיבי. לדוגמה, אתם יכולים להפסיק כמה משאבי Compute Engine בלי שתהיה לכך השפה על משאבי Cloud Storage. השבתה של חלק מהמשאבים מצמצמת את העלויות בלי להשבית את הסביבה לחלוטין.
בדוגמה שכאן, בפרויקט מופעל מחקר בכמה מכונות וירטואליות (VM) של Compute Engine, והתוצאות מאוחסנות בקטגוריות של 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}")
מגדירים את Entry point לפונקציה הנכונה להרצה:
Node.js
מגדירים את Entry point ל-limitUse.
Python
מגדירים את Entry point ל-limit_use.
בודקים את רשימת משתני הסביבה שמוגדרים אוטומטית כדי להחליט אם צריכים להגדיר ידנית את המשתנה GCP_PROJECT לפרויקט שהמכונות הווירטואליות רצות בו.
מגדירים את הפרמטר ZONE. הפרמטר הזה הוא התחום (zone) שבו המכונות מופסקות כשיש חריגה מהתקציב.
לוחצים על DEPLOY.
הגדרת הרשאות לחשבון שירות
פונקציית Cloud Run פועלת בתור חשבון שירות שנוצר אוטומטית. כדי לשלוט בשימוש, צריך לתת לחשבון השירות הרשאות לכל השירותים בפרויקט שהוא אמור לשנות. כדי לעשות את זה, מבצעים את הפעולות האלה:
כדי לזהות את חשבון השירות הנכון, אתם יכולים לבדוק את הפרטים של פונקציית Cloud Run. חשבון השירות מופיע בחלק התחתון של הדף.
נכנסים לדף IAM במסוף Google Cloud כדי להגדיר את ההרשאות המתאימות.
[[["התוכן קל להבנה","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-23 (שעון UTC)."],[[["\u003cp\u003eThis 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.\u003c/p\u003e\n"],["\u003cp\u003eBy 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.\u003c/p\u003e\n"],["\u003cp\u003eTo 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.\u003c/p\u003e\n"],["\u003cp\u003eThe 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.\u003c/p\u003e\n"],["\u003cp\u003eAfter 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.\u003c/p\u003e\n"]]],[],null,[]]