1
필요
로드 밸런서 사용 시 실제 서버가 로드 밸런싱 잘되는지 IP 확인하는 스크립트가 필요해 AI에게 요청했어요.
내용
AWS EC2 인스턴스가 생성될 때 자동으로 실행되는 User Data(사용자 데이터) 스크립트
AI에서 요청함
요즘은 아이디어만 있으면 AI가 다 해줘요!!
AI에서 요청함
aws ec2에서 사용할 init 스크립트 만들어줘.
웹으로 접속하면 매번 각 서버의 ip를 가져오도록 만들어줘
s3 버킷에 메타데이터 정보 가져오는 스크립트 올려놓고 서버 생성 시 가져와서 실행함
2
작업 순서
1) S3 버킷 설정 - EC2 생성 시 메타데이터 정보 (호스트명, ip 정보) 가져오도록 config.txt 파일 올리는 용도
2) EC2 생성 - AWS EC2 인스턴스가 생성될 때 자동으로 init 스크립트 실행
3) 로드 밸런서 생성 - 웹 브라우저로 접속
2
# S3 버킷 설정 (AI가 알려줌)
퍼블릭 액세스 차단 해제: 버킷 설정에서 **'모든 퍼블릭 액세스 차단'**이 비활성화(Off) 되어야 합니다.
객체 ACL 설정: 파일(객체)의 '권한' 탭에서 **'모든 사람(퍼블릭 액세스)'**에게 읽기(Read) 권한을 명시적으로 부여해야 합니다.
URL 확인: S3 콘솔에서 파일을 클릭하면 나오는 **'객체 URL'**을 위 스크립트의 S3_URL 변수에 넣으세요.
3
S3에 올릴 config.txt 파일
# 메타데이터 정보 가져오기
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
INSTANCE_ID=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/instance-id)
PRIVATE_IP=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/local-ipv4)
AZ=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
# 필수 내용으로 config.txt 작성
cat <<EOF > /var/www/html/config.txt
INSTANCE_ID=$INSTANCE_ID
PRIVATE_IP=$PRIVATE_IP
AVAILABILITY_ZONE=$AZ
DEPLOYED_AT=$(date '+%Y-%m-%d %H:%M:%S')
HOSTNAME=$(hostname)
EOF
4
AWS EC2 인스턴스가 생성될 때 자동으로 init 스크립트 실행
EC2 생성 시 사용할 init 스크립트 파일
#!/bin/bash
# 1. 모든 출력을 로그 파일에 기록 (디버깅용)
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
echo "--- Starting Dynamic Configuration Setup ---"
# 2. 패키지 설치 및 업데이트
yum update -y
yum install -y httpd
# 3. IMDSv2 토큰 생성 및 현재 IP 가져오기 (매 부팅 시 갱신됨)
TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
CURRENT_IP=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" -s http://169.254.169.254/latest/meta-data/local-ipv4)
# 4. S3 퍼블릭 URL에서 설정 가져오기
# 아래 URL을 실제 본인의 S3 파일 주소로 변경하세요.
S3_URL="https://server-ip1/config.txt"
S3_CONTENT=$(curl -s $S3_URL)
# 만약 curl 실패 시를 대비해 기본값 설정
if [ -z "$S3_CONTENT" ]; then
S3_CONTENT="S3 파일을 읽을 수 없습니다. (URL 또는 퍼블릭 권한 확인 필요)"
fi
# 5. 동적 index.html 작성
cat <<EOF > /var/www/html/index.html
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>EC2 Status Page</title>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #f0f2f5; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
.container { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); text-align: center; width: 400px; }
.header { color: #232f3e; font-size: 1.5rem; margin-bottom: 20px; border-bottom: 2px solid #ff9900; padding-bottom: 10px; }
.ip-address { font-size: 2rem; color: #ff9900; font-weight: bold; margin: 20px 0; }
.config-text { background: #f8f9fa; padding: 15px; border-radius: 8px; font-size: 0.9rem; color: #555; }
.footer { font-size: 0.8rem; color: #888; margin-top: 20px; }
</style>
</head>
<body>
<div class="container">
<div class="header">EC2 Instance Info</div>
<p><strong>Config from S3:</strong></p>
<div class="config-text">$S3_CONTENT</div>
<div class="ip-address">$CURRENT_IP</div>
<p>로드 밸런서 연결 상태: <strong>정상(Healthy)</strong></p>
<div class="footer">Last Update: $(date '+%Y-%m-%d %H:%M:%S')</div>
</div>
</body>
</html>
EOF
# 6. 서비스 시작 및 활성화
systemctl enable httpd
systemctl restart httpd
echo "--- Setup Completed Successfully ---"
5
웹브라우저로 ec2 접속
6
로드밸런서 생성
테스트 시간
단순 1회성으로 IP 필요하면 아래 스크립트
https://brunch.co.kr/@topasvga/5488
# AMI 사용할때 사용하는 스크립트
https://brunch.co.kr/@topasvga/5490