AWS: How to retrieve Instance Meta Data from with in Instance

neotam Avatar

AWS: How to retrieve Instance Meta Data from with in Instance
Posted on :

Instance meta deta explains lot of things related to the running or stopped EC2 instance which include ami-id which denotes the AMI used to provision the instance, instance-id which is the unique instance ID that can be used to perform actions like start, stop and restart through AWS CLI, and instance-type etc.

AWS Providies the in-genious way to retrieve the meta data about self (from with in running instance ) by

To view all categories of instance metadata from within a running instance, use the following IPv4 or IPv6 URIs.

IPv4

http://169.254.169.254/latest/meta-data/

IPv6

http://[fd00:ec2::254]/latest/meta-data/

To get all meta data fields

curl http://169.254.169.254/latest/meta-data/

All possible top lelve meta fields or items are as follows

ami-id
ami-launch-index
ami-manifest-path
block-device-mapping/
events/
hostname
identity-credentials/
instance-action
instance-id
instance-life-cycle
instance-type
local-hostname
local-ipv4
mac
metrics/
network/
placement/
profile
public-hostname
public-ipv4
public-keys/
reservation-id
security-groups
services/

For example to get the instance id

curl http://169.254.169.254/latest/meta-data/instance-id

Like wise to get the instance type

curl http://169.254.169.254/latest/meta-data/instance-type

Easy way to get the local or private of an instance by retrieving meta data

curl http://169.254.169.254/latest/meta-data/local-ipv4

Here is the small snippet that will print all meta information regarding host instance from which this script is being executed


import requests 

URL = 'http://169.254.169.254/latest/meta-data/'

resp = requests.get(URL)
meta_fields = resp.text.split('\n')

for i in meta_fields:
    url = f'{URL}/{i}'
    r = requests.get(url)
    data = r.text 
    metainfo = f'{i} : {data}'
    print(metainfo)

You can also use the meta data URL to check if script is running on AWS instance as follows

import requests

def is_running_on_aws_instance():
    try:
        # Make a request to the instance metadata service
        response = requests.get('http://169.254.169.254/latest/meta-data/')
        
        # If the request is successful, it means the script is running on an AWS instance
        if response.status_code == 200:
            return True
    except requests.exceptions.RequestException:
        pass

    return False


# Usage example
if __name__ == '__main__':
    if is_running_on_aws_instance():
        print("The script is running on an AWS instance.")
    else:
        print("The script is not running on an AWS instance.")

Pricing

You are not billed for HTTP requests used to retrieve instance metadata and user data from with in instance using URL –http://169.254.169.254/latest/meta-data/

Leave a Reply

Your email address will not be published. Required fields are marked *