Code Monkey home page Code Monkey logo

consumption-cost-node's Introduction

page_type languages products description urlFragment
sample
javascript
azure
On-demand calculation of Azure consumption cost
consumption-cost-node

Deploy to Azure

On-demand calculation of Azure consumption cost

This sample demonstrates how to use the Azure billing commerce APIs to find consumption cost per subscription and resource-groups. The sample is implemented as an Azure Function.

The challenge

The Billing API and the Consumption API don't expose the cost of consumption. Instead, the API only exposes the ability to interact with past invoices or receive consumption quantities without cost data.

For example, you can find out that a subscription had five compute hours, but response does not include the cost per compute unit.

In addition, some functions are also not available for sponsored accounts.

Explaining the solution

The Azure Commerce APIs expose two functions:

  1. Resource usage: Returns consumption data for an Azure subscription

  2. Resource RateCard: Returns price and metadata information for resources used in an Azure subscription, primarily a price for each meter.

This sample exposes a wrapper around the billing APIs to create a simple interface for calculating costs.

There are four steps to extract the cost:

  1. Authenticate to Azure and obtain the Credentials object.
  2. Use the Credentials object to pull rateCards which are the rates set up for the given account (Rate is also called Meters).
  3. Use the Credentials object to pull Consumption data for each resource in the given subscription. Each consumption listing contains the Meter ID from the rate cards. Consumption provides you with a quantity per meterID.
  4. The last step is to multiply the rate value with the consumption quantity. The result of this calculation represents the cost.

Results can be filtered by resource group or resource tags. The Node.js code makes use of the Azure node.js SDKs.

Deploy the sample to Azure

The automated deployment provisions an Azure Storage account and an Azure Function in a Dynamic compute plan and sets up deployment from source control.

When you set up the Azure Function, you supply information and credentials to initialize the function. This is a one-time step. Make sure you have the following information available:

Name Type Description
clientId string Your service principal ID. If you don't already have one you may need to create a service principal.
clientSecret string Your service principal secret
tenantId string Your subscription tenant ID. You can find the tenant ID through the portal.
subscriptionId string Subscription ID to pull consumption info for. You can find the subscription ID through the portal
offerId string Must be specific code taken from Microsoft Azure Offer Details

The deployment template has a parameter named manualIntegration which controls whether or not a deployment trigger is registered with GitHub. Use true if you are deploying from the main Azure-Samples repo (which does not register a hook), or false not to register the hook. Since a value of false registers the hook with GitHub, the deployment will fail if you don't have write permissions to the repo. If you want to deploy it from your own repo, make sure your account is authorized with GitHub.com, otherwise the deployment fails with an authentication error.

Calling the function

Once the template is deployed, two functions are created under the App service:

  1. get-consumption-cost-node: The function logs in into Azure and pulls the rate and consumption data to calculate the actual cost based on these values.

  2. download-consumtion-cost: The function logs into Azure and uses the rate and consumption data to calculate a detailed report of the actual cost of each resource. The result is a .csv file which you can download from the function.

Optional parameters:

Name Type Description
detailed bool true if the consumption info should contain details. Relevant only for get-consumption-cost-node
filter string A way to limit results only to a specific resource instance info. For example: resource group, tags etc.
startDate Date Start time for the report. The date format is ECMAScript YYYY-MM-DDTHH:mm:ss.sssZ. Defaults to 24 hours ago
endDate Date End time for the report. The date format is ECMAScript YYYY-MM-DDTHH:mm:ss.sssZ. Defaults to now.
granularity string Values: Daily (default) or Hourly

The parameters are sent as json in the body of the POST request.

Executing the get-consumption-cost-node function

The following code listing is an example of calling the get-consumption-cost-node function (make sure to replace values with your deployment info):

curl -H "Content-Type: application/json" -X POST -d '{"filter":"<resource-group-name>","detailed":"true"}' https://<app-service-name>.azurewebsites.net/api/get-consumption-cost-node?code=<code>

