本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
重新整理短期 Amazon Bedrock API 金鑰,以提高控制和安全性
一旦您更熟悉 Amazon Bedrock,我們強烈建議您不要使用長期 Amazon Bedrock API 金鑰。反之,您應該使用臨時安全登入資料切換到 ,或切換到短期 Amazon Bedrock API 金鑰。
您可以在aws-bedrock-token-generator
套件的協助下建立指令碼,以程式設計方式在目前金鑰過期時重新產生新的短期金鑰。首先,請確定您已滿足 的先決條件使用 API 產生短期 Amazon Bedrock API 金鑰。
然後,您可以使用下列 Python 指令碼:
from datetime import datetime, timedelta import os import boto3 from botocore.credentials import Credentials from aws_bedrock_token_generator import BedrockTokenGenerator # Replace the following values as necessary SESSION_DURATION = timedelta(hours=12) # 12 hours is the maximum EFFECTIVE_TOKEN_DURATION = min(SESSION_DURATION, timedelta(hours=12)) # The token can last no longer than 12 hours ROLE_ARN = "arn:aws:iam::111122223333:role/TargetRole" # Ensure that the identity you're authenticating with has permissions to assume this role ROLE_SESSION_NAME = "your-session-name" REGION = "us-east-1" def get_session_from_assume(): sts = boto3.client("sts") response = sts.assume_role( RoleArn=ROLE_ARN, RoleSessionName=ROLE_SESSION_NAME, DurationSeconds=int(SESSION_DURATION.total_seconds()) ) creds = response["Credentials"] return Credentials( access_key=creds["AccessKeyId"], secret_key=creds["SecretAccessKey"], token=creds["SessionToken"] ) # Step 1: Generate initial token and note timestamp generator = BedrockTokenGenerator() creds = get_session_from_assume() token = generator.get_token(creds, region=REGION) token_created_at = datetime.utcnow() # Step 2: Later in your long lived process — before using the token if datetime.utcnow() - token_created_at >= EFFECTIVE_TOKEN_DURATION: creds = get_session_from_assume() token = generator.get_token(creds, region=REGION) token_created_at = datetime.utcnow() else: # Token is still valid pass # Set the token as an environment variable so you can use it in API calls os.environ['AWS_BEARER_TOKEN_BEDROCK'] = token