Print
카테고리: [ Amazon Web Services ]
조회수: 20459

개요

AWS Python SDK인 boto3를 활용해 CloudTrail의 Event 기록을 조회하는 방법에 대해 기술한다.

 

클라이언트 생성

먼저 이벤트를 가져올 AWS 계정에 인증을 진행한다.(하단의 boto3가 자격 증명을 얻는 구조 링크 참고)

여러가지 방법이 있지만 간편한 AccessKey를 활용하여 인증 진행하였다. 

trail = boto3.client('cloudtrail',
aws_access_key_id=id.get('accessKey'),
aws_secret_access_key=id.get('secretKey')
)

 

Look Up Events API 호출

EC2에 발생한 이벤트 중 지난 1일간 있었던 이벤트를 호출 해 보았다. 

생성한 client의 lookup_events를 활용하며 사용할 옵션을 지정한다. 

response = trail.lookup_events(
LookupAttributes=[
{
'AttributeKey': 'EventSource',
'AttributeValue': 'ec2.amazonaws.com'
},
],
StartTime=datetime.combine(date.today() - timedelta(days=1), datetime.min.time()),
EndTime=datetime.combine(date.today(), datetime.min.time()),
#EventCategory='insight',
#MaxResults=10
#NextToken='string'
)

 

LookupAttributes

찾아올 이벤트를 특정하는 옵션이다. 

AttributeKey

필터링할 Attribute를 지정한다. 다음과 같은 옵션들로 필터링 할 수 있다. 이 예제에서는 이벤트가 일어난 소스로 EC2를 선택하였으므로 ResourceType으로 지정하였다. 

'EventId'|'EventName'|'ReadOnly'|'Username'|'ResourceType'|'ResourceName'|'EventSource'|'AccessKeyId'  

AttributeValue

지정한 Key에 대한 값을 지정한다. ec2에 대한 이벤트를 가져올 것이므로 ec2.amazonaws.com으로 지정하였다. 

Start/End Time

이벤트를 가져올 시간 범위를 지정한다. datetime 객체로 설정해야 API 인자로 전달할 수 있다. 

EventCategory

이벤트 카테고리를 선언하며, 지정하지 않으면 해당 이벤트는 리턴되지 않는다. 

MaxResults

가져올 최대 이벤트 갯수를 지정한다. 1~50까지 지정할 수 있으며, 미지정시 기본값은 50이다.

NextToken

결과가 여러 페이지로 출력될 경우 NextToken을 지정하여 다음 API 호출 시 넘겨주어야 한다. 

 

호출 결과

리턴받은 response를 필요에 맞게 파싱하여 사용할 수 있다. 임의로 이벤트 시간만 출력해 보았다. 
 
출력 코드
events = response.get('Events')
for event in events:
print(event.get('EventTime'))
 
출력 결과

이벤트가 발생한 시간들이 출력됨을 확인할 수 있다. 

 
참고

boto3가 자격 증명을 얻는 구조: https://velog.io/@city7310/boto3%EA%B0%80-%EC%9E%90%EA%B2%A9-%EC%A6%9D%EB%AA%85-%EC%A0%95%EB%B3%B4%EB%A5%BC-%EC%96%BB%EC%96%B4%EB%82%B4%EB%8A%94-%EA%B5%AC%EC%A1%B0

AssumeRole으로 boto3 자격 증명: https://docs.aws.amazon.com/ko_kr/IAM/latest/UserGuide/id_roles_use_switch-role-api.html

AWS API doc: https://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_LookupEvents.html

boto3doc: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/cloudtrail.html#CloudTrail.Client.lookup_events