简体   繁体   English

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

[英]Access denied when assuming role as IAM user via boto3

Issue问题

I have an IAM user, and an IAM role.我有一个 IAM 用户和一个 IAM 角色。 I am trying to configure the IAM user to have permission to assume the IAM role using STS.我正在尝试将 IAM 用户配置为有权使用 STS 代入 IAM 角色。 I am not sure why I receive an "Access Denied" error.我不确定为什么会收到“拒绝访问”错误。

Details细节

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

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

IAM user policy to allow assume role:允许代入角色的 IAM 用户策略:

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

Code:代码:

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
)

Error:错误:

botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the AssumeRole operation: User: arn:aws:iam::123456789:user/athena-external-user is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::123456789:role/athena_access botocore.exceptions.ClientError:调用 AssumeRole 操作时发生错误 (AccessDenied):用户:arn:aws:iam::123456789:user/athena-external-user 无权执行:sts:AssumeRole on resource:arn: aws:iam::123456789:role/athena_access

Of course, I found the solution shortly after posting the question.当然,我在发布问题后不久就找到了解决方案。

The IAM role needs to have a TrustRelationship policy for the user that will assume the role. 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"
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM