AWS ECS(Fargate / EC2)上のタスクに対して、ローカルのターミナルからシェル(bash/sh)で接続する方法をまとめました。
- AWS CLI v2 の execute-command 機能を使って、ローカルから ECS タスクへシェル接続
-
--profile
を使ったプロファイルの切り替え
🛠️ インストール
AWS CLI v2 をインストールします。
- macOS (Homebrew 使用):
brew install awscli
- 他のOSの場合は公式ガイドを参照:
👉 https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/install-cliv2.html
以下のコマンドで確認できます。
aws --version
# 出力
aws-cli/2.27.22 Python/3.13.3 Darwin/24.5.0 source/arm64
🔐 プロファイルの作成と確認
AWS CLI では --profile
を指定せずに default
プロファイルを使うこともできます。
複数の環境(dev/staging/prod など)を使う場合は、明示的にプロファイルを作成して指定しておくと安心かと思います。
プロファイルを作成する(任意)
aws configure --profile my-production
- AWS Access Key ID
- Secret Access Key を入力
- Default region(例:
ap-northeast-1
) - Output format(
json
推奨)
プロファイルを確認する
プロファイルの一覧を表示
aws configure list-profiles
# 出力
default
my-staging
my-production
プロファイルの詳細を表示
aws configure list --profile my-production
# 出力
Name Value Type Location
---- ----- ---- --------
profile my-production manual --profile
access_key ****************6WCC shared-credentials-file
secret_key ****************vJJ+ shared-credentials-file
region ap-northeast-1 config-file ~/.aws/config
💡 一時的に環境変数でプロファイルを指定したい場合
export AWS_PROFILE=my-production
📦 クラスターを確認する
aws ecs list-clusters --profile my-production
# 出力
{
"clusterArns": [
"arn:aws:ecs:ap-northeast-1:XXXXXXXXXXXX:cluster/my-ecs-cluster"
]
}
📋 タスクを確認する
aws ecs list-tasks --cluster my-ecs-cluster --profile my-production
# 出力
{
"taskArns": [
"arn:aws:ecs:ap-northeast-1:XXXXXXXXXXXX:task/my-ecs-cluster/xxxxxxxxxxxxxxxxxxxx",
"arn:aws:ecs:ap-northeast-1:XXXXXXXXXXXX:task/my-ecs-cluster/xxxxxxxxxxxxxxxxxxxx",
"arn:aws:ecs:ap-northeast-1:XXXXXXXXXXXX:task/my-ecs-cluster/xxxxxxxxxxxxxxxxxxxx",
"arn:aws:ecs:ap-northeast-1:XXXXXXXXXXXX:task/my-ecs-cluster/xxxxxxxxxxxxxxxxxxxx"
]
}
📛 コンテナ名を取得する
aws ecs describe-tasks \
--cluster my-ecs-cluster \
--tasks <TASK_ARN> \
--query 'tasks[0].containers[].name' \
--output text \
--profile my-production
# 出力
web
🧑💻 Execute Command で接続する
aws ecs execute-command \
--cluster my-ecs-cluster \
--task <TASK_ARN> \
--container <CONTAINER_NAME> \
--command "/bin/bash" \
--interactive \
--profile my-production
✅ これで、ECS タスクに対してローカルからシェル接続できるようになります。
環境ごとにプロファイルを切り替えることで、誤操作も防げて安心です。
📎 よく使うコマンドまとめ(コピペ用)
# クラスター一覧取得
aws ecs list-clusters --profile my-production
# タスク一覧取得
aws ecs list-tasks --cluster my-ecs-cluster --profile my-production
# コンテナ名取得
aws ecs describe-tasks \
--cluster my-ecs-cluster \
--tasks <TASK_ARN> \
--query 'tasks[0].containers[].name' \
--output text \
--profile my-production
# 実行接続
aws ecs execute-command \
--cluster my-ecs-cluster \
--task <TASK_ARN> \
--container <CONTAINER_NAME> \
--command "/bin/bash" \
--interactive \
--profile my-production
💻 補足:AWS CloudShell でも使えます
AWS CloudShellを使えば、ブラウザ上でCLIを実行できます。
https://aws.amazon.com/jp/cloudshell/
- IAMの許可があればそのまま
aws ecs execute-command
を実行可能です
💡「ちょっとだけ試したい」時や「出先から接続したい」時に便利!