EC2 stopped 시간과 이름 출력 (AWS CLI)

2024. 7. 29. 12:31AWS/AWS Command Line Interface

728x90
SMALL
  • 스크립트
#!/bin/bash

# 정지된 인스턴스 목록 가져오기
stopped_instances=$(aws ec2 describe-instances \
    --filters "Name=instance-state-name,Values=stopped" \
    --query "Reservations[*].Instances[*].[InstanceId, Tags[?Key=='Name'].Value | [0]]" \
    --output json)

# 테이블 헤더 출력
printf "%-50s %-50s %-50s\n" "Instance ID" "Instance Name" "Stopped Time"

# 각 인스턴스에 대해 정지 시간을 가져와서 출력
echo "$stopped_instances" | jq -c '.[][]' | while read -r instance; do
    instance_id=$(echo "$instance" | jq -r '.[0]')
    instance_name=$(echo "$instance" | jq -r '.[1] // "No Name"')

    # 인스턴스 상태 전환 이유 가져오기
    state_transition_reason=$(aws ec2 describe-instances \
        --instance-ids "$instance_id" \
        --query "Reservations[*].Instances[*].StateTransitionReason" \
        --output text)

    # 정지 시간 추출
    stopped_time=$(echo "$state_transition_reason" | sed -n 's/.*(\(.*\)).*/\1/p')

    # 결과 출력
    printf "%-50s %-50s %-50s\n" "$instance_id" "$instance_name" "$stopped_time"
done
728x90
LIST