-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.rb
More file actions
78 lines (62 loc) · 1.91 KB
/
lambda_function.rb
File metadata and controls
78 lines (62 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# frozen_string_literal: true
require 'slack-notifier'
require 'aws-sdk-costexplorer'
require 'net/http'
require 'uri'
require 'json'
EXCHANGE_RATE_URL = "https://openexchangerates.org/api/latest.json?app_id=#{ENV['OPENEXCHANGERATES_API_ID']}".freeze
def lambda_handler(*)
puts 'ok, called lambda handler'
message = fetch_cost
puts 'ok, fetched cost'
result = pretty_response(message)
puts 'ok, formatted response'
notify_slack(result)
puts 'ok, notify slack finished'
end
def fetch_cost
aws_client = Aws::CostExplorer::Client.new(region: 'us-east-1')
aws_client.get_cost_and_usage(
time_period: {
start: Date.new(Date.today.year, Date.today.month, 1).strftime('%F'),
end: Date.new(Date.today.year, Date.today.month, -1).strftime('%F')
},
granularity: 'MONTHLY',
metrics: ['AmortizedCost'],
group_by: [{ type: 'DIMENSION', key: 'SERVICE' }]
)
end
def pretty_response(message)
sum, cost_groups = summerize_cost_groups(message.dig(:results_by_time, 0, :groups), exchange_rate)
start_date = message.dig(:results_by_time, 0, :time_period, :start)
end_date = message.dig(:results_by_time, 0, :time_period, :end)
<<~"RESPONSE"
===========================
#{start_date} - #{end_date}
---------------------------
合計 : #{round(sum)}円
#{cost_groups.join("\n")}
===========================
RESPONSE
end
def exchange_rate
uri = URI.parse(EXCHANGE_RATE_URL)
res = Net::HTTP.get(uri)
JSON.parse(res)['rates']['JPY']
end
def summerize_cost_groups(cost_groups, rate)
sum = 0
formatted_cost_groups = cost_groups.map do |group|
amount = group.dig(:metrics, 'AmortizedCost', :amount).to_f * rate
sum += amount
"#{group.dig(:keys, 0)} : #{round(amount)}円"
end
[sum, formatted_cost_groups]
end
def round(amount)
amount.round
end
def notify_slack(result)
notifier = Slack::Notifier.new ENV['SLACK_WEBHOOK_URL']
notifier.ping result
end