2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AWS ECS Execの利便性を高めるショートカットコマンドの作成

Posted at

AWS ECS Execのショートカットコマンドを作りましょう

AWS ECSでExecコマンドを実行する際、通常はAPIやConsoleを介してタスクIDを取得し、そのIDを用いてコマンドを実行します。これは手間がかかりますよね。そこで、タスクID取得からExecまでの一連の流れを一気に実行するショートカットコマンドを作成する方法をご紹介します。

まずは、以下のショートカットコマンドを ~/.zshrc に追記します。
 

~/.zshrc
ecs_exec_command() {
    # Check if the right number of arguments are passed
    if [ $# -ne 3 ]; then
        echo "Usage: ecs_exec_command <cluster> <container> <service>"
        return 1
    fi

    # Get the parameters
    cluster=$1
    container=$2
    service=$3

    # Command to execute
    command="/bin/sh"

    # Get the list of task ARNs for the service
    taskArns=$(aws ecs list-tasks --cluster $cluster --service-name $service --query 'taskArns' --output text)

    # If there are no tasks, exit
    if [ -z "$taskArns" ]; then
        echo "No tasks found for service $service in cluster $cluster"
        return 1
    fi

    # Get the first task ARN
    taskArn=$(echo $taskArns | awk '{print $1}')

    # Get the task ID from the task ARN
    taskId=${taskArn##*/}

    # Execute command on the task
    aws ecs execute-command \
    --cluster $cluster \
    --container $container \
    --interactive \
    --command "$command" \
    --task $taskId
}


このショートカットコマンドは の3つの引数を受け取り、aws ecs list-tasksコマンドでタスクIDを取得した後aws ecs execute-commandでExecを実行します。

しかし、毎回これらの引数を指定するのは面倒なので、プリセット値を使用するラッピング関数を作成します。これを使えば、引数を渡すだけで簡単にExecを実行できます。

以下に、そのラッピング関数を示します。こちらも ~/.zshrc に追記します。

~/.zshrc
pj-ecs-exec() {
  # Check if the right number of arguments are passed
  if [ $# -ne 1 ]; then
      echo "Usage: ecs_exec_command <container>"
      return 1
  fi

  # Get the parameters
  preset_container=$1

  # Your preset cluster, container and service
  preset_cluster="your-cluster-name"
  preset_service="your-service-name"

  # Call the ecs_exec_command function
  ecs-exec-command $preset_cluster $preset_container $preset_service
}

preset_cluster, preset_serviceに事前に入れておけば、
以下のコマンドでcontainerを引数にするだけで実行できます。

$ pj-ecs-exec nginx

このように、ショートカットコマンドとラッピング関数を利用することで、AWS ECS Execの利便性を格段に向上させることができます。ぜひ一度お試しください。

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?