slackからhubot経由でEC2インスタンスにコマンドを発行し結果を返したい。
以前は力技のsshで実施していたのをEC2 run commandに置き換えてみた。
Run Commandについて
-
send-command
を実行しても結果は返ってこない - 実行結果を知るには
command id
を元にlist-command-invocations
を叩きStatusを確認する - StatusがSuccessになるまでポーリングする必要がある。
- nodeの場合は
bluebird-retry
でポーリングする様にできそう
coffeescript のサンプル
- hubotからコマンド結果表示も確認済み
- bluebird-retryで
checkStatus
関数を必要なだけ呼び出して結果を取得する -
hostname
コマンドを発行して結果を返すだけの例
AWS = require('aws-sdk')
AWS.config.region = 'ap-northeast-1'
ssm = new AWS.SSM()
Promise = require('bluebird')
retry = require('bluebird-retry')
Promise.promisifyAll(ssm)
checkStatus = (id) ->
params =
CommandId: id
Details: true
ssm.listCommandInvocationsAsync(params).then (res, err) ->
throw err if err
if res.CommandInvocations[0].Status == 'Success'
return res
else
throw new Error "#{res.CommandInvocations[0].Status}"
params =
DocumentName: 'AWS-RunShellScript'
InstanceIds: ['i-***']
Parameters:
commands: ['hostname']
ssm.sendCommandAsync(params).then (sendRes, sendErr) ->
if sendErr
console.log sendErr
throw sendErr
else
console.log sendRes
sendRes
.then (data) ->
retry(checkStatus, { args: [data.Command.CommandId], max_tries: 5, interval: 1000 })
.then (data) ->
console.log "SUCCESS:", JSON.stringify(data, null, 2)
.caught (err) ->
console.log "ERROR:", JSON.stringify(err, null, 2)
.catch (err) ->
console.log "ERROR:", JSON.stringify(err, null, 2)