使用假定角色模拟主要策略

时间:2018-10-23 05:00:17

标签: amazon-web-services aws-iam

我想知道如何通过AWS CLI将simulate-principal-policy用作假定角色。

要提供一些上下文,作为应用程序启动的一部分,我想确保该应用程序具有访问其所需的所有AWS资源所需的必要权限。我通过使用aws sts get-caller-identity获取呼叫者身份并将返回的呼叫者身份用作simulate-principal-policy请求的策略源信息来实现此目的。

当我们的应用程序在EC2上运行时,它将使用假定的角色。因此,get-caller-identity返回一个假定角色arn。

如果我尝试使用用户arn作为策略源arn执行simulate-principal-policy,该命令将正常工作。

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

但是,尝试通过使用假定角色执行上述命令会报告错误。

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.

我们的应用程序在Kubernetes集群上运行,并使用kiam将IAM角色与pod关联。

1 个答案:

答案 0 :(得分:2)

您的请求的问题在于您使用的是“配置文件 ARN”而不是“角色 ARN”。要获取角色 Arn,您可以执行以下操作:

  1. Instance Profile Arn 中提取角色名称:

arn:aws:sts::123456789021:assumed-role/development/development-session 变成 development/development-session

  1. 根据该名称获取实例配置文件:

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

  1. 在生成的文档中找到角色 Arn:
{
   "InstanceProfile":{
      "Roles":[
         {
            "Arn":"arn:aws:iam::992863558783:role/YourRole"
         }
      ]
   }
}
  1. 在模拟主体策略中使用此 ARN

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

在 Python 中,脚本如下所示:

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']
)
相关问题