🌱 Infra/Container_AWS_ECS

[ECS exec log ec2] 스크립트

mini_world 2022. 9. 15. 20:16
목차 접기

ECS exec도 불편하고, 로그를 보는것도 불편하고 ec2 매번 찾아들어가는것도 귀찮고 힘들어서 스크립트를 만들었다..

모두에게 도움이 되기를... 🥲

 

 


Step 1 ) ECS 서비스 설정

가장 먼저, enableExecuteCommand 가 활성화 되어있어야 한다.

aws ecs update-service --cluster ${클러스터이름} --services ${서비스이름} --enable-execute-command true

enableExecuteCommand 활성화 후에도 뭔가 오류가 발생한다면 이것을 실행해보자  (amazon-ecs-exec-checker)

 

Step2) 로컬 PC에 awscli, Session Manager 설치

스크립트를 실행하기위해서는 awscli, session Manager Plugin이 설치되어있어야 한다.

* AWS CLI: https://docs.aws.amazon.com/ko_kr/cli/latest/userguide/getting-started-install.html

* AWS Session Manager Plugin: https://docs.aws.amazon.com/ko_kr/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html

 

Step3) 스크립트 실행 

스크립트는 맨 아래줄에 있으니 스크롤 다운하고 로컬PC에 복붙한다. 그냥 스크립트를 실행하면 된다.

sh ecs.sh

 

스크립트 설명

sh ecs.sh ${command} ${profile_name} ${region} ${cluster} ${service}

 

 

 

[스크립트] 

#!/bin/bash
set -euo pipefail
export AWS_DEFAULT_OUTPUT=json

#### Colors for output
COLOR_DEFAULT='\033[0m'
COLOR_RED='\033[0;31m'
COLOR_YELLOW='\033[1;33m'
COLOR_GREEN='\033[0;32m'
COLOR_CLEAR='\033[0m'

#### Functions
printSectionHeaderLine() {
  printf "${COLOR_DEFAULT}---------------------------------------------------------------------\n"
}


#### Args
# sh ./ecs.sh \${command} \${profile_name} \${region} \${cluster} \${service}
COMMAND=${1:-None}
PROFILE_NAME=${2:-None}
REGION=${3:-None}
ECS_CLUSTER=${4:-None}
ECS_SERVICE=${5:-None}

# 실행할 명령어 선택
if [[ "${COMMAND}" = "None" ]]; then
AWS_CLI_VERSION=$(aws --version | cut -d " " -f1 | cut -d "/" -f2)
SESSION_PLUGIN_VERSION=$(/usr/local/bin/session-manager-plugin --version)
printf "
ECS를 편하게 사용할 수 있도록 만들어진 스크립트입니다.
자유롭게 수정하여 사용할 수 있습니다. 스크립트가 업그레이드 되었다면 공유해주세요. \n
🚨 사전조건 \n
    1) AWS CLI 버전 1.22.3 이상 또는 AWS CLI 버전 2.3.6 이상 사용
       현재 로컬에 설치되어있는 AWS CLI 버전: ${COLOR_YELLOW}$AWS_CLI_VERSION ${COLOR_CLEAR}
       https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html
    2) AWS CLI에 대한 Session Manager 플러그인 설치 \n\
       현재 로컬에 설치되어있는 Session Manager 플러그인 버전: ${COLOR_YELLOW}$SESSION_PLUGIN_VERSION ${COLOR_CLEAR}
       https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html\n
🚨 사용방법 \n
    1) 컨테이너 bash 실행: 컨테이너에 바로 bash를 실행합니다.
    ${COLOR_GREEN}sh ecs.sh exec \${profile_name} \${region} \${cluster} \${service}${COLOR_CLEAR} 를 입력합니다.
    2) 컨테이너 로그 확인: 컨테이너 로그를 tail 로 실행합니다. 
    ${COLOR_GREEN}sh ecs.sh log \${profile_name} \${region} \${cluster} \${service}${COLOR_CLEAR} 를 입력합니다.
    3) 컨테이너 인스턴스 접속: 컨테이너가 운영되고있는 ec2에 바로 접속합니다.
    ${COLOR_GREEN}sh ecs.sh ec2 \${profile_name} \${region} \${cluster} \${service}${COLOR_CLEAR} 를 입력합니다.
