概要
最も気軽な形でAWSの利用料金を確認したかったので、Hubotにそれをやらせた。
HubotにAWSの利用料金を問い合わせが出来るように。
AWS CLI を使えば簡単に実現できます。
AWSの利用料金を取得する
の前に、aws cliをインストールしておく必要があります。
aws cliを使ってcloudwatchのメトリクスで料金を取得。
jqでタイムスタンプでソートをかけ、最新の1件 だけ取得します。
bill.sh
# !/bin/bash
aws cloudwatch --region us-east-1 get-metric-statistics \
--namespace "AWS/Billing" \
--metric-name "EstimatedCharges" \
--dimensions "[{\"Value\":\"AmazonEC2\",\"Name\":\"ServiceName\"},{\"Value\":\"USD\",\"Name\":\"Currency\"}]" \
--period 60 \
--start-time `date -u -d '3 hours ago' +%Y-%m-%dT%TZ` \
--end-time `date -u +%Y-%m-%dT%TZ` \
--statistics "Maximum" \
| jq '.Datapoints | sort_by(.Timestamp) | reverse | .[0]'
この「bill.sh」と名付けたファイルを適当な場所に保存。
これを実行すると以下の形で返ってきます。
{
"Timestamp": "2015-05-25T01:08:00Z",
"Maximum": 10.25,
"Unit": "None"
}
Hubot側のスクリプト
あとは上記で作成したシェルスクリプトをHubotに実行させるだけ。
Node.jsで同期的にコマンドを実行できるようにする execsyncs というモジュールを使ったので、npmでインストールします。
npm install --save-dev execsyncs
```
スクリプトはこちら
上記で作成したシェルを実行。
```coffeescript:bill.coffee
execsyncs = require('execsyncs')
module.exports = (robot) ->
robot.respond /aws_bill/i, (msg) ->
result = '' + execsyncs('sh 「bill.sh」のパス')
obj = JSON.parse(result)
bill = '・・・$'+obj["Maximum"]
msg.send(bill)
```
# <i class="fa fa-dollar" style="font-size:1em;"></i> 実行結果
チャットツールは **ChatWork** を使ってます。

※「G」の顔を公開してしまっていた。。危うく消されるところだった。。