How to Get the Instance Profile attached to an AWS EC2
If you need to get the IAM Role information from the attached EC2 role directly, you can do the following:
IAM_ROLE=$(curl -s 169.254.169.254/latest/meta-data/iam/info | \
jq -r '.InstanceProfileArn' | cut -d'/' -f2)
This queries the EC2 instance metadata service to get the IAM role name attached to the instance you’re running on. I use this in bootstrap scripts that need to know their own role for logging or conditional logic.
The 169.254.169.254 address is the instance metadata endpoint — it’s only accessible from within the EC2 instance itself. If you’re on IMDSv2 (which AWS recommends), you’ll need to fetch a session token first with a PUT request before the GET will work. The jq and cut combo extracts just the role name from the full ARN.