Skip to main content

Command Palette

Search for a command to run...

How to Build an AWS Lambda Function to List EC2 Instances Across All Regions (Python 3.14 DIY Guide)

Updated
3 min read
How to Build an AWS Lambda Function to List EC2 Instances Across All Regions (Python 3.14 DIY Guide)
P

I’m Pratik Borkar, a Technical Architecture specializing in Oracle Cloud Infrastructure (OCI) and Kubernetes. I have extensive experience designing, automating, and optimizing cloud environments using Terraform, CI/CD pipelines, and container orchestration tools. I enjoy sharing hands-on guides and real-world implementations that help engineers simplify cloud operations, improve scalability, and adopt Infrastructure as Code best practices. When I’m not automating infrastructure, I explore new DevOps tools, contribute to open-source projects, and write about cloud-native technologies.

Managing EC2 instances across multiple AWS regions can quickly become complicated, especially in large or multi-account environments.
If you’ve ever wondered:

  • “How can I get a list of all EC2 instances across all AWS regions?”

  • “How do I build a Lambda function that scans every region safely?”

  • “Why do I get AuthFailure errors when calling DescribeInstances?”

…then this DIY AWS Lambda tutorial is exactly what you need.

In this article, we will walk through creating a fully working Python 3.14 AWS Lambda function that scans every AWS region, safely skips restricted regions, and returns a clean JSON list of all EC2 instances.

This guide is written for operations engineers, cloud admins, DevOps teams, and AWS learners who want a practical scenarios.

Prerequisites

Before you start, make sure you have:

  • An AWS account

  • IAM permissions to create and run Lambda functions

  • Basic knowledge of Python and AWS Console

  • Access to CloudWatch Logs

Step 1: Create the Lambda Function

  1. Go to AWS Console → Lambda

  2. Click Create Function

  3. Choose:

    • Author from scratch

    • Runtime: Python 3.14

    • Architecture: x86_64 or ARM64

  4. Click Create Function

Step 2: Add Required IAM Permissions

Your Lambda role MUST include these permissions:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeInstances",
        "ec2:DescribeRegions"
      ],
      "Resource": "*"
    }
  ]
}

Additionally, CloudWatch logging permissions:

{
  "Effect": "Allow",
  "Action": [
    "logs:CreateLogGroup",
    "logs:CreateLogStream",
    "logs:PutLogEvents"
  ],
  "Resource": "*"
}

These policies allow Lambda to read EC2 information and write logs.

Step 3: Paste the Python 3.14 EC2-Scanning Lambda Code

This version safely handles restricted regions, preventing common errors like:

AuthFailure: AWS was not able to validate the provided access credentials``UnauthorizedOperation

Fully Working Python 3.14 Code

import json
import boto3
from botocore.exceptions import ClientError

def lambda_handler(event, context):
    ec2list = []
    ec2 = boto3.client('ec2')

    # Get all AWS regions
    regions = ec2.describe_regions(AllRegions=True).get('Regions', [])

    for region in regions:
        reg = region['RegionName']
        print(f"* Checking region -- {reg}")

        try:
            client = boto3.client('ec2', region_name=reg)
            paginator = client.get_paginator('describe_instances')

            for page in paginator.paginate():
                for reservation in page.get("Reservations", []):
                    for instance in reservation.get("Instances", []):
                        ec2list.append({
                            "InstanceId": instance.get("InstanceId"),
                            "Region": reg
                        })

        except ClientError as e:
            # Skip restricted or disabled regions
            if "AuthFailure" in str(e):
                print(f"Skipping region {reg}: Not enabled for this account.")
                continue
            else:
                print(f"Error in region {reg}: {e}")
                continue

    return {
        "statusCode": 200,
        "body": json.dumps(ec2list)
    }

This is currently the best and safest multi-region EC2 discovery Lambda code for Python 3.14.

Step 4: Test the Lambda Function

  1. Click Test

  2. Choose Create Test Event

  3. Use this simple test JSON:

{}
  1. Run the test.

You will see logs such as:

Test Event Name
hello-world

Response
{
  "statusCode": 200,
  "body": "[]"
}

Function Logs
START RequestId: c036f21d-83e5-4fa7-b26c-5b286a55ac74 Version: $LATEST
* Checking region -- eu-north-1
* Checking region -- eu-west-3
* Checking region -- eu-west-2
* Checking region -- eu-west-1
* Checking region -- ap-northeast-3
* Checking region -- ap-northeast-2
* Checking region -- me-south-1

Finally, your output will be if any instance is running:

[
  {
    "InstanceId": "i-1234567890abcd",
    "InstanceType": "t3.micro",
    "State": "running",
    "Region": "us-east-1"
  }
]

If your account has no instances, it will return:

[]

Troubleshooting

Error: AuthFailure

This means the region is not enabled for your AWS account.
The provided code already skips these regions safely.

Error: UnauthorizedOperation

You are missing IAM permissions.
Add:

ec2:DescribeInstances
ec2:DescribeRegions

Timeout Errors

Increase Lambda timeout to 30–60 seconds:

Lambda → Configuration → General → Edit → Timeout