Simulate Principal Policy using assumed role

Viewed 2013

I was wondering how to use simulate-principal-policy using the AWS CLI for an assumed role.

To provide some context, as part of my application's startup, I want to ensure that the application has the necessary permissions to access all the AWS resources it needs. I do this by getting the caller identity using aws sts get-caller-identity and use the returned caller identity as the policy source arn for the simulate-principal-policy request.

When our application runs on EC2, it uses an assumed role. so, get-caller-identity returns an assumed role arn.

If I try to execute simulate-principal-policy using my user arn as the policy source arn, the command works fine.

aws iam simulate-principal-policy --action-names "sqs:Receivemessage" --policy-source-arn "arn:aws:sts::123456789021:user/divesh"

However, trying to execute the command above by using an assumed role reports an error.

aws iam simulate-principal-policy --action-names "sqs:Receivemessage" --policy-source-arn "arn:aws:sts::123456789021:assumed-role/development/development-session"
An error occurred (InvalidInput) when calling the SimulatePrincipalPolicy operation: Invalid Entity Arn: arn:aws:sts::123456789021:assumed-role/development/development-session does not clearly define entity type and name.

Our application runs on a Kubernetes cluster and uses kiam to associate IAM roles to pods.

1 Answers

The problem with your request is that you are using the "Profile ARN" instead of the "Role ARN". To get the Role Arn, you can do the following:

  1. Pull the Role Name from the Instance Profile Arn:

arn:aws:sts::123456789021:assumed-role/development/development-session becomes development/development-session

  1. Get the instance profile based on that name:

aws iam get-instance-profile --instance-profile-name Instance Profile Arn

  1. Find the Role Arn in the resulting document:
{
   "InstanceProfile":{
      "Roles":[
         {
            "Arn":"arn:aws:iam::992863558783:role/YourRole"
         }
      ]
   }
}
  1. Use this ARN in simulate-principal-policy

aws iam simulate-principal-policy --action-names "sqs:Receivemessage" --policy-source-arn "arn:aws:iam::992863558783:role/YourRole"

In Python, the script would look like this:

import boto3

iam= boto3.client('iam')

profileArn = 'arn:aws:sts::123456789021:assumed-role/development/development-session'
iamProfileName = iamInstanceProfileArn.split(':assumed-role/')[1]
profile = iam.get_instance_profile(InstanceProfileName=iamProfileName)
policySourceArns = []

for role in profile['InstanceProfile']['Roles']:
    policySourceArns.append(role['Arn'])

retval = iam.simulate_principal_policy(
    PolicySourceArn = policySourceArns[0],
    ActionNames = ['sqs:Receivemessage']
)
Related