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': ......}}