我在ec2上使用AWS跨账户访问角色来获取所有安全组规则&我使用了下面的代码。
import boto.ec2
import os
from boto.sts import STSConnection
sts_connection = STSConnection()
assumed_role_object = sts_connection.assume_role(
role_arn="AWS_ARN",
role_session_name="AssumeRoleSession"
)
os.environ["AWS_ACCESS_KEY_ID"] =assumed_role_object.credentials.access_key
os.environ["AWS_SECRET_ACCESS_KEY"] = assumed_role_object.credentials.secret_key
os.environ["AWS_SESSION_TOKEN"] = assumed_role_object.credentials.session_token
conn = boto.ec2.connect_to_region("eu-west-1")
groups = conn.get_all_security_groups()
for group in groups:
print group.name
for rule in group.rules:
print rule.ip_protocol, rule.from_port, rule.to_port, rule.grants
它正在使用角色在基本帐户上按预期工作,但在我尝试使用其他帐户(使用STS从ARN生成临时凭证)时收到以下错误。当我尝试手动执行任何命令或shell脚本时,相同的凭据从aws cli正常工作。我可以使用aws cli获取安全组详细信息,因此身份验证没有问题。
boto.exception.EC2ResponseError: EC2ResponseError: 401 Unauthorized
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>AuthFailure</Code><Message>AWS was not able to validate the provided access credentials</Message></Error></Errors><RequestID>5e15dcba-9c92-4161-ad7d-3ffdf202c972</RequestID></Response>
注意:我不想使用AWS Trusted Advisor