Notify Slack of AWS bills daily with Lambda for Ruby

When I googled the precedent cases, there were many examples of Python, so the minimum setting memo when I did it by hand with [Ruby] doc.

1. Create AWS Lambda with runtime Ruby

Create with a button click from the Lambda console screen on the Web

--Runtime with Ruby 2.7 --Give ce: GetCostAndUsage to the execution role -[Cost Explorer permissions will appear if you enable them as root] ce_auth should be

2. Write the acquisition process in Ruby

lambda_functions.rb


require 'aws-sdk'
require 'net/http'
require 'uri'
require 'json'

#Lambda entry point
def lambda_handler(event:, context:)
  fetch_cost
    .then { |response| pretty_response(response) }
    .then { |message| notify_slack(message) }

  #Return as HTTP response
  { statusCode: 200, body: 'ok' }
end

#Get billing information
def fetch_cost(time = Time.now)
  #I have already authenticated, so I don't need credentials(See below)
  client = Aws::CostExplorer::Client.new(region: 'us-east-1')

  client.get_cost_and_usage(
    time_period: {
      start: Time.local(time.year, time.month, 1).strftime('%F'),
      end: time.strftime('%F'),
    },
    granularity: 'MONTHLY',
    metrics: ['AmortizedCost'],
    group_by: [ { type: "DIMENSION",key: 'SERVICE' }]
  )
end

#Formatting API return values
def pretty_response(res)
  #abridgement. Appropriately
end

#Post to Slack
def notify_slack(message)
  #incoming Webhook Set the set URL in the environment variable
  uri = URI.parse(ENV['SLACK'])
  params = { text: message }
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  res = http.start do
    request = Net::HTTP::Post.new(uri.path)
    request.set_form_data(payload: params.to_json)
    http.request(request)
  end

  unless res.is_a? Net::HTTPSuccess
    raise 'Failed POST Slack'
  end

  res
end

Click here for the full source (gist). What you are doing is almost the same as [Getting process in Python of the precedent case of Developers.IO] [class method].

If you want to change what you want to see, you can change [what to pass to ʻAws :: CostExplorer :: Client # get_cost_and_usage] [api_doc] or change pretty_response`.

3. Set startup time in CloudWatch Events

  1. "Add trigger" on the Lambda function setting screen
  2. Select "Event Bridge (CloudWatch Events)"
  3. Can be set in the same way as cron (Reference: [AWS_Cron expression wildcard] cron)

I was addicted to IAM certification

I didn't know where to get the IAM authentication when executing the Lambda function, but if I'm using the aws-sdk gem, I've done it without doing anything. The reason is as follows.

-[In the Lambda execution environment, the environment variables (ʻENV) are set to ʻAWS_ACCESS_KEY_ID and ʻAWS_SECRET_ACCESS_KEY`] ENV. -[aws-sdk gem reads the above environment variables without permission and authenticates] rdoc. ――So you don't have to do anything.

At first I didn't know this, so it was useless because I made an IAM separately from the role for execution and used that access key and path.

Referenced web page

--[I tried to notify Slack of the billing amount for each AWS service every day --Developers.IO] classmethod --Python example. It feels like I ported this to Ruby. -[Building Lambda Functions with Ruby-AWS Lambda Developer Guide] doc --Official Ruby documentation for AWS Lambda. --[Using AWS Lambda Environment Variables --AWS Lambda Developer Guide] ENV --About Lambda environment variables. Many are set from the beginning.

Recommended Posts

Notify Slack of AWS bills daily with Lambda for Ruby
Regularly notify Slack of articles stocked on Qiita with AWS Lambda + DynamoDB + CloudWatch
Create and integrate Slack App and AWS Lambda (for ruby) in 30 minutes
Get S3 object size with AWS SDK for Ruby
Build AWS Lambda with Quarkus
Install gem in Serverless Framework and AWS Lambda with Ruby environment
Try AWS Lambda Runtime Interface Emulator with Docker Desktop for M1
Try running SlackBot made with Ruby x Sinatra on AWS Lambda
Create a periodical program with Ruby x AWS Lambda x CloudWatch Events
Learn AWS for free with LocalStack
Impressions of making BlackJack-cli with Ruby
Get a list of S3 files with ListObjectsV2Request (AWS SDK for Java)
[Ruby] Explanation for beginners of iterative processing with subscripts such as each_with_index!
I tried to visualize the access of Lambda → Athena with AWS X-Ray
Getting Started with Ruby for Java Engineers
AWS Lambda with Java starting now Part 1
Extract a part of a string with Ruby
Explanation of Ruby on rails for beginners ①
Get a list of Qiita articles for a specific user with Ruby + Qiita API v2
Send a notification to slack with the free version of sentry (using lambda)
Try local development of AWS (S3, DynamoDB) with AWS SDK for JavaScript and Docker