2016-02-28 100 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如下:

當(甚至之前)臨時安全證書過期,用戶可以請求新的憑證,只要請他們仍有權這樣做的用戶。