ECSタスクにSessionManagerで接続する方法

March 27, 2024

はじめに

ECS タスクに SessionManager で接続する方法を紹介します。

設定の有効化・確認方法

# 確認する
aws ecs describe-services --cluster クラスター名 --services サービス名 | jq '.services[].enableExecuteCommand'
# 有効化する
aws ecs update-service --region ap-northeast-1 --cluster クラスター名 --service サービス名 --enable-execute-command

接続方法

aws ecs execute-command --cluster クラスター名 \
  --task タスクID \
  --container コンテナ名 \
  --interactive \
  --command "/bin/sh"

接続出来ないときの対処法

  • SSMplugin がインストールされていない

    • SSMpluginをインストールしてください。
  • ECS のタスクロールに SessionManager の権限が追加されてない

    • マネージドポリシーAmazonSSMManagedInstanceCoreを利用するケースが多いと思いますが、以下の action 許可だけで接続自体は可能です。
data "aws_iam_policy_document" "session_manager_policy" {
  statement {
  sid = "1"
  effect = "Allow"
  actions = [
    "ssmmessages:CreateControlChannel",
    "ssmmessages:CreateDataChannel",
    "ssmmessages:OpenControlChannel",
    "ssmmessages:OpenDataChannel"
  ]
  resources = ["*"]
 }
}

それでも接続できない場合は、AWS 公式のツールを利用してデバッグしてみてください。

git clone https://github.com/aws-containers/amazon-ecs-exec-checker.git
brew install jq
./check-ecs-exec.sh [クラスター名] [タスク ID]
Nifty tech tag lists from Wouter Beeftink