Sionの技術ブログ

SREとして日々の学習を書いて行きます。twitterは@sion_cojp

GoでSlackに定常アラートが出たら、スレッドで自動コメントする

github.com

Slackに定常アラートが出たら、スレッドで自動コメントするGoのプログラムです。

今はアラート撲滅に着手出来ないけど、それまで周りに分かりやすいようにコメントを自動でしたい!という時に便利に使えるなぁと思って作りました。

動作

例えばこんなtomlを設定したら

$ vim examples/monitoring.toml
[[action]]
channel = "xxxxx"
in      = "test"
out     = "hoge"

testというワードに反応してスレッドにhogeを書いてくれます。

https://github.com/sioncojp/go-slack-auto-comment/blob/master/docs/go-slack-auto-comment01.png?raw=true


https://github.com/sioncojp/go-slack-auto-comment/blob/master/docs/go-slack-auto-comment02.png?raw=true

https://github.com/sioncojp/go-slack-auto-comment/blob/master/examples/monitoring-channel.toml

にサンプルがあります。

inは正規表現が使えたり、outは改行した書き方が出来ます。

またディレクトリ配下のtomlを全て読み込むので、チャンネルごとにtomlファイルを分離すると良いでしょう。

Usage

事前準備

Customize Slack -> API -> Your Apps -> Create New App

でAppを作り、

  • Bot UsersをONにし、Web版SlackからBOT ID
  • OAuth & PermissionsでBot User OAuth Access Token
  • BasicInformationにあるVerification Token

を取得してください。

動かしてみる

https://github.com/sioncojp/go-slack-auto-comment/tree/master/examples

を参考にconfigを設定してください。

Parameter Storeを使ってる場合は GitHub - sioncojp/tomlssm を使ってるので、 ssm://SSMのAlias名 と書けばIAM, KMS権限があればDecodeしてくれます。

### build
$ make build

### help
$ ./bin/go-slack-auto-comment help
NAME:
   go-slack-auto-comment - A new cli application

USAGE:
   go-slack-auto-comment [global options] command [command options] [arguments...]

VERSION:
   0.0.0

COMMANDS:
     help, h  Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --config-dir value, -c value  Load configuration *.toml in target dir
   --region value, -r value      Setting AWS region for tomlssm (default: "ap-northeast-1")
   --help, -h                    show help
   --version, -v                 print the version

### run。configが入ってるdirectoryを指定
$ ./bin/go-slack-auto-comment -c examples/
{"level":"info","ts":1562750380.530795,"caller":"go-slack-auto-comment/main.go:64","msg":"start..."}

実際にどう利用してる?

datadogからの通知、slowQueryの通知などに対して、設定してたりします f:id:sion_cojp:20190719145235p:plain

[[action]]
channel = "xxxxx"
in      = "^(Re-Triggered|Triggered|Warn):(.*)ECS cluster CPU reservation high.*"
out     = "autoscaleでCPUが下がらなければ、Terraformからcluster台数を増やしましょう"

課題

正規表現に癖があるので、そこが少し難しいです。

例えば

RDS Slow Log [test]

[IP: xxx.xxx.xxx.xxx]

'''
DELETE FROM `xxxx`
'''

にヒットさせようとしたら下記を書きます。

in = "^RDS Slow Log \\[test\\](?s)(.*)FROM `xxx`"

# (?s)(.*) ... 改行含む全ての文字

デバッグは容易ですが、さくっとやるにはサンプル数を増やしたり慣れる必要があります。

最後に

定常アラートをなくすことが大事なので、忘れずに。。