If the function is called from a mobile client or a JavaScript web app, we recommend that you add authentication to your Function using App Service Authentication/Authorization. The API key is insufficient for security purposes since it can be discovered by sniffing traffic or decompiling the client app.

The function takes a considerable amount of time (in seconds) to execute because it performs three API calls: Log in, Get Rates and Get Consumption. A real-world scenario would include use of caching and user sessions to avoid multiple logins and calls to the API.

The response

Response from the wrapper is an object in the form of:

{ total: (Number, the total cost), details: (Key-Value pairs of resource and cost)}

For example:

{ total: 10.3, details: { res1:5, res2: 5.3}}

Executing the download-consumtion-cost function

The following code listing is an example of calling the download-consumtion-cost function. It will download a detailed report in a csv format (make sure to replace values with your deployment info):

curl -H "Content-Type: application/json" -X POST -d '{"filter":"<resource-group-name>","granularity":"Hourly"}' https://<app-service-name>.azurewebsites.net/api/download-consumtion-cost?code=<code>

If the function is called from a mobile client or a JavaScript web app, we recommend that you add authentication to your Function using App Service Authentication/Authorization. The API key is insufficient for security purposes since it can be discovered by sniffing traffic or decompiling the client app.

The function takes a considerable amount of time (in seconds) to execute because it performs three API calls: Log in, Get Rates and Get Consumption. A real-world scenario would include use of caching and user sessions to avoid multiple logins and calls to the API.

The response

Response from the wrapper is a csv file having the following columns:

  • name: meter name
  • rate: meter rate,
  • consumption: meter consumption
  • cost: cost of meter consumption
  • region: Azure region
  • meterDescription: textual description
  • usageStartTime: start time
  • usageEndTime: end time
  • resourceGroup

Learn more

consumption-cost-node's People

Contributors

craigshoemaker avatar itye-msft avatar jongio avatar microsoftopensource avatar msftgits avatar v-jiaodi avatar v-rajagt-zz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

consumption-cost-node's Issues

Optional parameters for currency and region

Please provide us with the following information:

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [X] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

n/a

Any log messages given by the failure

n/a

Expected/desired behavior

n/a

OS and Version?

n/a

Versions

n/a

Mention any other details that might be useful

I would like to add a PR to add currency and region to this function app. Now this is hard-coded into the common code.


Thanks! We'll be in touch soon.

Execution fails

Please provide us with the following information:

This issue is for a: (mark with an x)

- [X ] bug report -> please search issues before submitting
- [ ] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

Minimal steps to reproduce

Deploy from Azure-Samples
make request https://costcontrolfunction.azurewebsites.net/api/download-consumtion-cost?code=
with JSON body '{"filter":"[resourcegroup]","detailed":"true"}'

Any log messages given by the failure

{
"id": "d427fe1d-a5ed-454d-a47c-5a89c5f1c03d",
"requestId": "c54a8670-1f78-4112-ad88-243ce1c16734",
"statusCode": 500,
"errorCode": 0,
"message": "Exception while executing function: Functions.download-consumtion-cost -> One or more errors occurred. -> Error: Cannot find module 'ms-rest-azure'\n at Function.Module._resolveFilename (module.js:469:15)\n at Function.Module._load (module.js:417:25)\n at Module.require (module.js:497:17)\n at require (internal/module.js:20:19)\n at Object. (C:\home\site\wwwroot\common\commerceUtils.js:1:83)\n at Module._compile (module.js:570:32)\n at Object.Module._extensions..js (module.js:579:10)\n at Module.load (module.js:487:32)\n at tryModuleLoad (module.js:446:12)\n at Function.Module._load (module.js:438:3)"
}

Expected/desired behavior

The response as described in the documents,
{ total: (Number, the total cost), details: (Key-Value pairs of resource and cost)}

OS and Version?

Windows 7, 8 or 10. Linux (which distribution). macOS (Yosemite? El Capitan? Sierra?)
Tried on windows 10 with Postman
Ubuntu WSL

Versions

Pulled from master branch

Mention any other details that might be useful

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.