LoginSignup
5
4

More than 1 year has passed since last update.

[ECS/Fargate]RailsコンテナにECS Execログインする

Last updated at Posted at 2022-02-20

はじめに

ECS Execを使用することで、SSHを介さずFargate上で動作するコンテナに対しdocker execコマンドを実行することができます。

前提

既に、ECS上で下記リソースを作成済みであること

  • クラスター
  • サービス
  • タスク定義

IAMポリシー

ECSの[タスク定義]-[タスク実行ロール]で使用するIAMポリシーの設定値です。

AmazonECSTaskExecutionRolePolicy.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:GetAuthorizationToken",
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

ecs_task_role_exec.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ssmmessages:CreateControlChannel",
                "ssmmessages:CreateDataChannel",
                "ssmmessages:OpenControlChannel",
                "ssmmessages:OpenDataChannel"
            ],
            "Resource": "*"
        }
    ]
}

aws cli2のインストール

Session Manager プラグインをインストール

curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/mac/sessionmanager-bundle.zip" -o "sessionmanager-bundle.zip"
unzip sessionmanager-bundle.zip
sudo ./sessionmanager-bundle/install -i /usr/local/sessionmanagerplugin -b /usr/local/bin/session-manager-plugin

# インストールが完了したか確認
session-manager-plugin

ECS Execの有効可

CLUSTERNAME="ecs-rails-cluster"
SERVICENAME="ecs-rails-service"
TASKDEFNAME="ecs-rails-def"
CONTAINERNAME="app"

aws ecs update-service \
    --cluster $CLUSTERNAME\
    --service $SERVICENAME \
    --enable-execute-command \
    | grep enableExecuteCommand

タスクを強制デプロイ

aws ecs update-service \
    --cluster $CLUSTERNAME \
    --service $SERVICENAME \
    --task-definition $TASKDEFNAME \
    --force-new-deployment

Fargateにログイン

TASKNAME=`aws ecs list-tasks --cluster $CLUSTERNAME --query "taskArns[0]" --output text`

aws ecs execute-command \
    --cluster $CLUSTERNAME \
    --task $TASKNAME \
    --container $CONTAINERNAME \
    --interactive \
    --command "/bin/sh"

参考資料

https://dev.classmethod.jp/articles/ecs-exec-for-fish-shell/
https://qiita.com/notakaos/items/eda64c3c38b17f181698

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4