2016-02-28 98 views
0

我有一个脚本从我们自己的内部报告中抽取了很多来自Cloudwatch的指标。请求中包含的安全令牌已过期

该脚本迭代特定区域中的所有EC2实例,并在过去2周内(每次5分钟之内返回5分钟间隔,这正是1440配额)要求5个cloudwatch指标(所有可用统计数据) 。我使用的是假设会话:

session = Session(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=regionName) 
sts = session.client('sts') 
response = sts.assume_role(
    RoleArn=arn, # External role arn 
    RoleSessionName='role-name', 
    ExternalId='<some-id-here>', 
) 
tempAccessKeyId = response['Credentials']['AccessKeyId'] 
tempSecretAccessKey = response['Credentials']['SecretAccessKey'] 
tempSessionToken = response['Credentials']['SessionToken'] 
assumedSession = Session(
    aws_access_key_id=tempAccessKeyId, 
    aws_secret_access_key=tempSecretAccessKey, 
    aws_session_token=tempSessionToken, 
    region_name=regionName) 

在运行该脚本,我得到这个异常:

botocore.exceptions.ClientError: An error occurred (ExpiredToken) when calling the GetMetricStatistics operation: The security token included in the request is expired 

有没有一种方法,以确保令牌不会过期运行脚本时?我正在使用boto3。

回答

1

您正在使用的assume_role方法返回临时安全凭证。从official documentation采取以下:

临时安全证书的有效期为你调用AssumeRole时指定的时间,这可以从900秒(15分钟)到3600秒(1小时)。默认值是1小时。

由于您未使用DurationSeconds关键字参数,因此返回的凭证在缺省1小时内有效。您必须确保获得新的凭据,以便在1小时后发出请求。请参阅从Temporary Security Credentials official documentation如下:

当(甚至之前)临时安全证书过期,用户可以请求新的凭证,只要请他们仍有权这样做的用户。