0

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.

NoviceMe
  • 3,126
  • 11
  • 57
  • 117
  • Does your code work when run standalone? How do you create the action, how do you invoke it? Please add details – data_henrik Dec 18 '18 at 05:50
  • Are you getting a 201 response or an unauthorized error? That status code doesn't usually got with that error. – nitind Dec 18 '18 at 06:52

1 Answers1

2

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

Vidyasagar Machupalli
  • 2,737
  • 1
  • 19
  • 29