Skip to main content

ec2imds, the extensive EC2 Instance Meta Data Service(IMDS) tool

Project description

EC2IMDS

The ec2imds python package is a module and a cli tool for retrieving AWS EC2 instance meta data and user data from the Instance Meta Data Service endpoint. It is an improved version of ec2metadata.

The cli tool prints data in JSON formate to stdout. The module consists of "low-level" utils for traversing the IMDS directory.

Install

pip install ec2imds

CLI Usage

On an EC2 instance, run the module.

# Get everything
python -m ec2imds

# Download user data(treated as binary)
python -m ec2imds -U > userdata

# Get specific categories
python -m ec2imds meta-data/instance-id meta-data/public-ipv4

# Get categories matching the regex
python -m ec2imds -E 'meta-data/placement/.*'

# List all implemented categories
python -m ec2imds -L

For more info on usage, run python -m ec2imds -h.

The cli tool can be used from a shell script in conjunction with jq.

Module Usage

ec2imds uses IMDS v2 only. The IMDS v2 mandates the use of token. IMDSWrapper provides callbacks for saving and loading tokens when sending requests to the IMDS endpoint. Incorporate the callbacks to suit your use case. You can use IMDSWrapper without the callbacks, but you may face issues from token exhaustion in the long run. Following is a simple example from the cli tool.

import datetime
import json
import os

from ec2imds import *

def on_new_token (
		token: str,
		expiry: datetime.datetime,
		endpoint: tuple[str, int]):
	# save the new token
	doc = {
		"token": token,
		"expiry": expiry.isoformat()
	}

	fp = rp.t + os.path.sep + IMDSWrapper.construct_endpoint_str(endpoint)
	os.makedirs(rp.t, 0o700, True)

	saved_umask = os.umask(0o077)
	with open(fp, "w") as f:
		json.dump(doc, f)
	os.umask(saved_umask)

def on_load_token (endpoint: tuple[str, int]) -> tuple[str, datetime.datetime]:
	fp = rp.t + os.path.sep + IMDSWrapper.construct_endpoint_str(endpoint)
	try:
		with open(fp, "rb") as f:
			t = json.load(f)
			return ( t["token"], datetime.datetime.fromisoformat(t["expiry"]) )
	except (FileNotFoundError, json.JSONDecodeError):
		return

Where

  • rp.t is the path to the token directory.

In the token directory, a file will be created to save the taken value and its expiry for each IMDS endpoints, 169.254.169.254:80 and [fd00:ec2::254]:80.

Now, functions for fetching categories are defined in IMDSWrapper.dir_dict.

# Instantiate and set up
w = IMDSWrapper()
w.on_new_token = on_new_token
w.on_load_token = on_load_token

# Get all meta data
all_meta = w.all()

# Get user data
try:
	with (w.open_userdata() as u, open("file", "wb") as f):
		while f.write(w.read(4096)): pass
except:
	...

# Get specific meta data
instance_id = w.dir_dict["meta-data/instance-id"].func()

# Cycle through
for k, v in w.dir_dict.items():
	if k.startswith("meta-data/placement/"):
		print(v.func())

Note that for requests ended in 404, the functions return None.

The module does not define any classes for returned meta data. The functions always return dict for directory data and str, int, bool ... for scalar values. The module is, per se, a low-level util for fetching data from the IMDS.

IPv6 Considerations

See doc/ipv6only.md.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ec2imds-0.0.3.tar.gz (25.0 kB view details)

Uploaded Source

Built Distribution

ec2imds-0.0.3-py3-none-any.whl (22.4 kB view details)

Uploaded Python 3

File details

Details for the file ec2imds-0.0.3.tar.gz.

File metadata

  • Download URL: ec2imds-0.0.3.tar.gz
  • Upload date:
  • Size: 25.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.12.1

File hashes

Hashes for ec2imds-0.0.3.tar.gz
Algorithm Hash digest
SHA256 0872ba8fd825d2e5957c5b22156c3e73ade565b214cb90703adf7a3f7ea3af6d
MD5 e3fa69452b165a9c14c12b1e14c38c68
BLAKE2b-256 e2bbcf045d6f768e2b950442b0771cf7900db02ea14533b2b598d2e91ad116c5

See more details on using hashes here.

File details

Details for the file ec2imds-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: ec2imds-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 22.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.2 CPython/3.12.1

File hashes

Hashes for ec2imds-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 5f5d92f48586f8f3b24e93743255c3631e6f97428119ffa7b6695ff763284a32
MD5 0425b599e59e1f7293e403694bdb531f
BLAKE2b-256 550873ca5f9db21e3da9f4860aa44a2172bf0802da91399f39cf5932baf277b1

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page