Aws-sdk-js: Call to CostExplorer API after AssumeRole is not as expected

Created on 13 Jan 2019  路  6Comments  路  Source: aws/aws-sdk-js

Environment: Lambda - Nodejs 8.10

Background:

Here is my code:

var AWS = require('aws-sdk');

exports.handler = (event, context, callback) => {
  AWS.config.update({ region: 'us-east-1' });
  var sts = new AWS.STS();
  var params = {
    DurationSeconds: 3600,
    RoleArn: "arn:aws:iam::myid1234:role/my-role", // here is a role that I made for account A from account B
    RoleSessionName: "bob"
  };
  sts.assumeRole(params, function (err, data) { //switch to role X in account B
    if (err) return console.log(err, err.stack); // an error occurred
    else console.log(data);
    var params = {
      TimePeriod: {
        Start: '2019-01-01',
        End: '2019-01-31',
      },
      Granularity: 'MONTHLY',
      Metrics: ['BLENDED_COST'],
    };
    var costexplorer = new AWS.CostExplorer();
    costexplorer.getCostAndUsage(params, function (err, data) { // here I want to get cost usage for account B
      if (err) console.log(err);
      let { Amount, Unit } = data.ResultsByTime[0].Total.BlendedCost;
      Amount = Number(Amount).toFixed(2);
      console.log(Amount) // but this amount from account A not B :(

      callback(null);
    });
  });
  callback(null)

};

Could you please help me to fix this, thank you a lot!

guidance

Most helpful comment

@bugb

Refer to the documentation on the Lamba Execution Environment for details on how to closely match your local and deployed environments.

There is also additional documentation on Testing and Debugging which may be useful for you.

If you have Lambda specific questions, that are not SDK issues, you can also ask for guidance on Stack Exchange, or the AWS Developer Forum.

All 6 comments

@bugb,

data returned from assumeRole needs to be used to set the credentials for the costexplorer client, otherwise, that client will just use the same credentials as the rest of the Lambda function.

Once data is returned, you could do either of the following:

Update the global config (using Account B credentials for any clients created thereafter):

AWS.config.update({
  accessKeyId: data.Credentials.AccessKeyId,
  secretAccessKey: data.Credentials.SecretAccessKey,
  sessionToken: data.Credentials.SessionToken
});
var costexplorer = new AWS.CostExplorer();

Or you could use the returned credentials only for costexplorer:

const accountBCredentials = new AWS.Credentials(data.Credentials.AccessKeyId, data.Credentials.SecretAccessKey, data.Credentials.SessionToken));
const costexplorer = new AWS.CostExplorer(accountBCredentials);

@srchase thank you a lot for your effort I will try this!

@srchase Thank you a lot, it work like a charm, but I need to manual create the new policy for access Cost Explorer API, because the default Billing access policy does not provide us permission to call to Cost explorer API, it like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "aws-portal:*Billing",
                "awsbillingconsole:*Billing",
                "aws-portal:*Usage",
                "awsbillingconsole:*Usage",
                "aws-portal:*PaymentMethods",
                "awsbillingconsole:*PaymentMethods",
                "budgets:ViewBudget",
                "budgets:ModifyBudget",
                "cur:*",
                "ce:*"
            ],
            "Resource": "*"
        }
    ]
}

The line that I added is "ce:*".

By the way, I found it is very hard to debug lambda function because the environment for Lambda and environment in my computer is too different, could you please suggest me any approach to deal with it?

@bugb

Refer to the documentation on the Lamba Execution Environment for details on how to closely match your local and deployed environments.

There is also additional documentation on Testing and Debugging which may be useful for you.

If you have Lambda specific questions, that are not SDK issues, you can also ask for guidance on Stack Exchange, or the AWS Developer Forum.

@srchase Thank you a lot!

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs and link to relevant comments in this thread.

Was this page helpful?
0 / 5 - 0 ratings