インスタンス数が増えるほど、手作業の設定変更はヒューマンエラーのリスクを高めます。特にマルチAZ冗長構成では、AZ間の設定差異がフェイルオーバー時の障害原因になります。
この記事では、AWS SSM Document(AWS Systems Manager ドキュメント)を使って複数AZのEC2インスタンスに同じ手順を統一適用する方法を解説します。カスタムDocumentのYAML定義・登録手順から、Run Commandによる一括実行・バージョン管理まで、実践的な手順を顺番に説明します。
この記事のポイント
・SSM DocumentはEC2への手順をYAMLで定義し再利用できる「実行設計図」
・create-documentコマンドで登録しsend-commandで複数AZに一括適用できる
・ドキュメントのバージョン管理により手順変更を安全にロールバックできる
・タグフィルターにMaxConcurrencyを組み合わせて段階展開リスクを制御できる
でも安心してください。プロのエンジニアはコマンドを暗記していません。
「現場で使える型」を効率よく使いこなしているだけです。
AWS SSM Documentとは|EC2への手順を「実行設計図」として管理する仕組み
AWS SSM Document(以下、Document)は、AWS Systems Managerがインスタンス上で実行する「手順」をJSONまたはYAML形式で定義したテンプレートファイルです。Run Command・Automation・State Managerなど複数のSSM機能がこのDocumentを参照して動作します。マルチAZ構成で特に重要なのは「1つのDocumentを複数AZの全インスタンスに適用できる」点です。手順をファイルとして管理するため、一度作った手順をGitなどのバージョン管理ツールで履歴管理することもできます。
AWSが提供するマネージドDocument(AWS-RunShellScriptやAWS-UpdateSSMAgent等)もありますが、自社定義のカスタムDocumentを作成することで、辺りのパラメータや規格化された手順を定義できます。
SSM Documentの4種類と用途の違い
Documentには複数のタイプがあります。マルチAZ冠長設計で主に使うのはCommandとAutomationの2種類です。・Command:インスタンス上でシェルコマンドを直接実行。Run Commandが使用。設定変更・Packageインストールに適する
・Automation:複数のAWSリソース操作(EC2白動停止・AMI作成等)をワークフローとして定義
・Session:Session Managerのセッション設定(タイムアウト・ログ先等)を定義
・Policy:State Managerと組み合わせて期待構成を継続的に適用する
この記事では、最も使用頻度の高いCommandドキュメントを中心に解説します。
カスタムSSM DocumentをYAMLで作成する方法
1. YAMLのスキーマ構造を理解する
CommandタイプのDocumentの基本構造です。必須項目はschemaVersion・description・mainStepsの3つです。# nginx-install.yaml --- カスタムDocument定義 schemaVersion: '2.2' description: 'Install and enable Nginx on Amazon Linux 2023' parameters: NginxPackage: type: String default: nginx description: Package name to install allowedValues: - nginx mainSteps: - action: 'aws:runShellScript' name: installNginx inputs: runCommand: - 'dnf install -y {{ NginxPackage }}' - 'systemctl enable --now nginx' - 'systemctl status nginx --no-pager' timeoutSeconds: 120
2. aws ssm create-documentで登録する
YAMLファイルを準備したら、AWS CLIでDocumentを登録します。# Documentを登録する $ aws ssm create-document --name "MyNginxInstall" --document-type "Command" --document-format "YAML" --content file://nginx-install.yaml --region ap-northeast-1 { "DocumentDescription": { "Hash": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2", "HashType": "Sha256", "Name": "MyNginxInstall", "Owner": "123456789012", "CreatedDate": "2026-10-10T09:00:00.000000+09:00", "Status": "Active", "DocumentVersion": "1", "DefaultVersion": "1", "DocumentType": "Command", "SchemaVersion": "2.2" } } # Documentの一覧確認 $ aws ssm list-documents --filters '[{"Key":"Owner","Values":["Self"]}]' --query 'DocumentIdentifiers[*].[Name,DocumentVersion,Status]' --output table ----------------------------------------------------- | ListDocuments | +---------------------+--------+------------------+ | MyNginxInstall | 1 | Active | +---------------------+--------+------------------+
3. バージョン管理とデフォルトバージョンの切り替え
Documentの内容を変更する場合は、既存のDocumentを更新して新バージョンを作成できます。本番に適用するデフォルトバージョンを明示的に切り替えるまで、既存インスタンスには古い手順が適用され続けます。このボールを考慮して、本番適用前に必ず検証環境で新バージョンをテストしてください。# Documentを新バージョンで更新する $ aws ssm update-document --name "MyNginxInstall" --document-version "\$LATEST" --document-format "YAML" --content file://nginx-install-v2.yaml # デフォルトバージョンをv2に切り替える $ aws ssm update-document-default-version --name "MyNginxInstall" --document-version "2" { "Description": { "Name": "MyNginxInstall", "DefaultVersion": "2" } }
複数AZのEC2にDocumentを一括適用する方法|Targetsでタグ指定する
1. ターゲット指定の3つのパターン
send-commandのターゲット指定には3つの方法があります。マルチAZ冗長構成では、EC2タグで環境を識別する方法が最も运用しやすいです。・インスタンスID指定:タEC2の実障数が少ない暑れ向き。導入時のテストなど
・タグ指定(全EC2用途):疲定数の多い本番環境で正式に使う
・リソースグループ:EC2 FleetやAuto Scalingグループと連携して活用
2. aws ssm send-commandでDocumentを実行する
EC2タグで「Environment=production」と「Role=webserver」が設定された全インスタンス,かつマルチAZ(行先AZを問わず)に一括適用する例です。AWSLinux 2023环境でのSSMインストール・設定の詳細はAmazon LinuxでのAWS现場手順も参考になります。
# タグ指定で複数AZのEC2に一括実行 $ aws ssm send-command --document-name "MyNginxInstall" --document-version "2" --targets '[{"Key":"tag:Environment","Values":["production"]},{"Key":"tag:Role","Values":["webserver"]}]' --parameters '{"NginxPackage":["nginx"]}' --max-concurrency "50%" --max-errors "1" --output-s3-bucket-name "my-ssm-output-prod" --output-s3-key-prefix "ssm-logs/" --region ap-northeast-1 { "Command": { "CommandId": "abc12345-1234-1234-1234-abc123456789", "DocumentName": "MyNginxInstall", "DocumentVersion": "2", "Status": "Pending", "TargetCount": 6, "CompletedCount": 0, "MaxConcurrency": "50%", "MaxErrors": "1" } }
3. aws ssm list-command-invocationsで実行結果を確認する
# インスタンス単位の実行結果を確認する $ aws ssm list-command-invocations --command-id "abc12345-1234-1234-1234-abc123456789" --details --query 'CommandInvocations[*].[InstanceId,StatusDetails,ResponseCode]' --output table ------------------------------------------------------------- | ListCommandInvocations | +---------------------+-----------+------------------------+ | i-0abc123def456789 | Success | 0 | | i-0def456abc789012 | Success | 0 | | i-0ghi789def012345 | Success | 0 | | i-0jkl012ghi345678 | Success | 0 | | i-0mno345jkl678901 | Success | 0 | | i-0pqr678mno901234 | Success | 0 | +---------------------+-----------+------------------------+ # 1台の詳細ログを確認する $ aws ssm get-command-invocation --command-id "abc12345-1234-1234-1234-abc123456789" --instance-id "i-0abc123def456789" { "Status": "Success", "StatusDetails": "Success", "StandardOutputContent": "Last metadata expiration check... Nginx 1.24.0 installed * nginx.service: active (running)" }
実践例|Nginx設定変更ファイルをAZ-1a/1b/1cに同時展開する
本番環境で〈8台のEC2(3AZ・最大同時実行4叴)に、カスタムのnginx.confを配信してreloadする手順をDocument化した例です。# deploy-nginx-conf.yaml --- nginx.conf配信Document schemaVersion: '2.2' description: 'Deploy nginx.conf from S3 and reload Nginx' parameters: S3Bucket: type: String description: 'S3 bucket where nginx.conf is stored' S3Key: type: String description: 'S3 key for nginx.conf' default: 'configs/nginx.conf' mainSteps: - action: 'aws:runShellScript' name: backupCurrentConf inputs: runCommand: - 'cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak.$(date +%Y%m%d%H%M%S)' - action: 'aws:runShellScript' name: downloadNewConf inputs: runCommand: - 'aws s3 cp s3://{{ S3Bucket }}/{{ S3Key }} /etc/nginx/nginx.conf' - 'nginx -t && systemctl reload nginx' - 'echo "Deploy completed: $(hostname)"' timeoutSeconds: 60
# AZを問わず3AZ全時に配信実行 $ aws ssm send-command --document-name "DeployNginxConf" --document-version "\$DEFAULT" --targets '[{"Key":"tag:Role","Values":["nginx-prod"]}]' --parameters '{"S3Bucket":["my-config-bucket"],"S3Key":["configs/nginx-20261010.conf"]}' --max-concurrency "4" --max-errors "1" --region ap-northeast-1 # 全台完了確認 $ aws ssm list-command-invocations --command-id "xyz99999-9999-9999-9999-xyz999999999" --query 'CommandInvocations[*].[InstanceId,StatusDetails]' --output table --region ap-northeast-1
トラブルシュート|DocumentがEC2に届かない時の確認手順
1. SSM Agentの動作状態とインスタンス登録状態の確認
SSM経由の実行が届かない場合、まずEC2上でAgent実障のプロセスが動いているか確認します。# EC2インスタンス上で実行(まずSSHで確認) $ sudo systemctl status amazon-ssm-agent $ sudo systemctl restart amazon-ssm-agent # SSMのオンラインインスタンス一覧でOnline状態確認 $ aws ssm describe-instance-information --filters '[{"Key":"PingStatus","Values":["Online"]}]' --query 'InstanceInformationList[*].[InstanceId,PlatformType,PingStatus,IPAddress]' --output table ----------------------------------------------------------- | DescribeInstanceInformation | +---------------------+-------+--------+----------------+ | i-0abc123def456789 | Linux | Online | 10.0.1.45 | | i-0def456abc789012 | Linux | Online | 10.0.2.78 | | i-0ghi789def012345 | Linux | Online | 10.0.3.12 | +---------------------+-------+--------+----------------+
2. IAMロールとVPCエンドポイントの確認
インスタンスがオンラインにならない場合の主な原因は2つです。・IAMロール不足: EC2にAmazonSSMManagedInstanceCoreポリシーを含むIAMロールがアタッチされているか確認する
・443ポート封鎖: SSM Agentはssmessages.ap-northeast-1.amazonaws.comへのHTTPS(ポTCP 443)が必要。セキュリティグループのアウトバウンドルールを確認する
ポートの通信確認には、EC2上でLinux ポート確認の全コマンドを使って確認することをおすすめします。
# EC2上でSSMエンドポイントへの死活監視 $ curl -s -o /dev/null -w "%{http_code}" https://ssm.ap-northeast-1.amazonaws.com/ping 200 # SSコマンドでアウトバウンド接続を確認 $ ss -tn | grep ':443' ESTAB 0 0 10.0.1.45:54321 3.112.xxx.xxx:443
3. アクセス除外環境でのVPCエンドポイント設定
インターネットアクセスなしのプライベートサブネットウインスタンスには、ssm・エssmmessages・ec2messagesの3つのVPCインターフェース型エンドポイントが必要です。# 3つのSSMエンドポイントを作成する(各AZのサブネットへ) for svc in ssm ssmmessages ec2messages; do aws ec2 create-vpc-endpoint --vpc-id vpc-0abc123 --service-name com.amazonaws.ap-northeast-1.${svc} --vpc-endpoint-type Interface --subnet-ids subnet-0az1a subnet-0az1b subnet-0az1c --security-group-ids sg-0ssm123 --private-dns-enabled --region ap-northeast-1 done
本記事のまとめ
| タスク | コマンド |
|---|---|
| DocumentをYAMLで登録する | aws ssm create-document --name NAME --document-type Command --content file://doc.yaml |
| Documentを新バージョンで更新する | aws ssm update-document --name NAME --document-version $LATEST --content file://doc.yaml |
| デフォルトバージョンを切り替える | aws ssm update-document-default-version --name NAME --document-version 2 |
| 複数AZのEC2に一括実行する | aws ssm send-command --document-name NAME --targets '[{"Key":"tag:Env","Values":["prod"]}]' |
| 実行結果をインスタンス単位で確認する | aws ssm list-command-invocations --command-id ID --details |
| オンラインインスタンス一覧を確認する | aws ssm describe-instance-information --filters '[{"Key":"PingStatus","Values":["Online"]}]' |
3,100名以上が実践した「型」を無料で公開中
プロのエンジニアはコマンドを暗記していません。
「現場で使える型」を効率よく使いこなしているだけです。
その「型」を図解60Pにまとめた入門マニュアルを、完全無料でプレゼントしています。
姓・名・メールの3つだけ/30秒/解除は3秒 / 詳細はこちら
- 前のページへ:AWS CLI SSMセッションマネージャーを使ったVPC内サーバー接続設計|踏み台不要の安全なアクセス経路
- この記事の属するカテゴリ:AWS(Amazon Linux)へ戻る

無料メルマガで学習を続ける
Linuxの実践スキルをメールで毎週お届け。
登録は30秒、解除もいつでも可。
登録無料・いつでも解除できます