Shahar Hamuzim Rajuan
Shahar Hamuzim Rajuan

Reputation: 6159

Python boto3- How to work on cross region

I started writing my lambda function using python and boto3,

I managed to work on every region separately but I didn't see how I can work in a few regions together.

This is how I announce my client:

region= 'ap-southeast-2'
ec2 = boto3.client('ec2', region_name=region)

If I do not give it a region it will run on the region you created your lambda function on, which is something I don't want.

Did anyone did it before?

Upvotes: 4

Views: 6329

Answers (2)

Navindu Jayatilake
Navindu Jayatilake

Reputation: 53

Here I have listed all the instances available across multiple regions.

You could do something like,

1. List all regions available.

    client = boto3.client('ec2')


    def get_all_regions():
        all_regions = [ region['RegionName'] for region 
        inclient.describe_regions['Regions']]
        return all_regions

    regions_arr = []
    regions = get_all_regions()

2. Append the result to a python list

    for each_reg in regions:
        regions_arr.append(each_reg)

3. Loop through each and every region in your python list and have the region_name attribute set to it.

    for x in range(0, len(regions_arr)):
         client_2 = boto3.client('ec2', region_name=regions_arr[x])
         response = client_2.describe_instance_status()

         for x in response['InstanceStatuses']:
              print(x['InstanceId'])

Hope this helps. Thanks!

Upvotes: 2

Mark B
Mark B

Reputation: 201058

If you do not give it a region it will use the region your Lambda function is running in.

If you want to make AWS API calls in multiple regions via Boto3 you will have to create a client object for each region, and make separate API calls for each region.

Upvotes: 8

Related Questions