trex tiab
trex tiab

Reputation: 33

How to get aws billing for previous day using lambda function?

exports.handler = (event, context, callback) => {
    // TODO implement


var AWS = require('aws-sdk');
var cloudwatch = new AWS.CloudWatch();
var params = {
              MetricName: 'EstimatedCharges',
              Namespace: 'AWS/Billing',
            };
            cloudwatch.listMetrics(params, function(err, data) {
              if (err) console.log(err, err.stack); // an error occurred
              else     console.log("success",JSON.stringify(data));           // successful response
            });

callback(null, 'Hello from Lambda');
};

Upvotes: 0

Views: 886

Answers (1)

Dvir669
Dvir669

Reputation: 8590

I would suggest using the Cost Explorer API. You have the JS SDK to use: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CostExplorer.html

From the examples:

var params = {
  Filter: { /* Expression */
    And: [
      /* recursive Expression */,
      /* more items */
    ],
    Dimensions: {
      Key: AZ | INSTANCE_TYPE | LINKED_ACCOUNT | OPERATION | PURCHASE_TYPE | REGION | SERVICE | USAGE_TYPE | USAGE_TYPE_GROUP | RECORD_TYPE | OPERATING_SYSTEM | TENANCY | SCOPE | PLATFORM | SUBSCRIPTION_ID | LEGAL_ENTITY_NAME | DEPLOYMENT_OPTION | DATABASE_ENGINE | CACHE_ENGINE | INSTANCE_TYPE_FAMILY,
      Values: [
        'STRING_VALUE',
        /* more items */
      ]
    },
    Not: /* recursive Expression */,
    Or: [
      /* recursive Expression */,
      /* more items */
    ],
    Tags: {
      Key: 'STRING_VALUE',
      Values: [
        'STRING_VALUE',
        /* more items */
      ]
    }
  },
  Granularity: DAILY | MONTHLY,
  GroupBy: [
    {
      Key: 'STRING_VALUE',
      Type: DIMENSION | TAG
    },
    /* more items */
  ],
  Metrics: [
    'STRING_VALUE',
    /* more items */
  ],
  NextPageToken: 'STRING_VALUE',
  TimePeriod: {
    End: 'STRING_VALUE', /* required */
    Start: 'STRING_VALUE' /* required */
  }
};
costexplorer.getCostAndUsage(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Upvotes: 1

Related Questions