gra*_*_15 6 google-app-engine billing google-cloud-platform google-cloud-billing
我在谷歌云平台中有多个项目和API,如地图API、PHP应用程序引擎、SQL等。
谷歌改变了计费管理方式,现在计费确实有可能因任何原因(错误、黑客等)飙升。
如何才能在达到限制时禁用所有计费?不仅仅是电子邮件通知,这还不够!我不能只是关闭我的应用程序引擎实例,因为地图和其他地方的 API 凭据仍然会产生费用!
设置预算和预算警报文档。你有两种策略来解决这个问题。
第一个是设置基于 wuota的 API 支出限制或限制每个用户的调用,因此,如果您的服务对特定 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)}`;
};
Run Code Online (Sandbox Code Playgroud)
依赖项:
{
"name": "cloud-functions-billing",
"version": "0.0.1",
"dependencies": {
"google-auth-library": "^2.0.0",
"googleapis": "^52.0.0"
}
}
Run Code Online (Sandbox Code Playgroud)
然后您向此云功能的服务帐户授予计费管理员权限
如果您想使用这种方法,我建议您在任何一种情况下都为每个服务设置不同的项目(如果可能),这样您就可以仅关闭部分服务。
| 归档时间: |
|
| 查看次数: |
3517 次 |
| 最近记录: |