LoginSignup
2

More than 5 years have passed since last update.

Amazon EC2 Run Commandでコマンド発行から結果出力まで1アクションで実施

Last updated at Posted at 2017-01-20

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)

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
2