LoginSignup
9
8

More than 5 years have passed since last update.

AWS Lambdaを使って、MySQLのコネクション数増大時にSlackにprocesslistを通知する

Posted at

やりたいこと

CloudWatch で MySQL の connection 数や CPU 使用率などを監視している状況で、警告が発生したときに即座に processlist を取得したい.

やりかた

以下のような Lambda function を作成し、Event source として(RDS connection alertなどの通知先に設定した)適当な SNS Topic に対して subscribe しておけば良い.

package.json
:
    "dependencies": {
    "mysql": "2.10.2",
    "slack-node": "0.1.7"
  },
:
index.js
var Slack = require('slack-node');
var Mysql = require('mysql');

exports.handler = function(event, context) {
    var post = function(text, context){
        var slack = new Slack();
        slack.setWebhook("https://hooks.slack.com/services/xxxxxxxxxxxxxxxxxx");
        slack.webhook({
            channel: "#healthcheck",
            username: "CloudWatch",
            text: text
        }, function(err, response){
            if (err) {
                console.error(err);
                console.log(response);
                context.fail('failure slack post');
            } else {
                context.succeed();
            }
        });
    };

    var connection = Mysql.createConnection({
        host     : 'xxxxxxxxx.xxxxxxxxxxxxxx.ap-northeast-1.rds.amazonaws.com',
        user     : 'xxxxxxxxx',
        password : 'xxxxxxxxx',
        database : 'xxxxxxxxx'
    });

    connection.connect();

    connection.query('show processlist;', function(err, rows, fields) {
        if (err) throw err;

        // ここで適当にフォーマットしてやるとみやすいかもしれない
        var text = JSON.stringify(rows);
        post(text, context);
    });

};

実行イメージ

Slack.png

注意点

VPC 構成の DB に対してこれをやる場合は、Slack への外部アクセスをおこなうため、private subnet & NAT Gateway (もしくは NAT インスタンス) な環境で Lambda function を実行するよう設定してやる必要がある. public subnet & Internet Gateway 環境ではダメ.

参考

9
8
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
9
8