使用boto3访问AWS Secrets Manager时遇权限拒绝问题求助
问题描述
我需要在AWS组织内的其他账号中使用账号A的Secret,已完成以下配置:
- 为Secret配置了组织级权限策略(见下方)
- 使用KMS密钥加密该Secret
- 创建了跨组织角色用于访问资源
通过AWS CLI从账号B获取Secret完全正常,但使用Python boto3调用时收到权限拒绝错误:
botocore.exceptions.ClientError: An error occurred (AccessDeniedException) when calling the GetSecretValue operation: User: arn:aws:sts:::assumed-role// is not authorized to perform: secretsmanager:GetSecretValue on resource: because no identity-based policy allows the secretsmanager:GetSecretValue action
CLI成功执行示例:
$ aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:eu-central-1:291854329851:secret:D011358-f9gGzq --region eu-central-1 { "ARN": "arn:aws:secretsmanager:eu-central-1:<acc number>:secret:Cuser-f9gGzq", "Name": "Cuser", "VersionId": "c4537bdf-3aff-4e13-b355-36890834a407", "SecretString": "{\"C user\":\"password\"}", "VersionStages": [ "AWSCURRENT" ], "CreatedDate": 1690539987.039 }
Secret权限策略:
{ "Version" : "2012-10-17", "Statement" : [ { "Sid" : "AllowUseOfTheKey", "Effect" : "Allow", "Principal" : { "AWS" : "*" }, "Action" : "secretsmanager:GetSecretValue", "Resource" : "*", "Condition" : { "StringEquals" : { "aws:PrincipalOrgID" : "orgid" } } } ] }
排查与解决建议
1. 核对boto3会话的身份凭证
CLI成功但boto3失败,首先确认两者使用的身份是否一致:
- 打印boto3调用者身份,对比CLI输出:
同时在CLI执行import boto3 sts_client = boto3.client('sts') print(sts_client.get_caller_identity()['Arn'])aws sts get-caller-identity,确保两个ARN完全匹配。如果不一致,说明boto3未正确使用跨组织角色,需检查会话初始化逻辑(比如assume_role调用是否正确,或者凭证链是否加载了正确配置)。
2. 验证Secret资源策略的条件匹配
错误提示提到"无身份策略允许该操作",但当前配置的是资源级策略,需确认:
- 将策略中的
"orgid"替换为实际AWS组织ID(可通过aws organizations describe-organization获取),确保拼写完全正确。 - 验证调用方身份属于目标组织:通过CLI获取调用者ARN后,在账号A中执行
aws iam get-user --user-name <用户名>或aws iam get-role --role-name <角色名>,查看返回结果的Tags中是否包含aws:PrincipalOrgID标签且值正确。
3. 检查KMS密钥的权限
由于Secret用KMS加密,即使Secret权限通过,KMS密钥的权限也可能导致拒绝:
- 确保KMS密钥的资源策略允许组织内账号角色执行
kms:Decrypt操作,添加类似规则:{ "Effect": "Allow", "Principal": "*", "Action": "kms:Decrypt", "Resource": "*", "Condition": { "StringEquals": { "aws:PrincipalOrgID": "你的组织ID" } } }
4. 确认boto3客户端的区域配置
CLI指定了--region eu-central-1,需确保boto3客户端也使用相同区域:
- 初始化客户端时明确指定区域:
避免因默认区域不匹配导致资源定位或权限问题。secretsmanager_client = boto3.client('secretsmanager', region_name='eu-central-1')
5. 检查跨组织角色的信任与权限策略
- 信任策略必须允许组织内账号身份扮演该角色:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "aws:PrincipalOrgID": "你的组织ID" } } } ] } - 角色权限策略需明确允许
secretsmanager:GetSecretValue操作(即使Secret有资源策略,身份自身的权限策略也需要允许该动作):{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "secretsmanager:GetSecretValue", "Resource": "arn:aws:secretsmanager:eu-central-1:291854329851:secret:D011358-f9gGzq" } ] }
内容的提问来源于stack exchange,提问作者Linuxuser
相关产品推荐
相关产品推荐

