ec2_metadata_cache#

Get EC2 metadata and leverage cache to reduce the number of requests to AWS.

class simple_aws_ec2.ec2_metadata_cache.Ec2MetadataCache(_update_time: datetime, _instance_id: Optional[str] = None, _instance_type: Optional[str] = None, _region: Optional[str] = None, _public_ipv4: Optional[str] = None, _iam_info: Optional[dict] = None)[source]#

A data container for EC2 metadata with cache backend.

Usage example:

>>> ec2_metadata = Ec2MetadataCache.load()
>>> ec2_metadata.get_instance_id
>>> ec2_metadata.get_instance_type
>>> ec2_metadata.get_region
>>> ec2_metadata.get_public_ipv4
>>> ec2_metadata.get_iam_info
>>> ec2_metadata.get_boto_ses_from_ec2_inside
classmethod from_dict(data: dict)[source]#

Deserialize the data to the class instance.

to_dict()[source]#

Serialize the data to a dictionary.

classmethod load()[source]#

Load the data from the cache file. If cache file does not exist, initialize the cache file.

dump()[source]#

Dump the data to the cache file.

is_expired() bool[source]#

Check if the in-memory cache is expired.

get_instance_id(refresh_cache: bool = True, ignore_cache: bool = False) str[source]#

Get EC2 instance id.

get_instance_type(refresh_cache: bool = True, ignore_cache: bool = False) str[source]#

Get EC2 instance type.

get_region(refresh_cache: bool = True, ignore_cache: bool = False) str[source]#

Get EC2 placement region.

get_public_ipv4(refresh_cache: bool = True, ignore_cache: bool = False) str[source]#

Get EC2 public IPv4 address.

get_iam_info(refresh_cache: bool = True, ignore_cache: bool = False) Dict[str, str][source]#

Get EC2 IAM info. Example response:

{
    "Code" : "Success",
    "LastUpdated" : "2023-01-01T00:00:00Z",
    "InstanceProfileId" : "ABCD..."
    "InstanceProfileArn" : "arn:aws:iam::111122223333:instance-profile/profile-name",
}
get_boto_ses_from_ec2_inside(refresh_cache: bool = True, ignore_cache: bool = False) Session[source]#

Get the boto3 session of the EC2 instance. On EC2, we use the IAM role to get the AWS credentials, and use the EC2 metadata API to get the region.