AWS Developer Tools Blog

EC2Metadata

A few months ago we added a helper utility to the SDK called EC2Metadata. This is a class that provides convenient access to EC2 Instance Metada. The utility surfaces most instance data as static strings and some complex data as .NET structures. For instance, the following code sample illustrates how you can retrieve the current EC2 instance’s Id and network interfaces:

string instanceId = EC2Metadata.InstanceId;
Console.WriteLine("Current instance: {0}", instanceId);

var networkInstances = EC2Metadata.NetworkInterfaces;
foreach(var netInst in networkInstances)
{
    Console.WriteLine("Network Interface: Owner = {0}, MacAddress = {1}", netInst.OwnerId, netInst.MacAddress);
}

The utility also exposes methods to retrieve data that may not have yet been modeled in EC2Metadata. These are EC2Metadata.GetItems(string path) and EC2Metadata.GetData(string path). GetItems returns a collection of items for that source, while GetData returns the metadata for that path (if the path is invalid or the item doesn’t exist, GetData returns null). For example, to retrieve the current instance Id you can use the InstanceId property or, equivalently, you can use GetData:

string instanceId = EC2Metadata.GetData("/instance-id");
Console.WriteLine("Current instance: {0}", instanceId);

Similarly, you can use GetItems to retrieve the available nodes for a specific path:

// Retrieve nodes from the root, http://169.254.169.254/latest/meta-data/
var rootNodes = EC2Metadata.GetItems(string.Empty);
foreach(var item in rootNodes)
{
    Console.WriteLine(item);
}

Note: since instance metadata is accessible only from an EC2 instance, the SDK will throw an exception if you attempt to use this utility anywhere outside of an EC2 instance (for example, your desktop).