Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to get EC2 instance attributes within the instance itself

Can you guys show me how to retrieve instanceId, dns public name and type of current EC2 instance from where I'm running the code...

I'm playing with DescribeInstanceAttribute(), but it needs to supply the instanceId to the request, and I can't find how to get the id of currently running instance.

like image 216
iLemming Avatar asked Nov 07 '12 16:11

iLemming


People also ask

How do I find my EC2 instance metadata?

To view instance metadata, you can only use the link-local address of 169.254. 169.254 to access. Requests to the metadata via the URI are free, so there are no additional charges from AWS. Using the curl tool on Linux or the PowerShell cmdlet Invoke-WebRequest on Windows, you will first create your token.

How do I export EC2 instance details?

Click on the number below the Instance count to view the discovered EC2 instance opsData. Click on Export. In the Export Data as CSV pop up box, enter select the S3 bucket and SNS topic that was created in the prerequisites. Enter an optional SNS topic message and click Export.

What URL can be used to view instance user data from within a running instance?

Can be accessed using the URL http://169.254.169.254/latest/dynamic/ Note: Although you can only access instance metadata and user data from within the instance itself, the data is not protected by cryptographic methods. Anyone who can access the instance can view its metadata.


1 Answers

There's a much easier method than making a web API call, the .NET SDK.

See the SDK documentation for EC2InstanceMetadata here

For example, if you need InstanceId you can use:

Amazon.Util.EC2InstanceMetadata.InstanceId.ToString();

All the other properties are available in a similar manner.

Note that the SDK used to have Amazon.EC2.Utils - this was deprecated in 2015 and moved to Amazon.Util namespace

like image 63
Lou O. Avatar answered Oct 26 '22 07:10

Lou O.