Disabling Billing on Google Cloud Using Google Cloud Function (Keyerror: 'data')

后端 未结 1 1568
礼貌的吻别
礼貌的吻别 2021-01-14 20:44

I am attempting to write a Google Cloud Function to set caps to disable usage above a certain limit. I followed the instructions here: https://cloud.google.com/billing/docs/

相关标签:
1条回答
  • 2021-01-14 21:10

    There seems to be an error in the code Google provided. I got it working when I changed the stop_billing function:

    def stop_billing(data, context):
        if 'data' in data.keys():
            pubsub_data = base64.b64decode(data['data']).decode('utf-8')
            pubsub_json = json.loads(pubsub_data)
            cost_amount = pubsub_json['costAmount']
            budget_amount = pubsub_json['budgetAmount']
        else:
            cost_amount = data['costAmount']
            budget_amount = data['budgetAmount']
        if cost_amount <= budget_amount:
            print(f'No action necessary. (Current cost: {cost_amount})')
            return    
        if PROJECT_ID is None:
            print('No project specified with environment variable')
            return
        billing = discovery.build('cloudbilling', 'v1', cache_discovery=False, )
        projects = billing.projects()
        billing_enabled = __is_billing_enabled(PROJECT_NAME, projects)
        if billing_enabled:
            __disable_billing_for_project(PROJECT_NAME, projects)
        else:
            print('Billing already disabled')
    

    The problem is that the pub/sub message provides input as a json message with a 'data' entry that is base64 encoded. In the testing functionality you provide the json entry without a 'data' key and without encoding it. This is checked for in the function that I rewrote above.

    0 讨论(0)
提交回复
热议问题