【GCE/GCP】Google Compute Engine hubotとslackを使ってサーバを起動・停止させる
前回の記事でGoogleComputeEngine(以下GCE)を使ってリモートからサーバを起動・停止させました。
今回はGCEの操作をサーバからではなくslackから操作をしたいと思います。
slackから操作させる理由としては複数人でサーバを操作する時に誰でも簡単に起動・停止などの操作ができるようになります。
また、誰にでもWEBコンソールやclound computeコマンドを公開しておくのはセキュリティ上よろしくないので、制限をかけておきたいという狙いもあります。
・・・と、もっともらしい事を言ってみましたが単純にHUBOTを使ってchatops的な事をたまにはやってみたかっただけです。。。
目次
HUBOTを作る slack側
まずはslackからhubotを作ります。公式サイトからhubotアプリをプロジェクトに追加します。hubotを作成するとtokenが取得できますので控えておきます。
HUBOTを作る サーバ側
hubotの準備
hubotのtokenが用意できればあとは作るだけです。
全体的な作り方は次のサイトが参考になりますので一式インストールを済ませます。
EPELリポジトリを追加→redisインストール&起動→coffee-scriptインストール→yemon generatorインストール。
$yo hubot コマンドで作成コンソールが立ち上がるので、画面に従って作ります。
動作確認
hubotを作ったら起動テストをします。tokenをexportしてhubotのhomeディレクトリにて下記コマンドを実行。
$HUBOT_SLACK_TOKEN=XXXXX ./bin/hubot –adapter slack
すると起動します。標準で簡単なスクリプトが入ってますので動作確認をします。slackよりhelloを通知。すると・・・
おおお。応答した!嬉しい!動作確認はOKですね。
foreverによるデーモン化
今回はhubotをデーモン化して稼動させますのでforeverをインストールして使います。
インストールはsudo npm install forever -gでできます。foreverが用意できたら次のような起動スクリプトを用意します。
run.sh
#!/bin/bash export HUBOT_SLACK_TOKEN=XXXXXXX forever start -c coffee node_modules/.bin/hubot --adapter slack
試しに起動するとforever listコマンドによりプロセスの起動が確認できると思います。
起動・停止スクリプトを用意
hubotとforeverの準備ができたので、あとは中身を作るだけです。
slackに応答しGCEに起動・停止を命令するcoffeeスクリプトを作ります。/botディレクトリ/scriptsに入れます。
googleCompute.coffee
module.exports = (robot) -> robot.hear /\[gce alert\](.*) stop/i, (msg) -> @exec = require('child_process').exec command = "perl /home/TEST/gce/controlGCE.pl start" + " " + msg.match[1] + " 1" #msg.send "Command: #{command}" @exec command, (error, stdout, stderr) -> msg.send error if error? msg.send stdout if stdout? msg.send stderr if stderr? robot.hear /\[gce ctrl\]status all/i, (msg) -> @exec = require('child_process').exec command = "perl /home/TEST/gce/controlGCE.pl status all" #msg.send "Command: #{command}" msg.send "ういーーーんんんんんん!ガチャン!!" @exec command, (error, stdout, stderr) -> msg.send error if error? msg.send stdout if stdout? msg.send stderr if stderr? robot.hear /\[gce ctrl\]stop (.*)/i, (msg) -> @exec = require('child_process').exec command = "perl /home/TEST/gce/controlGCE.pl stop" + " " + msg.match[1] + " 0" #msg.send "Command: #{command}" msg.send "ういーーーん停止します!ガチャン!!" @exec command, (error, stdout, stderr) -> msg.send error if error? msg.send stdout if stdout? msg.send stderr if stderr? robot.hear /\[gce ctrl\]start (.*)/i, (msg) -> @exec = require('child_process').exec command = "perl /home/TEST/gce/controlGCE.pl start" + " " + msg.match[1] + " 0" #msg.send "Command: #{command}" msg.send "ういーーーん開始します!ガチャン!!" @exec command, (error, stdout, stderr) -> msg.send error if error? msg.send stdout if stdout? msg.send stderr if stderr?
このスクリプトで呼び出されるプログラム(controlGCE.pl)は前回の記事で作成したものをそのまま使用可能です。slackから[gce ctrl]start XXXでサーバが開始、[gce ctrl]stop XXXでサーバが停止できます。こんな感じでslackから要求することで簡単にサーバの起動、停止ができるようになりました!。