Search code examples
ibm-cloudopenwhiskibm-cloud-functions

Trying to run code in IBM Cloud Functions


I have following code I am trying to run in IBM function to get billing data out:

iam_token = 'Bearer eyJraWQiOiIyMDE3MTAzMC0wM****'
def processResourceInstanceUsage(account_id, billMonth):
    METERING_HOST = "https://metering-reporting.ng.bluemix.net"
    USAGE_URL = "/v4/accounts/"+account_id + \
        "/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"

    url = METERING_HOST+USAGE_URL
    headers = {
        "Authorization": "{}".format(iam_token),
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    response = requests.get(url, headers=headers)
    print("\n\nResource instance usage for first 100 items")
    return response.json()

processResourceInstanceUsage('*****', '11')

For some reason, I keep on getting 201 unauthorized error. I tried creating iam_token many times. It still gives the same error.


Solution

  • There are few things that should be taken care in the code you provided.

    • The month you are passing is wrong. It should be in YYYY-MM format.

    • account_id should be the id next to your Account name when you run ibmcloud target

    • For IAM token, run this command ibmcloud iam oauth_tokens. If you want to generate access token using your Platform API Key, refer to this link. The word Bearer is not required as this is not an authorization token.

    Once you have all this in place, create an IBM Cloud function (Python 3), add the below code, pass the account_id and token and invoke the action to see the result . IBM Cloud function expects a dictionary as an input/parameter and JSON as response

    import sys
    import requests
    
    def main(dict):
        METERING_HOST="https://metering-reporting.ng.bluemix.net"
        account_id="3d40d89730XXXXXXX"
        billMonth="2018-10"
        iam_token="<IAM_TOKEN> or <ACCESS_TOKEN>"
        USAGE_URL="/v4/accounts/"+account_id+"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
    
        url=METERING_HOST+USAGE_URL
        headers = {
            "Authorization": "{}".format(iam_token),
            "Accept": "application/json",
            "Content-Type": "application/json"
        }
        response=requests.get(url, headers=headers)
        print ("\n\nResource instance usage for first 100 items")
        return { 'message': response.json() }
    

    This worked for me and returned a JSON with region-wise billing data.

    Reference: https://stackoverflow.com/a/52333233/1432067