【问题标题】:Stop Google Cloud billing for specific services using Cloud Functions使用 Cloud Functions 停止对特定服务的 Google Cloud 计费
【发布时间】:2020-02-23 14:27:13
【问题描述】:

我需要开发一个 Cloud Function 脚本来停止对特定服务的计费,以防成本爆炸。

示例:想象一下,出于某种原因,Pub/Sub 的成本很高。

我的云功能必须检测到这个事件(我已经知道怎么做)并且只禁用这个服务计费。

有没有办法做到这一点?我看到了I can disable API Service。是否可以使用 Cloud Function 禁用发布/订阅 API 服务?有代码示例吗?它会禁用此服务的计费吗?或者更好的方法是删除有问题的发布/订阅?

【问题讨论】:

    标签: google-cloud-functions google-cloud-billing


    【解决方案1】:

    当您禁用某个 API 时,您可能会删除该 API 创建的所有资源,并且您还将禁用依赖于您正在禁用的 API 的其他 API。根据您在提到的特定情况下您在项目中使用的产品,如果您禁用 Pub/Sub API,您可能会禁用以下 API:

    cloudbuild.googleapis.com
    cloudfunctions.googleapis.com
    containerregistry.googleapis.com
    run.googleapis.com
    ...among others
    

    如果您意识到禁用 API(以及所有其他相关 API)可能会对您的项目造成风险和中断,如果您在生产中使用以下代码,请使用服务使用 API 的 disable 方法从Python 客户端库将工作将禁用 Dataflow API:

    from googleapiclient import discovery
    import google.auth
    
    def hello_world(request):
        credentials, project_id = google.auth.default()
        name = 'projects/[PROJECT-NUMBER-NOT-ID]/services/dataflow.googleapis.com'
        body = {'disableDependentServices': True,}
        service = discovery.build('serviceusage', 'v1', credentials=credentials, cache_discovery=False)
        request = service.services().disable(name=name, body=body)
        try:
            response = request.execute()
        except Exception as e:
            print(e)
        return "API disabled"
    

    通过检查您的活动日志,您应该会在触发云功能后看到与以下类似的消息:

    9:12 AM Completed: google.api.serviceusage.v1.ServiceUsage.DisableService [PROJECT-ID]@appspot.gserviceaccount.com has executed google.api.serviceusage.v1.ServiceUsage.DisableService on dataflow.googleapis.com
    9:12 AM google.api.serviceusage.v1.ServiceUsage.DisableService [PROJECT-ID]@appspot.gserviceaccount.com has executed google.api.serviceusage.v1.ServiceUsage.DisableService on dataflow.googleapis.com
    

    请注意,根据您使用的产品,这种禁用 API 的方法可能会停止与网络流量等相关的所有计费费用,但一般而言,Cloud SQL 实例中的存储定价等费用仍会继续产生。

    总的来说,我个人认为这不是最好的方法(因为如果您有一个生产中的应用程序并且其他 API 依赖于该 API,那么禁用 API 可能会非常危险),我通常会考虑使用预算和预算警报(也使用 Cloud Functions 和 Pub/Sub 等其他服务来接收通知)。查找文档中有关预算和预算警报 herehere 的所有相关部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 2020-03-19
      • 2018-07-11
      • 2020-03-15
      • 2018-11-18
      • 2017-08-03
      • 1970-01-01
      相关资源
      最近更新 更多