EC2 Metadata Python Library

3.0.0 · active · verified Thu Apr 09

ec2-metadata is a Python library that provides an easy, cached interface to query the EC2 Instance Metadata Service (IMDS). It supports IMDSv2 exclusively and is designed for use within EC2 instances to retrieve details like instance ID, AMI ID, region, and more. The current version is 3.0.0, and it is actively maintained.

Warnings

Install

Imports

Quickstart

Demonstrates how to retrieve basic EC2 instance metadata attributes using the singleton `ec2_metadata` object. This code should be run from within an EC2 instance.

from ec2_metadata import ec2_metadata

try:
    print(f"Region: {ec2_metadata.region}")
    print(f"Instance ID: {ec2_metadata.instance_id}")
    print(f"AMI ID: {ec2_metadata.ami_id}")
    print(f"Instance Type: {ec2_metadata.instance_type}")
except Exception as e:
    print(f"Could not retrieve EC2 metadata: {e}")
    print("This code must be run on an EC2 instance with IMDSv2 enabled and accessible.")

view raw JSON →