EC2インスタンスにSSH接続せずに任意のLinuxコマンドを実行する
AWS Systems Manager(通称 SSM)のRun Commandを使うと、EC2インスタンスに対しての様々な管理タスクの実行を自動化したり、多くのインスタンスにたいして大規模に実行したりできます。
管理タスクはコマンドドキュメントという形で定型化されていて、このうちの AWS-RunShellScript
を使うと、任意のLinuxコマンドを、外部から実行することができます。
設定
必要なの操作は、次の2つです。
EC2インスタンスでSSMエージェントを起動
AmazonLinux2であればデフォルトでインストールされているため、操作は不要です。 そうでない場合、SSMエージェントをインストールしておきます。
systemctl status amazon-ssm-agent
で実行中のインスタンスがSSMへ接続できていることを確認します。
[ec2-user@ip-10-0-0-108 ~]$ sudo systemctl status amazon-ssm-agent ● amazon-ssm-agent.service - amazon-ssm-agent Loaded: loaded (/usr/lib/systemd/system/amazon-ssm-agent.service; enabled; vendor preset: enabled) Active: active (running) since Wed 2020-08-12 13:57:27 UTC; 4s ago Main PID: 1536 (amazon-ssm-agen) CGroup: /system.slice/amazon-ssm-agent.service └─1536 /usr/bin/amazon-ssm-agent Aug 12 13:57:29 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [MessageGatewayService] listening reply. Aug 12 13:57:29 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [LongRunningPluginsManager] There are no long running plugins currently getting executed - skipp...healthcheck Aug 12 13:57:29 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [StartupProcessor] Executing startup processor tasks Aug 12 13:57:30 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [StartupProcessor] Write to serial port: Amazon SSM Agent v2.3.1319.0 is running Aug 12 13:57:30 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [StartupProcessor] Write to serial port: OsProductName: Amazon Linux Aug 12 13:57:30 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [StartupProcessor] Write to serial port: OsVersion: 2 Aug 12 13:57:30 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [MessageGatewayService] Opening websocket connection to: wss://ssmmessages.ap-northeast-1.amazon...tream=input Aug 12 13:57:30 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [MessageGatewayService] Successfully opened websocket connection to: wss://ssmmessages.ap-northe...tream=input Aug 12 13:57:30 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [MessageGatewayService] Starting receiving message from control channel Aug 12 13:57:30 ip-10-0-0-108.ap-northeast-1.compute.internal amazon-ssm-agent[1536]: 2020-08-12 13:57:27 INFO [MessageGatewayService] [EngineProcessor] Initial processing Hint: Some lines were ellipsized, use -l to show in full.
EC2インスタンスに必要な権限を与える
EC2インスタンスに対して RunCommand が使えるように、EC2に対して必要な権限を割り当てるために、インスタンスロールを作成します。
インスタンスロールには AmazonSSMManagedInstanceCore
AWS管理ポリシーを適用します。