☁️
클라우드
EC2
Elastic Compute Cloud
AWS 가상 서버 서비스. 다양한 인스턴스 타입. 온디맨드, 스팟, 예약 인스턴스.
Elastic Compute Cloud
AWS 가상 서버 서비스. 다양한 인스턴스 타입. 온디맨드, 스팟, 예약 인스턴스.
Amazon EC2(Elastic Compute Cloud)는 AWS의 핵심 IaaS(Infrastructure as a Service) 서비스로, 클라우드에서 가상 서버를 온디맨드로 프로비저닝하고 관리할 수 있게 해줍니다. 2006년 AWS 최초 서비스 중 하나로 출시되어 현재 클라우드 컴퓨팅의 표준이 되었습니다.
EC2 인스턴스 타입은 용도에 따라 구분됩니다:
요금제는 온디맨드(시간당 과금), 예약 인스턴스(1-3년 약정, 최대 72% 할인), 스팟 인스턴스(미사용 용량 입찰, 최대 90% 할인), Savings Plans(유연한 약정)으로 나뉩니다.
# EC2 인스턴스 생성
aws ec2 run-instances \
--image-id ami-0c55b159cbfafe1f0 \
--instance-type t3.micro \
--key-name my-key-pair \
--security-group-ids sg-903004f8 \
--subnet-id subnet-6e7f829e \
--count 1 \
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=WebServer}]'
# 인스턴스 상태 확인
aws ec2 describe-instances \
--filters "Name=tag:Name,Values=WebServer" \
--query 'Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress]'
# 인스턴스 중지/시작
aws ec2 stop-instances --instance-ids i-1234567890abcdef0
aws ec2 start-instances --instance-ids i-1234567890abcdef0
# 스팟 인스턴스 요청 (최대 90% 비용 절감)
aws ec2 request-spot-instances \
--spot-price "0.03" \
--instance-count 1 \
--type "one-time" \
--launch-specification file://spot-spec.json
# Terraform EC2 인스턴스 구성
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0" # Amazon Linux 2
instance_type = "t3.micro"
# 프리 티어: t2.micro/t3.micro 월 750시간 무료
key_name = "my-key-pair"
vpc_security_group_ids = [aws_security_group.web_sg.id]
subnet_id = aws_subnet.public.id
# EBS 루트 볼륨 설정
root_block_device {
volume_type = "gp3" # 최신 SSD 타입
volume_size = 20 # GB
delete_on_termination = true
encrypted = true
}
# 사용자 데이터 (인스턴스 시작 시 실행)
user_data = <<-EOF
#!/bin/bash
yum update -y
yum install -y httpd
systemctl start httpd
systemctl enable httpd
echo "Hello from EC2" > /var/www/html/index.html
EOF
tags = {
Name = "web-server"
Environment = "production"
}
}
# Auto Scaling Group (고가용성)
resource "aws_autoscaling_group" "web_asg" {
desired_capacity = 2
max_size = 10
min_size = 2
vpc_zone_identifier = [aws_subnet.az1.id, aws_subnet.az2.id]
target_group_arns = [aws_lb_target_group.web.arn]
launch_template {
id = aws_launch_template.web.id
version = "$Latest"
}
tag {
key = "Name"
value = "web-asg"
propagate_at_launch = true
}
}
import boto3
from botocore.exceptions import ClientError
# EC2 클라이언트 생성
ec2 = boto3.client('ec2', region_name='ap-northeast-2')
ec2_resource = boto3.resource('ec2', region_name='ap-northeast-2')
def create_instance(name: str, instance_type: str = 't3.micro'):
"""EC2 인스턴스 생성"""
instances = ec2_resource.create_instances(
ImageId='ami-0c55b159cbfafe1f0', # Amazon Linux 2
InstanceType=instance_type,
MinCount=1,
MaxCount=1,
KeyName='my-key-pair',
SecurityGroupIds=['sg-903004f8'],
TagSpecifications=[{
'ResourceType': 'instance',
'Tags': [{'Key': 'Name', 'Value': name}]
}],
# IMDSv2 필수 (보안 권장)
MetadataOptions={
'HttpTokens': 'required',
'HttpEndpoint': 'enabled'
}
)
instance = instances[0]
instance.wait_until_running()
instance.reload()
print(f"인스턴스 생성: {instance.id}")
print(f"Public IP: {instance.public_ip_address}")
return instance
def get_spot_price(instance_type: str):
"""스팟 인스턴스 현재 가격 조회"""
response = ec2.describe_spot_price_history(
InstanceTypes=[instance_type],
ProductDescriptions=['Linux/UNIX'],
MaxResults=5
)
for price in response['SpotPriceHistory']:
print(f"AZ: {price['AvailabilityZone']}, "
f"가격: ${price['SpotPrice']}/시간")
def list_running_instances():
"""실행 중인 인스턴스 목록"""
response = ec2.describe_instances(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
)
for reservation in response['Reservations']:
for instance in reservation['Instances']:
name = next(
(t['Value'] for t in instance.get('Tags', [])
if t['Key'] == 'Name'), 'N/A'
)
print(f"{instance['InstanceId']}: {name} "
f"({instance['InstanceType']}) - "
f"{instance.get('PublicIpAddress', 'No Public IP')}")
# 사용 예시
if __name__ == "__main__":
# instance = create_instance("my-web-server")
get_spot_price('t3.medium') # 스팟 가격 확인
list_running_instances()