AWS 환경에서 운영 중인 다양한 리소스를 효율적으로 검색하고 관리하려면, AWS Resource Explorer를 활용하면 좋습니다.
이 글에서는 AWS Resource Explorer의 개념과 함께 AWS Organizations을 활용하여 계정 전체의 리소스를 검색하는 방법,
그리고 Python을 사용해 AWS 리소스를 자동으로 수집하고 태그 정보를 포함하는 CSV 파일을 생성하는 방법을 소개합니다.
1️⃣ AWS Resource Explorer란?
AWS Resource Explorer는 AWS 계정에서 운영 중인 다양한 리소스를 빠르게 검색할 수 있도록 지원하는 서비스입니다.
이 기능을 사용하면 EC2, S3, RDS, Lambda 등 여러 AWS 리소스를 통합적으로 검색할 수 있습니다.
🛠 주요 기능
✅ AWS 리소스 검색
- AWS 계정에 존재하는 모든 리소스를 빠르게 검색 가능
- 특정 서비스(EC2, S3, Lambda 등) 또는 특정 태그(Tag) 기준으로 필터링 가능
✅ Cross-Region 검색 지원
- 여러 리전(Region)에 걸쳐 있는 리소스를 한 번에 검색 가능
✅ AWS Organizations 지원
- AWS Organizations를 사용하면, 여러 AWS 계정에 대한 통합 검색이 가능
- 조직 내의 여러 계정에서 리소스를 검색하여 한 곳에서 관리 가능
✅ API 및 CLI 지원
- AWS SDK(Boto3) 또는 AWS CLI를 활용하여 프로그램에서 자동화 가능
2️⃣ AWS Resource Explorer 활성화 방법
AWS Resource Explorer를 사용하려면 먼저 계정에서 기능을 활성화해야 합니다.
🛠 AWS Management Console에서 활성화
- AWS Console 접속 → Resource Explorer 검색 후 이동
- Resource Explorer 활성화 버튼 클릭
- View 생성: 검색 가능한 리소스 그룹(View)을 생성
- 기본 검색 리전 설정 (Cross-Region 검색 가능)
🛠 AWS CLI로 활성화
# Resource Explorer 활성화
aws resource-explorer-2 create-index --region ap-northeast-2
# 기본 검색 리전 설정
aws resource-explorer-2 update-index --region ap-northeast-2 --type AGGREGATOR
# View 생성
aws resource-explorer-2 create-view --region ap-northeast-2 --view-name all-resources
3️⃣ AWS Organizations와 함께 Resource Explorer 사용하기
AWS Organizations를 활용하면, 단일 계정이 아니라 조직 내 모든 계정에서 리소스를 검색할 수 있습니다.
🛠 Organizations와 Resource Explorer 통합 설정
- AWS Organizations 활성화
- 관리 계정에서 AWS Organizations을 활성화
- AWS Resource Explorer 권한 부여
- 조직의 모든 계정에서 Resource Explorer를 사용할 수 있도록 설정
- Cross-Account 검색 활성화
- 관리 계정에서 검색 가능한 AGGREGATOR 인덱스를 설정해야 함
🛠 Organizations 활성화 관련 CLI 명령어
# AWS Organizations에서 조직 생성 (관리 계정에서 실행)
aws organizations enable-aws-service-access --service-principal resource-explorer-2.amazonaws.com
# AWS Organizations 내 계정 추가
aws organizations invite-account-to-organization --target Id=<계정ID> --target Type=ACCOUNT
4️⃣ AWS Resource Explorer를 활용한 리소스 검색
Resource Explorer가 활성화되면, AWS Console 또는 CLI에서 리소스를 검색할 수 있습니다.
🛠 AWS CLI를 이용한 검색
# 특정 리소스 검색 (예: EC2 인스턴스)
aws resource-explorer-2 search --query-string "resourceType:AWS::EC2::Instance" --region ap-northeast-2
# 모든 리소스 검색
aws resource-explorer-2 search --query-string "*" --region ap-northeast-2
5️⃣ Python을 활용한 AWS 리소스 검색 및 태그 정보 저장
이제 AWS Resource Explorer API를 활용하여, 모든 AWS 리소스를 검색하고, 태그 정보를 포함하여 CSV 파일로 저장하는 코드를 작성합니다.
콘솔 상에서는 1000개 이상의 전체 리소스 수집에 한계가 있어 SDK 를 이용하여 전체 리소스를 수집 하는 코드
📌 Python 코드 (aws_resource_all.py)
아래 코드는 모든 AWS 리소스를 가져오고 태그 정보를 포함하여 CSV로 저장하는 코드입니다.
특히, log-group 리소스의 경우, Identifier 값을 더 정확하게 가져오도록 보완되었습니다.
# -*- coding: utf-8 -*-
import boto3
import csv
import time
# ✅ 사용할 리전
region = "ap-northeast-2"
# ✅ AWS 클라이언트 생성
resource_explorer_client = boto3.client("resource-explorer-2", region_name=region)
tagging_client = boto3.client("resourcegroupstaggingapi", region_name=region)
# ✅ 사용할 View ARN
# ✅ View ARN 입력
view_arn = "arn:aws:resource-explorer-2:ap-northeast-2:1111111111:view/all-resources/569dfa7e-c4fa-4ca9-97df-xxxxxxxxxx"
# ✅ CSV 파일명
csv_filename = "aws_all_resources_with_tags.csv"
# ✅ 동적으로 태그 Key를 수집할 Set
all_tag_keys = set()
# ✅ 모든 리소스를 저장할 리스트
resources_data = []
# ✅ 1️⃣ 모든 리소스를 가져오기
next_token = None
while True:
try:
if next_token:
response = resource_explorer_client.list_resources(ViewArn=view_arn, MaxResults=100, NextToken=next_token)
else:
response = resource_explorer_client.list_resources(ViewArn=view_arn, MaxResults=100)
resources = response.get("Resources", [])
if not resources:
break
for resource in resources:
arn = resource.get("Arn", "N/A")
service = arn.split(":")[2] if ":" in arn else "N/A"
identifier = arn.split("/")[-1] if "/" in arn else arn.split(":")[-1]
if service == "logs" and "log-group:" in arn:
identifier = arn.split("log-group:")[-1]
tag_dict = {}
try:
tag_response = tagging_client.get_resources(ResourceARNList=[arn])
tag_list = tag_response.get("ResourceTagMappingList", [])
if tag_list:
for tag in tag_list[0].get("Tags", []):
tag_key = f"Tag:{tag.get('Key', 'Unknown')}"
tag_value = tag.get("Value", "(not tagged)")
tag_dict[tag_key] = tag_value
all_tag_keys.add(tag_key)
except Exception as tag_error:
print(f"태그 정보를 가져올 수 없음: {tag_error}")
resources_data.append({
"Identifier": identifier,
"ARN": arn,
"Tags": tag_dict,
})
next_token = response.get("NextToken")
if not next_token:
break
time.sleep(1)
except Exception as e:
print(f"❌ 오류 발생: {e}")
break
# ✅ 2️⃣ CSV 저장
with open(csv_filename, mode="w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
header = ["Identifier", "ARN"] + sorted(all_tag_keys)
writer.writerow(header)
for resource in resources_data:
row = [resource["Identifier"], resource["ARN"]]
for tag_key in sorted(all_tag_keys):
row.append(resource["Tags"].get(tag_key, "(not tagged)"))
writer.writerow(row)
print(f"✅ {csv_filename} 파일로 저장 완료!")
🚀 마무리
✅ AWS Resource Explorer를 활용하면 모든 AWS 리소스를 빠르게 검색하고 관리할 수 있음
✅ AWS Organizations을 설정하면 여러 AWS 계정에서 검색 가능
✅ Python과 Boto3를 활용하면 AWS 리소스를 자동으로 검색하고 태그 정보를 포함하여 CSV 저장 가능
🔥 이제 Resource Explorer를 활용하여 AWS 리소스를 효율적으로 관리하세요! 🚀
'Tech > AWS' 카테고리의 다른 글
🎯 Terraform 변수 참조 구조 제대로 이해하기 (모듈 + 환경 구성 예시 기반) (0) | 2025.04.03 |
---|---|
AWS CLI로 생성 되어 있는 EC2 인스턴스에 Private IP 태그 자동 추가하는 방법 (실습 스크립트 포함) (0) | 2025.03.24 |
EC2 인스턴스 생성 시 Private IP 자동 태그 추가하는 방법 (EventBridge + Lambda 자동화) (0) | 2025.03.22 |