EKS Pod中使用AssumeRoleWithWebIdentity生成AWS Token的代码疑问
Answer to Your EKS Web Identity Token Question
Your current code won't work as-is because the WebIdentityToken parameter expects the actual token content, not the path to the token file stored in AWS_WEB_IDENTITY_TOKEN_FILE. Here's what you need to do instead:
- First, read the token string from the file path specified by the environment variable
- Pass that raw token content as the value for
WebIdentityToken
Corrected Manual Implementation
import os import boto3 sts_client = boto3.client('sts') # Read the token content from the file with open(os.environ['AWS_WEB_IDENTITY_TOKEN_FILE'], 'r') as token_file: web_identity_token = token_file.read().strip() # Call assume_role_with_web_identity with the actual token response = sts_client.assume_role_with_web_identity( RoleArn=os.environ['AWS_ROLE_ARN'], RoleSessionName='mySession', WebIdentityToken=web_identity_token ) # Extract temporary credentials from the response temp_creds = response['Credentials'] print(f"Temporary Access Key: {temp_creds['AccessKeyId']}") print(f"Temporary Secret Key: {temp_creds['SecretAccessKey']}") print(f"Session Token: {temp_creds['SessionToken']}")
Bonus: Automatic Credential Handling (Recommended)
If you're using boto3 version 1.10.0 or newer, you don't need to manually call assume_role_with_web_identity at all. Boto3 will automatically detect the AWS_ROLE_ARN and AWS_WEB_IDENTITY_TOKEN_FILE environment variables and handle credential retrieval/refreshing behind the scenes:
import boto3 # Boto3 uses web identity credentials automatically if the env vars exist s3_client = boto3.client('s3') # Use the client normally without manual credential setup buckets = s3_client.list_buckets()
This is the preferred approach because it reduces boilerplate code and ensures credentials are refreshed properly when they expire.
内容的提问来源于stack exchange,提问作者Punter Vicky
相关产品推荐
相关产品推荐

