
AWS에서 만든 Python SDK로, AWS의 다양한 서비스들을 제어/관리할 수 있다
import boto3
# client 방식 (low-level)
ec2_client = boto3.client('ec2')
# resource 방식 (high-level)
ec2_resource = boto3.resource('ec2')
(전체 서비스는 200개가 넘어요)
| 서비스 | 주요 리소스 | 조회 메서드 예시 | 관리/제어 메서드 예시 |
|---|---|---|---|
| EC2 | 인스턴스, AMI, EBS, 보안 그룹 등 | describe_instances(), describe_images() | start_instances(), stop_instances(), terminate_instances(), create_security_group() |
| S3 | 버킷, 오브젝트 | list_buckets(), list_objects_v2() | create_bucket(), delete_object(), put_object() |
| IAM | 사용자, 정책, 역할 | list_users(), list_roles() | create_user(), attach_user_policy() |
| CloudWatch | 지표, 로그, 경보 | list_metrics(), get_metric_data(), describe_alarms() | put_metric_alarm(), delete_alarms() |
| CloudTrail | 이벤트 기록 | lookup_events() | (읽기 전용) |
| Lambda | 함수 | list_functions() | create_function(), invoke() |
| DynamoDB | 테이블 | list_tables(), describe_table() | put_item(), delete_item(), create_table() |
| RDS | DB 인스턴스 | describe_db_instances() | start_db_instance(), stop_db_instance() |
| VPC | 서브넷, 라우팅 | describe_vpcs(), describe_subnets() | create_vpc(), delete_subnet() |
| ELB | 로드밸런서 | describe_load_balancers() | create_load_balancer(), delete_load_balancer() |
| ECS | 클러스터, 서비스 | list_clusters(), describe_services() | update_service(), run_task() |
| EKS | 클러스터 | list_clusters(), describe_cluster() | create_cluster(), delete_cluster() |
| CloudFormation | 스택 | describe_stacks() | create_stack(), delete_stack() |
| SNS | 주제, 구독 | list_topics(), list_subscriptions() | create_topic(), publish() |
| SQS | 큐 | list_queues() | send_message(), receive_message() |
| Billing/Cost Explorer | 비용/사용량 | get_cost_and_usage() | (읽기 전용) |
| Tagging | 리소스 태그 | get_resources() (resourcegroupstaggingapi) | tag_resources(), untag_resources() |

중간중간 커비는.. 제가 좋아해서.. 넣습니다.. 히히
python --version
# 또는
python3 --version
1-1. 없는 경우 Python 설치
mkdir test
cd test
python -m venv .venv
.\.venv\Scripts\Activate.ps1 # Windows
source .venv/bin/activate # macOS/Linux
pip install boto3 python-dotenv
# 선택 설치
pip install requests
#설치된 패키지 저장
pip freeze > requirements.txt
.env
AWS_ACCESS_KEY_ID=your_access_key # 계정 키 입력
AWS_SECRET_ACCESS_KEY=your_secret_key # 계정 시크릿키 입력
AWS_REGION=ap-northeast-2 # 계정 리전
주의! .env 파일은 절대 커밋하지 않도록 .gitignore에 추가하세요!
import os
import boto3
from dotenv import load_dotenv
# .env 파일에서 환경 변수 로드
load_dotenv()
aws_access_key = os.getenv("AWS_ACCESS_KEY_ID")
aws_secret_key = os.getenv("AWS_SECRET_ACCESS_KEY")
aws_region = os.getenv("AWS_REGION")
# EC2 client 생성
ec2 = boto3.client(
"ec2",
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
region_name=aws_region
)
# S3 client 생성
s3 = boto3.client(
"s3",
aws_access_key_id=aws_access_key,
aws_secret_access_key=aws_secret_key,
region_name=aws_region
)
# EC2 인스턴스 조회
def list_ec2_instances():
print("🖥 EC2 인스턴스 목록:")
response = ec2.describe_instances()
for reservation in response["Reservations"]:
for instance in reservation["Instances"]:
print(f"- Instance ID: {instance['InstanceId']}, State: {instance['State']['Name']}")
# S3 버킷 조회
def list_s3_buckets():
print("\n🪣 S3 버킷 목록:")
response = s3.list_buckets()
for bucket in response["Buckets"]:
print(f"- {bucket['Name']}")
# 실행
if __name__ == "__main__":
list_ec2_instances()
list_s3_buckets()
python test.py
🖥 EC2 인스턴스 목록:
- Instance ID: i-0123456789abcdef0, State: running
- Instance ID: i-0abcdef1234567890, State: stopped
🪣 S3 버킷 목록:
- my-project-logs
- static-assets-kwon
import boto3
print(boto3.session.Session().get_available_services())
import boto3
client = boto3.client('ec2')
print(dir(client))
잘 따라오셨나요?
boto3 초기화 시 Session을 사용하는 방식도 추후에 다루어 보겠습니다!