EC2 Metadata Python Library
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
- breaking ec2-metadata version 3.0.0 and above exclusively uses Instance Metadata Service Version 2 (IMDSv2). If your EC2 instance is configured to *only* allow IMDSv1, this library will not work. Ensure your instance supports IMDSv2.
- gotcha When running `ec2-metadata` within a Docker container on an EC2 instance, you might encounter `requests.exceptions.ReadTimeout` errors. This is often due to IMDSv2's default IP hop limit of 1.
- gotcha Instance metadata and user data are not cryptographically protected and are accessible by any user or process on the instance. Do not store sensitive information like passwords or private keys in user data.
- deprecated The functionality provided by the older `boto` library's `boto.utils.get_instance_metadata` for retrieving EC2 metadata is not ported to `boto3`. `ec2-metadata` was created to serve as a standalone replacement for this specific functionality.
Install
-
pip install ec2-metadata
Imports
- ec2_metadata
from ec2_metadata import ec2_metadata
Quickstart
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.")