how to get aws account number /id based on EC2 instance ip which is hosted in amazon i have a instance name CTI server it is hosted in one AWS account. I have the details of CTI server like private ip and hosts and able to do ssh this instance through putty .I want the AWS account number /aws account ID of where this instance is created . is their any command to find out account number without login into aws console
You can obtain the account number from within an EC2 instance by querying the instance metadata. The metadata is located in http://169.254.169.254/latest/dynamic/instance-identity/document.
If an IAM role is attached to the instance, you can retrieve it using:
aws sts get-caller-identity
This information is available in the dynamic Instance Metadata. It can be extracted in a number of different ways.
The jq
JSON parser is the best method currently available, and it comes pre-installed on the AWS Linux AMIs.
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .accountId
Most other methods I found online tended to make a long chain of process calls like grep | sed | awk
etc. which is less than ideal. So I explored some alternatives trying to limit the parsing to just one extra process.
The best alternative I could come up with, using only a single pipe, was with sed
and extended regular expressions. Plus, unlike the other solutions, this can even handle the (contrived) scenario of (escaped) double quotes in the middle of an accountId:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | sed -nE 's/.*"accountId"\s*:\s*"(.*)".*/\1/p'
Or, slightly less readable with plain BRE:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | sed -n 's/.*"accountId"\s*:\s*"\(.*\)".*/\1/p'
grep
is an option, but requires GNU grep with PCRE support:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep -oP '"accountId"\s*:\s*"\K[^"]+'
This more portable alternative requires an extra step (if avoiding heavier tools like awk
), but is also more straightforward and easier to understand:
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | grep '"region"' | cut -d\" -f4
The grep
output looks like this:
"region" : "us-east-1"
Then cut
will split on double quotes and pick the fourth field.
I try to avoid using awk for simple uses like this, but it can obviously do the above in one step. It may sometimes be the only available option (e.g busybox):
curl -s http://169.254.169.254/latest/dynamic/instance-identity/document | awk -F'"' '/"accountId"/ { print $4 }'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With