本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
刷新短期 Amazon Bedrock API 密钥以提高控制和安全性
一旦您更加熟悉亚马逊 Bedrock,我们强烈建议您不要长期使用亚马逊 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