
실행 중인 정상 인스턴스 수를 일정하게 유지하고 싶습니다. 그러나 때때로 애플리케이션에 버그가 발생하고 리소스 활용률이 너무 낮아서 CloudWatch 지표만으로 확인할 수 있습니다. 그리고 물론 해당 인스턴스가 자동으로 교체되기를 원합니다. 하지만 이 작업을 수행하는 방법을 알 수 없습니다. 내가 생각할 수 있는 가장 가까운 것은 자동 크기 조정이지만기본 종료 정책, 이러한 모든 옵션은 특정 인스턴스의 측정항목과 아무 관련이 없는 것 같습니다.
출시 준비가 완료된 AMI를 생성했습니다. 나에게 필요한 유일한 것은 비정상 인스턴스를 자동으로 종료하고 새 인스턴스로 교체하는 것입니다. 그러면 어떻게 해야 할까요? 도움을 주시면 감사하겠습니다.
답변1
사용자 정의 인스턴스 상태 확인(페이지 하단)은 하나의 옵션입니다.
상태를 모니터링하고 인스턴스를 비정상으로 설정하는 API 호출을 실행하는 머신(또는 실제 머신)에서 실행되는 별도의 코드 조각이 있을 것입니다.
또 다른 절반의 아이디어가 있지만 이를 구현하는 방법을 잘 모르겠습니다. 저는 인스턴스의 별도 웹 서버에 로드 밸런서를 호출하는 온프레미스 시스템의 설계자였습니다. 우리의 경우에는 약 50줄의 코드로 구성된 작은 사용자 정의 Java 웹 서버였습니다. HTTP 상태 코드를 반환했는데, 정상적으로 진행되고 있으면 200(OK), 종료해야 하면 500(ERROR)이 반환되었습니다. 나는 이와 같은 것이 자동 스케일링과 통합될 수 있다고 생각하지만 한동안 이 작업을 수행하지 않았으며 이것을 자동 스케일링과 어떻게 통합할지 잘 모르겠습니다.
위의 첫 번째 아이디어의 명령은 다음과 같습니다.
aws autoscaling set-instance-health --instance-id i-123abc45d --health-status Unhealthy
답변2
이 질문을 접하는 사람은 다음과 같습니다.
AWS가 CloudWatch에 이러한 기능을 포함했어야 했다고 생각하지만, 안타깝게도 이 기능을 사용할 수 있다는 정보를 찾을 수 없습니다. 그래서 CloudWatch API를 쿼리하여 리소스 소비 지표를 확인한 다음 그에 따라 인스턴스 상태를 설정하는 bash 스크립트를 만들었습니다.팀:
준비
- 아직 그렇게 하지 않았다면,AWS 명령줄 인터페이스 설치.
yum
또는를 통해 이용 가능apt
. - AWS CLI 구성실행하여
aws configure
API 키 및 기타 설정을 입력하세요.중요한: 저처럼 루트로 아래 스크립트를 실행하려면 이 구성 명령을 루트로 실행해야 합니다. 그렇지 않으면 스크립트가 실패합니다.
/root/my-health-check.sh
#!/bin/bash
# retrieve metrics starting from 20 minutes ago (3 data points)
# Note: Sometimes CloudWatch failed to gather data for a specific period,
# then the number of data points returned could be less than what we expect.
# Also, when the instance just started, there will be no data point.
start_time=$(date -d "-20 minutes" -u +"%Y-%m-%dT%H:%M:%SZ")
# retrieve metrics up to now
end_time=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
# get current instance ID [1]
instance_id=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
# get current region [2]
# This is only needed if you have multiple regions to manage, otherwise just
# specify a region via `aws configure`.
region=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone | sed 's/\(.*\)[a-z]/\1/')
# save data retrieved for processing [3]
# Here I used an example of retrieving "NetworkIn" of "AWS/EC2" namespace,
# with metric resolution set to 300 (5 minutes).
# For a list of available metrics, run `aws cloudwatch list-metrics`
datapoints=$(aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name NetworkIn --dimensions Name=InstanceId,Value=$instance_id --statistics Average --start-time $start_time --end-time $end_time --period 300 --region $region --output text | awk '{ print $2 }')
# custom handler
# In this example, the health check will fail if all data points fall below
# my threshold. The health check will not fail if there is no data.
healthy=0
hasdata=0
THRESHOLD=300000
for i in $datapoints; do
# In this case, the metric(NetworkIn) is not integer.
if (( $(echo "$i $THRESHOLD" | awk '{print ($1 > $2)}') )); then
healthy=1
fi
hasdata=1
done
if [ $hasdata -eq 1 ]; then
if [ $healthy -eq 0 ]; then
aws autoscaling set-instance-health --instance-id $instance_id --health-status Unhealthy --region $region
fi
fi
나머지
- 스크립트를 주기적으로 실행하도록 설정
$ chmod +x /root/my-health-check.sh
# run the script at 0, 5, 10, 15 ... 55 of every hour
$ echo "*/5 * * * * root /root/my-health-check.sh 2>&1 | /usr/bin/logger -t ec2_health_check" >> /etc/crontab
- 인스턴스의 전원을 끄고 AMI를 만듭니다. 완료되면 AMI를 사용하여 새 Auto Scaling 그룹을 생성합니다. 이제 지표가 정상 조건을 충족하지 않으면 자체적으로 종료되고 새 지표를 시작해야 합니다. 짜잔!
참고자료:
[1]:EC2 인스턴스 메타데이터