LoginSignup
25
23

More than 5 years have passed since last update.

【Hubot】AWSの利用料金を聞くと答えてくれるようにした

Last updated at Posted at 2015-05-25

 概要

最も気軽な形で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

スクリプトはこちら
上記で作成したシェルを実行。

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)

 実行結果

チャットツールは ChatWork を使ってます。

bill.png

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

25
23
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25
23