"
printSectionHeaderLine
printf "[실행 명령어 목록]
${COLOR_GREEN}exec ${COLOR_CLEAR}   컨테이너에 bash 실행
${COLOR_GREEN}log ${COLOR_CLEAR}    컨테이너 tail log 확인
${COLOR_GREEN}ec2 ${COLOR_CLEAR}    컨테이너 호스트에 접속\n"
printSectionHeaderLine
PS3='실행할 명령어 번호를 선택하세요:'
select COMMAND in "exec" "log" "ec2"
do
#   echo "The one you have selected is: $ECS_CLUSTER"
break  
done
fi

if [[ "${COMMAND}" = "exec" ]]; then
    # 사용 방법 안내
    if [[ "${PROFILE_NAME}" = "None" ]]; then
        AWS_CLI_VERSION=$(aws --version | cut -d " " -f1 | cut -d "/" -f2)
        SESSION_PLUGIN_VERSION=$(/usr/local/bin/session-manager-plugin --version)
        printf "
---------------------------------------------------------------------                                                              
####     #####    #####             ####   #### ###   ####     #####  
##  ##   ##  ##   ##                ##  ##   ##   #   ##  ##   ##  ##  
######   ##        ####             ######    ####    ######   ##      
##       ##         ####            ##        ###     ##       ##      
##       ##   #   #    #            ##       #  ##    ##       ##   #  
####     ####    #####              ####   ###  ###   ####     ####  "
    fi

    # 사용할 프로필 선택
    if [[ "${PROFILE_NAME}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        read -p " AWS Profile 입력하세요 [기본값:default]: " PROFILE_NAME
        PROFILE_NAME=${PROFILE_NAME:-default}
        printf "${COLOR_GREEN} - AWS Profile: "$PROFILE_NAME
    fi

    # 리전 선택
    if [[ "${REGION}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine  
        read -p " AWS Region 입력하세요 [기본값:ap-northeast-2]: " REGION
        REGION=${REGION:-ap-northeast-2}
        printf "${COLOR_GREEN} - AWS Profile: "$REGION
    fi

    # ECS Cluster 선택
    if [[ "${ECS_CLUSTER}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        CLUSTER_LIST=$(aws ecs list-clusters --profile $PROFILE_NAME --region $REGION | jq '.clusterArns[]' | cut -d '/' -f2 | cut -d '"' -f1)
        PS3='클러스터 목록 확인 후 번호를 입력하세요:'
        select ECS_CLUSTER in $CLUSTER_LIST
        do
        #   echo "The one you have selected is: $ECS_CLUSTER"
        break  
        done
        printf "${COLOR_GREEN} - ECS Cluster: "$ECS_CLUSTER
    fi

    # ECS Service 선택
    if [[ "${ECS_SERVICE}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        SERVICE_LIST=$(aws ecs list-services --cluster $ECS_CLUSTER --profile $PROFILE_NAME --region $REGION | jq '.serviceArns[]' | cut -d '/' -f3 | cut -d '"' -f1)
        PS3='서비스 목록 확인 후 번호를 입력하세요:'
        select ECS_SERVICE in $SERVICE_LIST
        do
        #   echo "The one you have selected is: $ECS_SERVICE"
        break  
        done
        printf "${COLOR_GREEN} - ECS Service: "$ECS_SERVICE
    fi

    # ECS Task 선택
    printf "\n"
    printSectionHeaderLine
    TASK_LIST=$(aws ecs list-tasks --cluster $ECS_CLUSTER --family $ECS_SERVICE --profile $PROFILE_NAME --region $REGION | jq '.taskArns[]' | cut -d '/' -f3 | cut -d '"' -f1)
    TASK_COUNT=$(aws ecs list-tasks --cluster $ECS_CLUSTER --family $ECS_SERVICE --profile $PROFILE_NAME --region $REGION | jq '.taskArns[]' | wc -l)
    if [[ "${TASK_COUNT}" -gt 1 ]]; then
        PS3='Task ID 번호를 입력하세요: '
        select ECS_TASK in $TASK_LIST
        do
        #   echo "The one you have selected is: $task_list"
        CONTAINER_NAME=$(aws ecs describe-tasks --cluster $ECS_CLUSTER --tasks $ECS_TASK --profile $PROFILE_NAME --region $REGION | jq '.tasks[].containers[].name' | tr -d '"')
        break  
        done
        printf "${COLOR_GREEN} - ECS task: "$ECS_TASK"\n - Container name: "$CONTAINER_NAME
    else
        ECS_TASK=${TASK_LIST}
        CONTAINER_NAME=$(aws ecs describe-tasks --cluster $ECS_CLUSTER --tasks $ECS_TASK --profile $PROFILE_NAME --region $REGION | jq '.tasks[].containers[].name' | tr -d '"')
        printf "${COLOR_GREEN} - ECS task: "$ECS_TASK"\n - Container name: "$CONTAINER_NAME
    fi


    # 선택한 목록 출력 및 커멘드 실행
    printf "\n"
    printSectionHeaderLine
    printf "${COLOR_GREEN} AWS Profile: $PROFILE_NAME\n${COLOR_GREEN} AWS region: $REGION\n${COLOR_GREEN} ECS Cluster: $ECS_CLUSTER\n${COLOR_GREEN} ECS Service: $ECS_SERVICE\n${COLOR_GREEN} ECS task: $ECS_TASK\n😎${COLOR_YELLOW}'sh ./ecs.sh $COMMAND $PROFILE_NAME $REGION $ECS_CLUSTER $ECS_SERVICE'\nECS $CONTAINER_NAME 컨테이너에 bash를 실행합니다\n${COLOR_CLEAR}"
    aws ecs execute-command --cluster $ECS_CLUSTER --task $ECS_TASK --container $CONTAINER_NAME --profile $PROFILE_NAME --region $REGION --interactive --command "/bin/bash"

elif [[ "${COMMAND}" = "ec2" ]]; then

    # 사용 방법 안내
    if [[ "${PROFILE_NAME}" = "None" ]]; then
        printf "
---------------------------------------------------------------------                                                              
                                    #######   ######  #####   
####     #####    #####             ##   #  ##   ## ##   ##  
##  ##   ##  ##   ##                 ##      ##    #      ##  
######   ##        ####              #####   ##         ###   
##       ##         ####             ##      ##       ###     
##       ##   #   #    #             ##   #  ##   ## ##   ##  
####     ####    #####             #######   #####  #######   "
    fi

    # 사용할 프로필 선택
    if [[ "${PROFILE_NAME}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        read -p " AWS Profile 입력하세요 [기본값:default]: " PROFILE_NAME
        PROFILE_NAME=${PROFILE_NAME:-default}
        printf "${COLOR_GREEN} - AWS Profile: "$PROFILE_NAME
    fi

    # 리전 선택
    if [[ "${REGION}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine  
        read -p " AWS Region 입력하세요 [기본값:ap-northeast-2]: " REGION
        REGION=${REGION:-ap-northeast-2}
        printf "${COLOR_GREEN} - AWS Profile: "$REGION
    fi

    # ECS Cluster 선택
    if [[ "${ECS_CLUSTER}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        CLUSTER_LIST=$(aws ecs list-clusters --profile $PROFILE_NAME --region $REGION | jq '.clusterArns[]' | cut -d '/' -f2 | cut -d '"' -f1)
        PS3='클러스터 목록 확인 후 번호를 입력하세요:'
        select ECS_CLUSTER in $CLUSTER_LIST
        do
        #   echo "The one you have selected is: $ECS_CLUSTER"
        break  
        done
        printf "${COLOR_GREEN} - ECS Cluster: "$ECS_CLUSTER
    fi

    # ECS Service 선택
    if [[ "${ECS_SERVICE}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        SERVICE_LIST=$(aws ecs list-services --cluster $ECS_CLUSTER --profile $PROFILE_NAME --region $REGION | jq '.serviceArns[]' | cut -d '/' -f3 | cut -d '"' -f1)
        PS3='서비스 목록 확인 후 번호를 입력하세요:'
        select ECS_SERVICE in $SERVICE_LIST
        do
        #   echo "The one you have selected is: $ECS_SERVICE"
        break  
        done
        printf "${COLOR_GREEN} - ECS Service: "$ECS_SERVICE
    fi

    # ECS Task 선택
    printf "\n"
    printSectionHeaderLine
    TASK_LIST=$(aws ecs list-tasks --cluster $ECS_CLUSTER --family $ECS_SERVICE --profile $PROFILE_NAME --region $REGION | jq '.taskArns[]' | cut -d '/' -f3 | cut -d '"' -f1)
    TASK_COUNT=$(aws ecs list-tasks --cluster $ECS_CLUSTER --family $ECS_SERVICE --profile $PROFILE_NAME --region $REGION | jq '.taskArns[]' | wc -l)
    if [[ "${TASK_COUNT}" -gt 1 ]]; then
        PS3='Task ID 번호를 입력하세요: '
        select ECS_TASK in $TASK_LIST
        do
        #   echo "The one you have selected is: $task_list"
        CONTAINER_NAME=$(aws ecs describe-tasks --cluster $ECS_CLUSTER --tasks $ECS_TASK --profile $PROFILE_NAME --region $REGION | jq '.tasks[].containers[].name' | tr -d '"')
        break  
        done
        printf "${COLOR_GREEN} - ECS task: "$ECS_TASK"\n - Container name: "$CONTAINER_NAME
    else
        ECS_TASK=${TASK_LIST}
        CONTAINER_NAME=$(aws ecs describe-tasks --cluster $ECS_CLUSTER --tasks $ECS_TASK --profile $PROFILE_NAME --region $REGION | jq '.tasks[].containers[].name' | tr -d '"')
        printf "${COLOR_GREEN} - ECS task: "$ECS_TASK"\n - Container name: "$CONTAINER_NAME
    fi

    # 선택한 목록 출력 및 커멘드 실행
    printf "\n"
    printSectionHeaderLine
    printf "${COLOR_GREEN} AWS Profile: $PROFILE_NAME\n${COLOR_GREEN} AWS region: $REGION\n${COLOR_GREEN} ECS Cluster: $ECS_CLUSTER\n${COLOR_GREEN} ECS Service: $ECS_SERVICE\n${COLOR_GREEN} ECS task: $ECS_TASK\n😎${COLOR_YELLOW}'sh ./ecs.sh $COMMAND $PROFILE_NAME $REGION $ECS_CLUSTER $ECS_SERVICE'\nECS $CONTAINER_NAME 컨테이너가 실행중인 EC2에 연결합니다\n${COLOR_CLEAR}"
    ECS_INSTANCE=$(aws ecs describe-tasks --cluster $ECS_CLUSTER --tasks $ECS_TASK --profile $PROFILE_NAME --region $REGION | jq '.tasks[].containerInstanceArn'| cut -d '/' -f3 | tr -d '"')
    INSTANCE_ID=$(aws ecs describe-container-instances --cluster $ECS_CLUSTER --container-instances $ECS_INSTANCE --profile $PROFILE_NAME --region $REGION | jq '.containerInstances[].ec2InstanceId' | tr -d '"')
    aws ssm start-session --target $INSTANCE_ID --profile $PROFILE_NAME --region $REGION 

elif [[ "${COMMAND}" = "log" ]]; then
    # 사용 방법 안내


    if [[ "${PROFILE_NAME}" = "None" ]]; then
        printf "
---------------------------------------------------------------------                                                              
                                    ###                   ## 
####     #####    #####              ##      ####     #####  
##  ##   ##  ##   ##                  ##     ##  ##   ##  ##  
######   ##        ####               ##     ##  ##   #####   
##       ##         ####              ##     ##  ##    ##     
##       ##   #   #    #              ##     ##  ##    #####  
####     ####    #####              ####     ####    ##  ##   "
    fi

    # 사용할 프로필 선택
    if [[ "${PROFILE_NAME}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        read -p " AWS Profile 입력하세요 [기본값:default]: " PROFILE_NAME
        PROFILE_NAME=${PROFILE_NAME:-default}
        printf "${COLOR_GREEN} - AWS Profile: "$PROFILE_NAME
    fi

    # 리전 선택
    if [[ "${REGION}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine  
        read -p " AWS Region 입력하세요 [기본값:ap-northeast-2]: " REGION
        REGION=${REGION:-ap-northeast-2}
        printf "${COLOR_GREEN} - AWS Profile: "$REGION
    fi

    # ECS Cluster 선택
    if [[ "${ECS_CLUSTER}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        CLUSTER_LIST=$(aws ecs list-clusters --profile $PROFILE_NAME --region $REGION | jq '.clusterArns[]' | cut -d '/' -f2 | tr -d '"')
        PS3='클러스터 목록 확인 후 번호를 입력하세요:'
        select ECS_CLUSTER in $CLUSTER_LIST
        do
        #   echo "The one you have selected is: $ECS_CLUSTER"
        break  
        done
        printf "${COLOR_GREEN} - ECS Cluster: "$ECS_CLUSTER
    fi

    # ECS Service 선택
    if [[ "${ECS_SERVICE}" = "None" ]]; then
        printf "\n"
        printSectionHeaderLine
        SERVICE_LIST=$(aws ecs list-services --cluster $ECS_CLUSTER --profile $PROFILE_NAME --region $REGION | jq '.serviceArns[]' | cut -d '/' -f3 | tr -d '"')
        PS3='서비스 목록 확인 후 번호를 입력하세요:'
        select ECS_SERVICE in $SERVICE_LIST
        do
        #   echo "The one you have selected is: $ECS_SERVICE"
        break  
        done
        printf "${COLOR_GREEN} - ECS Service: "$ECS_SERVICE
    fi

    # ECS Task 선택
    printf "\n"
    printSectionHeaderLine
    ECS_TASK=$(aws ecs list-tasks --cluster $ECS_CLUSTER --family $ECS_SERVICE --profile $PROFILE_NAME --region $REGION | jq '.taskArns[]' |head -1| cut -d '/' -f3 | tr -d '"')
    CONTAINER_NAME=$(aws ecs describe-tasks --cluster $ECS_CLUSTER --tasks $ECS_TASK --profile $PROFILE_NAME --region $REGION | jq '.tasks[].containers[].name' | tr -d '"')
    printf "${COLOR_GREEN} - ECS task: "$ECS_TASK"\n - Container name: "$CONTAINER_NAME

    # 선택한 목록 출력 및 커멘드 실행
    printf "\n"
    printSectionHeaderLine
    printf "${COLOR_GREEN} AWS Profile: $PROFILE_NAME\n${COLOR_GREEN} AWS region: $REGION\n${COLOR_GREEN} ECS Cluster: $ECS_CLUSTER\n${COLOR_GREEN} ECS Service: $ECS_SERVICE\n${COLOR_GREEN} ECS task: $ECS_TASK\n😎${COLOR_YELLOW}'sh ./ecs.sh $COMMAND $PROFILE_NAME $REGION $ECS_CLUSTER $ECS_SERVICE'\nECS $CONTAINER_NAME 컨테이너의 로그를 출력합니다.\n${COLOR_CLEAR}"
    TASK_DEF=$(aws ecs describe-tasks --cluster $ECS_CLUSTER --tasks $ECS_TASK --profile $PROFILE_NAME --region $REGION | jq '.tasks[].taskDefinitionArn'| tr -d '"')
    TASK_LOG_GROUP=$(aws ecs describe-task-definition --task-definition $TASK_DEF --profile $PROFILE_NAME --region $REGION | jq '.taskDefinition.containerDefinitions[].logConfiguration.options."awslogs-group"'| tr -d '"')
    printSectionHeaderLine
    aws logs tail $TASK_LOG_GROUP --profile $PROFILE_NAME --region $REGION --follow --since 1m

fi



728x90