☁️ Cloud
EC2
Elastic Compute Cloud
AWS's virtual server service. Various instance types. On-demand, spot, and reserved instances.
Elastic Compute Cloud
AWS's virtual server service. Various instance types. On-demand, spot, and reserved instances.
Amazon EC2 (Elastic Compute Cloud) is AWS's core IaaS (Infrastructure as a Service) offering, which lets you provision and manage virtual servers in the cloud on demand. Launched in 2006 as one of the first AWS services, it has become the standard of cloud computing today.
EC2 instance types are divided by use case:
Pricing models are divided into On-Demand (hourly billing), Reserved Instances (1–3-year commitment, up to 72% discount), Spot Instances (bidding on unused capacity, up to 90% discount), and Savings Plans (flexible commitment).
# 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()
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free