问题描述
我在谷歌云平台有多个项目和api,比如地图api、PHP应用引擎、sql等。
Google 改变了帐单管理方式,现在帐单很有可能因任何原因(错误、黑客等)而猛增。
如何才能在达到限制时禁用所有计费?不仅仅是电子邮件通知,这还不够! 我不能只是关闭我的应用引擎实例,因为地图和其他地方的 api 凭据仍然可以产生费用!
解决方法
Set budgets and budget alerts 文档。您有 2 种策略来解决这个问题。
第一个是设置 API spending limit 基于 wuota 或限制每个用户的调用,因此如果您的服务对特定 API 进行大量调用,您只需阻止此 API,这样您的整个服务/项目可以继续服务。
另一种方法是为整个项目automate the disabling of billing。这样做的风险更大,因为它会阻塞整个项目并可能导致数据丢失。
为此,您将部署一个 Cloud Functions 函数,如由您的预算设置使用的 Pub/Sub 主题触发的文档中的那个函数:
const {google} = require('googleapis');
const {GoogleAuth} = require('google-auth-library');
const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT;
const PROJECT_NAME = `projects/${PROJECT_ID}`;
const billing = google.cloudbilling('v1').projects;
exports.stopBilling = async pubsubEvent => {
const pubsubData = 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';
}
_setAuthCredential();
const billingEnabled = await _isBillingEnabled(PROJECT_NAME);
if (billingEnabled) {
return _disableBillingForProject(PROJECT_NAME);
} else {
return 'Billing already disabled';
}
};
/**
* @return {Promise} Credentials set globally
*/
const _setAuthCredential = () => {
const client = new GoogleAuth({
scopes: [
'https://www.googleapis.com/auth/cloud-billing','https://www.googleapis.com/auth/cloud-platform',],});
// Set credential globally for all requests
google.options({
auth: client,});
};
/**
* 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 = async projectName => {
try {
const res = await billing.getBillingInfo({name: projectName});
return res.data.billingEnabled;
} catch (e) {
console.log(
'Unable to determine if billing is enabled on specified project,assuming billing is enabled'
);
return true;
}
};
/**
* 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 = async projectName => {
const res = await billing.updateBillingInfo({
name: projectName,resource: {billingAccountName: ''},// Disable billing
});
return `Billing disabled: ${JSON.stringify(res.data)}`;
};
依赖:
{
"name": "cloud-functions-billing","version": "0.0.1","dependencies": {
"google-auth-library": "^2.0.0","googleapis": "^52.0.0"
}
}
然后您授予此云功能的服务帐户Billing Admin权限
如果您想使用这种方法,我建议您在两种情况下尽可能为每个服务设置不同的项目,以便您可以仅关闭部分服务。