TODD 의 사과농장

Python 으로 AWS CLI 를 통해 Security Group 데이터 수집하기 본문

카테고리 없음

Python 으로 AWS CLI 를 통해 Security Group 데이터 수집하기

TODD 2025. 4. 27. 18:58

 

AWS CLI를 사용하여 EC2 보안 그룹 데이터를 조회하고 Markdown 표로 변환하는 Python 스크립트.
이 코드는 AWS 인프라 관리 자동화에 활용 가능함.

AWS 보안 그룹 데이터 수집 및 Markdown 변환 코드

 
 
import subprocess
import json from py_markdown_table.markdown_table
import markdown_table
 
def get_security_groups():
"""AWS CLI로 보안 그룹 정보 조회"""
   try: cmd = "aws ec2 describe-security-groups --query 'SecurityGroups[*].{GroupName:GroupName, GroupId:GroupId, VpcId:VpcId, Description:Description}' --output json"
      result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
      return json.loads(result.stdout)
   except Exception as e:
      print(f"AWS CLI 실행 오류: {e}")
      return []
 
def save_markdown_table(data, filename):
"""Markdown 테이블로 변환 후 저장"""
   try:
      table = markdown_table(data).set_params(
         padding_width=2,
         padding_weight='centerleft',
         row_sep='markdown'
      ).get_markdown()
 
      with open(filename, 'w') as f:
         f.write(table)
      print(f"{filename} 저장 완료!")
   except Exception as e:
      print(f"Markdown 변환 오류: {e}")
 
if __name__ == "__main__":
   security_groups = get_security_groups()
   if security_groups:
      save_markdown_table(security_groups, "security_groups.md")
 
 

코드 설명

  1. AWS CLI 연동: subprocess 모듈로 AWS CLI 명령어 실행8
  2. 데이터 필터링: --query 파라미터로 필요한 필드만 선택적 추출3
  3. JSON 파싱: CLI 출력 결과를 Python 딕셔너리로 변환
  4. Markdown 변환: py-markdown-table 라이브러리로 표 생성7
  5. 파일 저장: 결과를 security_groups.md 파일에 저장

 

 

Comments