Getting informations on a running instance from the inside is a tedious task and it’s usually done in an insecure and error prone way.
With this article we want to show you our way to get instance tags from the inside of a running instance.
Setting up your Ec2 instance with an IAM role
Setting up an IAM role
The first step to implement a secure solution is to create an IAM role that our instance will use as an “Instance role”. The role must have the “AmazonEC2ReadOnlyAccess” policy attached. Alternatively you can create a more restricted policy with only the “Action”: “ec2:Describe*” permission. From now on we call this role “MyEC2ReadOnlyAccess”.
Launch your new instance
At this point, you can run a new instance with your newly created role. The wizard let’s you specify which role to attach to an EC2 instance; alternatively, you can use Ansible or other methods to launch an instance.
Getting the instance details
Now you can ssh into your new machine and you will have access to all EC2 attributes and all tags. AWS gives an handy way to get some of the basic details of a running instance using an internal web service at the address http://169.254.169.254.
The important thing for us is getting the instance ID:
1 |
curl -s http://169.254.169.254/latest/meta-data/instance-id |
With the instance ID we can query additional attributes like tags and other details. Doing that requires using the aws cli console.
For example to have the instance “Name” you can do:
1 2 |
$ aws ec2 describe-tags --filters "Name=resource-id,Values=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)" "Name=key,Values=Name" | jq ".Tags[0].Value" "myEC2Instance" |
With this command instead you can explore all tags of your running instance:
1 |
$ aws ec2 describe-tags --filters "Name=resource-id,Values=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)" | jq . |
We hope you enjoyed reading this article, leave a comment if you find it useful. Ciao!