2021年谷歌云平台如何防止超额计费



我在谷歌云平台上有多个项目和api,如地图api, php应用引擎,sql等。

Google改变了计费的管理方式,现在计费很有可能因为任何原因(bug,黑客等)而飙升

如何使达到限制时每个账单都被禁用?不只是电子邮件通知,这是不够的!我不能直接关闭我的应用引擎实例,因为地图和其他地方的api凭据仍然会产生费用!

设置预算和预算警报文档。你有两种策略来处理这个问题。

第一个是设置API支出限制,要么基于wuta,要么限制每个用户的调用,所以如果你的一个服务对特定API进行了过多的调用,你只要阻止这个API,这样你的整个服务/项目就可以继续服务。

另一种方法是自动禁用整个项目的账单。这是更危险的,因为它会阻塞整个项目,并可能导致数据丢失。

为此,您将部署一个云功能,类似于文档中由您的预算设置为使用的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权限授予此Cloud Function的服务帐户

如果你想使用这种方法,我建议你在任何一种情况下,每个服务都有不同的项目,如果可能的话,这样你就可以只关闭部分服务。

相关内容

  • 没有找到相关文章

最新更新