You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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']}")

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 23:07:47