シェルスクリプトをSSMのドキュメントに登録して実行する
目的
Lambdaを使ってEC2上でコマンド実行したい
実現案
Lambda --> SSM --> EC2
SSMが実行するアクションを「ドキュメント」として定義できる。
ドキュメントにはいくつかのタイプがあり、コマンドを使用できるRun Command
を使えば実現できそう。
やってみた
SSMのメニューでドキュメント
を選択後、Create command or session
を選択。
項目 | 値 |
---|---|
名前 | 任意の名前 |
ターゲットタイプ | /AWS::EC2::Instance |
ドキュメントタイプ | コマンドドキュメント |
コンテンツ | YAML |
内容は以下で設定。
--- schemaVersion: "2.2" description: "Command Document Example YAML Template" mainSteps: - action: "aws:runShellScript" name: "hostname" inputs: runCommand: - "hostname" - "ls -l /etc"
hostname
やls
を試す内容です。
以上の内容で作成する。
自己所有で作成したドキュメントが確認できました。
作成したドキュメントを実行すると以下の結果が得られました。
ip-10-0-1-188 total 1508 -rw-r--r-- 1 root root 5090 Feb 25 2016 DIR_COLORS -rw-r--r-- 1 root root 5725 Feb 25 2016 DIR_COLORS.256color -rw-r--r-- 1 root root 4669 Feb 25 2016 DIR_COLORS.lightbgcolor -rw-r--r-- 1 root root 94 Aug 17 2017 GREP_COLORS drwxr-xr-x 3 root root 4096 Nov 16 2018 NetworkManager drwxr-xr-x 4 root root 4096 Nov 16 2018 X11 drwxr-xr-x 4 root root 4096 Nov 16 2018 acpi -rw-r--r-- 1 root root 44 Jan 27 15:37 adjtime -rw-r--r-- 1 root root 1512 Jan 12 2010 aliases -rw-r----- 1 root smmsp 12288 Nov 16 2018 aliases.db drwxr-xr-x 2 root root 12288 Jan 20 11:06 alternatives drwxr-xr-x 3 root root 4096 Nov 16 2018 amazon -rw------- 1 root root 541 Sep 28 2016 anacrontab -rw-r--r-- 1 root root 148 Jan 6 2012 asound.conf -rw-r--r-- 1 root root 1 Aug 16 2016 at.deny drwxr-x--- 3 root root 4096 Nov 16 2018 audisp drwxr-x--- 3 root root 4096 Nov 16 2018 audit drwxr-xr-x 2 root root 4096 Jan 20 10:35 bash_completion.d -rw-r--r-- 1 root root 2681 Sep 10 2014 bashrc drwxr-xr-x 2 root root 4096 Jan 20 10:28 blkid -rw-r--r-- 1 root root 905 Feb 28 2014 cgconfig.conf -rw-r--r-- 1 root root 234 Feb 28 2014 cgrules.conf -rw-r--r-- 1 root root 131 Feb 28 2014 cgsnapshot_blacklist.conf drwxr-xr-x 2 root root 4096 Mar 17 2015 chkconfig.d drwxr-xr-x 4 root root 4096 Nov 16 2018 cloud drwxr-xr-x 2 root root 4096 Jan 20 10:48 containerd drwxr-xr-x 2 root root 4096 Jan 27 13:52 cron.d drwxr-xr-x 2 root root 4096 Nov 16 2018 cron.daily -rw------- 1 root root 0 Sep 28 2016 cron.deny drwxr-xr-x 2 root root 4096 Jan 6 2012 cron.hourly drwxr-xr-x 2 root root 4096 Jan 6 2012 cron.monthly drwxr-xr-x 2 root root 4096 Jan 6 2012 cron.weekly -rw-r--r-- 1 root root 457 Jan 6 2012 crontab -rw-r--r-- 1 root root 1602 Sep 10 2014 csh.cshrc -rw-r--r-- 1 root root 794 Sep 10 2014 csh.login drwxr-xr-x 4 root root 4096 Jan 20 10:27 dbus-1 drwxr-xr-x 2 root root 4096 Jan 20 10:27 default drwxr-xr-x 2 root root 4096 Nov 16 2018 depmod.d drwxr-x--- 4 root root 4096 Nov 16 2018 dhcp drwxr-xr-x 2 root root 4096 Jan 20 10:48 docker -rw-r--r-- 1 root root 519 May 6 2019 dracut.conf drwxr-xr-x 2 root root 4096 Jan 20 10:27 dracut.conf.d -rw-rw-r-- 1 root disk 0 Jan 5 2012 dumpdates -rw-r--r-- 1 root root 119 Oct 1 2018 e2fsck.conf ---Output truncated---
hostname
コマンドとls
コマンドの結果が出てますね。
S3に出力するオプションを有効にすると、出力結果のファイルが作成されていました。