简体   繁体   中英

How can I look up all CloudTrail events from all regions using boto3?

I have a quick question about how to get all CloudTrail events from all regions with boto3 .

When I run the following script, it only lists up the instances from the CloudTrail home region (which means the region that CloudTrail was created).


response = trail.lookup_events(
    LookupAttributes = [
        {
            'AttributeKey': 'EventName',
            'AttributeValue': 'RunInstances'
        }
    ],
    StartTime = datetime(2021,8,21),
    EndTime = datetime(2021,8,24),
)

Is there any way that I can get all the CloudTrail events from all regions?

Thanks for your help in advance!

FYI, the MultiRegion option is on for my CloudTrail.

Changing region with boto3 config will work.

I use the regions_work_with_service function below as a snippet for getting all regions. And then loop with regions to do something.

Below, client = boto3.client("cloudtrail", config=my_config) set one region, and the client run lookup_events and events are printed (if any).

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM