我有一个关于如何使用boto3从所有地区获取所有CloudTrail事件的快速问题.
当我运行下面的脚本时,它只列出来自CloudTrail主区域(这意味着创建CloudTrail的区域)的实例。
response = trail.lookup_events(
LookupAttributes = [
{
'AttributeKey': 'EventName',
'AttributeValue': 'RunInstances'
}
],
StartTime = datetime(2021,8,21),
EndTime = datetime(2021,8,24),
)
是否有任何方法可以从所有地区获得所有CloudTrail事件?
提前感谢您的帮助!
仅供参考,我的CloudTrail的MultiRegion选项是开启的。
使用boto3配置更改区域将有效。
我使用下面的regions_work_with_service
函数作为获取所有区域的代码片段。然后循环与区域做一些事情。
下面,client = boto3.client("cloudtrail", config=my_config)
设置一个区域,客户端运行lookup_events
并打印事件(如果有)。
import boto3
from botocore.config import Config
def regions_work_with_service(service):
regions = []
client = boto3.client(service)
response = client.describe_regions()
for item in response["Regions"]:
regions.append(item["RegionName"])
return regions
regions = regions_work_with_service("ec2")
for region in regions:
print(f"region: {region}")
my_config = Config(region_name=region)
client = boto3.client("cloudtrail", config=my_config)
response = client.lookup_events(
LookupAttributes=[
{"AttributeKey": "EventName", "AttributeValue": "RunInstances"}
]
)
if response["Events"]:
for i in range(len(response["Events"])):
event = json.loads(response["Events"][i]["CloudTrailEvent"])
print(event)