9
votes

How to check which IAM roles and it's policy json, are attached to the running EC2 instance?

Is it possible through AWS CLI?

Here the response for aws ec2 ddescribe-instances enter image description here

I tried firing the command - aws iam list-instance-profiles,
it gave me the following error -

An error occurred (AccessDenied) when calling the ListInstanceProfiles operation: User: is not authorized to perform: iam:ListInstanceProfiles on resource:

5

5 Answers

5
votes

Yes. If you look at the response generated by aws ec2 describe-instances command, you'll notice that the resulting JSON data has

IamInstanceProfile -> (structure)

The IAM instance profile associated with the instance, if applicable.

Arn -> (string)

The Amazon Resource Name (ARN) of the instance profile.

Id -> (string)

The ID of the instance profile.

And later, you can use the iam cli interface to fetch policy/role details.

aws iam get-instance-profile --instance-profile-name <name here>
5
votes

No need to look for AWS CLI installed your Machine, Just machine should have internet and no block from metadata. You can curl the metadata from EC2:

curl -s http://169.254.169.254/latest/meta-data/iam/info |grep InstanceProfileArn  | awk '{print $3}'
3
votes

Please run describe-instances command (OSX/Linux/UNIX) to determine whether the selected instance has any IAM Roles/Instance Profiles assigned:

  aws ec2 describe-instances
    --region us-east-1
    --instance-ids i-07a2ad8872fb3226b
    --query 'Reservations[*].Instances[*].IamInstanceProfile'
0
votes

If you're using (Python):

import boto3    
client = boto3.client('ec2')

response = client.describe_instances()

# Example 1 - Short version
for r in response['Reservations']:
  for instance in r['Instances']:
    if instance.get('IamInstanceProfile'):
      print (instance['InstanceId'], instance['IamInstanceProfile'])



# Example 2 - Longer version    
for r in response['Reservations']:
  for instance in r['Instances']:
    if instance.get('IamInstanceProfile'):
      raw = client.describe_iam_instance_profile_associations(
        Filters=[
            {
                'Name': 'instance-id',
                'Values': [instance['InstanceId']]
            }
        ]
      )
      current_res = raw.get('IamInstanceProfileAssociations')[0] # <----- We're passing only one instance id in filter so only one result is returned
      print (current_res.get('InstanceId'), current_res.get('IamInstanceProfile'))
0
votes

Using boto3

ec2 = session.client('ec2') 
iam = session.client('iam')

Describe the instance profile association using ec2 client and fetch the instance profile name

ec2.describe_iam_instance_profile_associations(Filters=[{'Name': 'instance-id','Values': ['i-02a1cde71XXXXXX']}])

Response:

{'IamInstanceProfileAssociations': [{'AssociationId': 'iip-assoc-0f7dd8ceeXXXXXX', 'InstanceId': 'i-02a1cde71XXXXXX', 'IamInstanceProfile': {'Arn': 'arn:aws:iam::12345679012:instance-profile/XYZ', 'Id': 'XXXXXXXXXXXXX'}, 'State': 'associated'}],....... }

Use iam client and do get_instance_profile call to get the RoleName associated with the instanceProfile

iam.get_instance_profile(InstanceProfileName='XYZ')

Response:

{'InstanceProfile': {'Path': '/', 'InstanceProfileName': 'XYZ', 'InstanceProfileId': 'XXXXXXXXXXXXX', 'Arn': arn:aws:iam::12345679012:instance-profile/XYZ', 'CreateDate': datetime.datetime(2021, 6, 10, 16, 15, 8, tzinfo=tzutc()), 'Roles': [{'Path': '/', 'RoleName': 'ABCD', ............... 'RetryAttempts': 0}}

Optionally you can use list_attached_role_policies to know what are the managed policy attached with the role

iam.list_attached_role_policies(RoleName='ABCD')

Response:

{'AttachedPolicies': [{'PolicyName': 'EFG', 'PolicyArn': 'arn:aws:iam::12345679012:policy/EFG'}], 'IsTruncated': ......}}