3

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

Google 改变了计费的管理方式,现在确实有可能以任何原因(错误、黑客等)导致计费飙升

我怎样才能使达到限制时禁用每个计费?不仅仅是电子邮件通知,这还不够!我不能只是关闭我的应用引擎实例,因为地图和其他地方的 api 凭据仍然可以产生费用!

4

1 回答 1

2

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

第一个是设置基于 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)}`;
};

依赖项:

{
 "name": "cloud-functions-billing",
 "version": "0.0.1",
 "dependencies": {
   "google-auth-library": "^2.0.0",
   "googleapis": "^52.0.0"
 }
}

然后您授予此 Cloud Function 的服务帐户的Billing Admin权限

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

于 2021-01-31T11:28:10.440 回答