AWS凭证文件中包含多个角色相同配置文件,可以通过使用不同的配置文件名称来解决。以下是一个示例代码:
import boto3
from botocore.exceptions import ProfileNotFound
def get_credentials(profile_name):
try:
session = boto3.Session(profile_name=profile_name)
credentials = session.get_credentials()
return credentials
except ProfileNotFound:
print(f"Profile '{profile_name}' not found.")
return None
# 定义要使用的配置文件名称列表
profile_names = ['profile1', 'profile2', 'profile3']
# 使用不同的配置文件名称获取凭证
for profile_name in profile_names:
credentials = get_credentials(profile_name)
if credentials is not None:
# 打印凭证的访问密钥和秘密密钥
print(f"Profile: {profile_name}")
print(f"Access key: {credentials.access_key}")
print(f"Secret key: {credentials.secret_key}")
print("")
在上面的示例中,我们定义了一个get_credentials
函数,它接受一个配置文件名称作为参数,并返回与该配置文件关联的凭证。然后,我们定义了一个配置文件名称列表profile_names
,并使用循环遍历每个配置文件名称来获取相应的凭证。
请确保您的AWS凭证文件中包含与profile_names
列表中定义的配置文件名称相匹配的配置文件。如果配置文件不存在,代码将捕获ProfileNotFound
异常并打印相应的错误消息。
对于每个配置文件,我们打印其关联的凭证的访问密钥和秘密密钥。您可以根据需要进一步处理这些凭证。