通过boto3担任IAM用户时拒绝访问

时间:2019-10-29 22:09:16

标签: python amazon-web-services boto3 amazon-iam

问题

我有一个IAM用户和一个IAM角色。我正在尝试将IAM用户配置为具有使用STS承担IAM角色的权限。我不确定为什么会收到“访问被拒绝”错误。

详细信息

IAM角色:arn:aws:iam::123456789:role/athena_access

IAM用户:arn:aws:iam::123456789:user/athena-external-user

允许角色扮演的IAM用户策略:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "StsAssumeRole",
            "Effect": "Allow",
            "Action": "sts:*",
            "Resource": "arn:aws:iam::123456789:role/athena_access"
        }
    ]
}

代码:

import boto3
os.environ['AWS_ACCESS_KEY_ID'] = '...'
os.environ['AWS_SECRET_ACCESS_KEY'] = '...'

client = boto3.client('sts')
role_to_assume_arn='arn:aws:iam::123456789:role/athena_access'
role_session_name='test_session'
response=client.assume_role(
    RoleArn=role_to_assume_arn,
    RoleSessionName=role_session_name
)

错误:

  

botocore.exceptions.ClientError:调用AssumeRole操作时发生错误(AccessDenied):用户:arn:aws:iam :: 123456789:user / athena-external-user无权执行:sts:AssumeRole on resource :arn:aws:iam :: 123456789:role / athena_access

1 个答案:

答案 0 :(得分:0)

当然,我在发布问题后不久就找到了解决方案。

IAM角色需要为将承担该角色的用户制定一个TrustRelationship策略。

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com",
        "AWS": "arn:aws:iam::123456789:user/athena-external-user"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}