AWS CLI requests "ec2 describe-instances" and "ec2 describe-iam-instance-profile-associations" include instance profile in the "IamInstanceProfile" property.
This includes ARN, for example:
arn:aws:iam::123:instance-profile/AmazonSSMRoleForInstancesQuickSetup
In such a case the last segment, "AmazonSSMRoleForInstancesQuickSetup" in this example, is the IAM role name. This is also suggested in answers to multiple existing questions:
- https://stackoverflow.com/questions/69002676/how-to-get-an-aws-roles-friendly-name-from-its-arn
- https://stackoverflow.com/questions/68347014/is-there-a-way-to-get-name-of-iam-role-attached-to-an-ec2-instance-with-boto3
- https://stackoverflow.com/questions/70307973/how-to-get-arn-of-an-iam-role
- https://stackoverflow.com/questions/69002676/how-to-get-an-aws-roles-friendly-name-from-its-arn
But sometimes the ARN in the instance profile will look like this:
arn:aws:iam::123:instance-profile/eks-ab13cc88-bc13-13bc-acdc-1234567890ab
And the last part is not a role name anymore - actually, it seems to be "Auto Scaling Group name". AWS web interface does show the assigned IAM role in both cases inside the instance properties.
How could the role name be reliably obtained for EC2 instances in all cases using AWS CLI?