過去記事たち
EC2 Run Command (Linux)を使ってみた。
EC2 Run Command (Linux)のRunRemoteScriptを使ってみた。
やりたいこと
・別サーバーにあるファイルの中身をのぞき見する。
単純にこれだけ。sftp使って転送とかでもいいけど、せっかくだしRunCommandを使って取ってみる。 Command部分を変更すればなんでもできるよ。
準備
boto3とか入っていると想定。
profileは実行したいサーバーの権限があるものをaws configureで設定済み。
のぞき見したいinstanceにはssmの権限のあるIAMロールを割り振り済み。わからなければ過去記事ミテネ
Pythonはこんなふうに書いてみた。
import boto3
import time
import sys
from logging import getLogger, StreamHandler, DEBUG, Formatter
from datetime import datetime
args = sys.argv
command = "cat /root/hogehoge.txt"
instance_id = args[1]
ssm = boto3.client('ssm')
##Command投入
r = ssm.send_command(
InstanceIds = [instance_id],
DocumentName = "AWS-RunShellScript",
Parameters = {
"commands": [
command
]
}
)
command_id = r['Command']['CommandId']
## 処理終了待ち
time.sleep(2)
res = ssm.list_command_invocations(
CommandId = command_id,
Details = True
)
invocations = res['CommandInvocations']
status = invocations[0]['Status']
if status == "Failed":
print("Command実行エラー")
## 結果格納
account = invocations[0]['CommandPlugins'][0]['Output']
使い方は引数にinstance idをあげる。
python3 hogehoge.py i-xxxxxxxxxxx
簡単な解説
r = ssm.send_command(
InstanceIds = [instance_id],
DocumentName = "AWS-RunShellScript",
Parameters = {
"commands": [
command
]
}
)
Commandを実行させる。 instanceIDで指定したinstanceにRunShellScriptで実行させますよってそのまま書いておけば大丈夫。 複数あるなら列挙すればおk。
command_id = r['Command']['CommandId']
返り値にはCommandIDが入っている。このCommandIDでコマンドが終了したかどうかチェックしたり、表示を確認するために使ったり出来る。
time.sleep(2)
即時で行うと、次で参照できずエラーになるので、とめている。
invocations = res['CommandInvocations'] status = invocations[0]['Status']
ステータス取ってきてる。終了したら「Success」か「Failed」が入る。それ意外だと処理中と思って良いのでループさせて再取得してもいい。 エラー処理はいろいろ書いてたけど、都合上消したのでしっかり変えてね。
account = invocations[0]['CommandPlugins'][0]['Output']
コマンドの実行結果がこれに返ってくる。今回だとhogehoge.txtの中身がでてくるよ。


