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

如何用Python替换AWS临时凭证至指定配置文件?报错及优化问询

问题分析与优化实现

报错原因

你遇到的AttributeError: 'tuple' object has no attribute 'find',是因为修改列表元素时错误地用逗号拼接字符串和换行符,导致列表中的元素变成了元组:

# 错误写法:生成了元组
aws_credential_file[new_aws_access_key_line_num] = "aws_access_key_id = " + temp_credentials["AccessKeyId"], "\n"
# 正确写法:合并成单个字符串
aws_credential_file[new_aws_access_key_line_num] = "aws_access_key_id = " + temp_credentials["AccessKeyId"] + "\n"

除此之外,你的代码还有其他逻辑问题:比如每次循环没找到[temp-token]就执行写入操作,会重复添加多次;只读取了文件内容,最后没有把修改后的内容写回文件;手动解析配置文件容易忽略空行、注释等情况,稳定性差。

更优实现方式

直接用Python标准库的configparser处理AWS凭证文件,它专门适配INI格式的配置,能自动处理section的新增/覆盖,无需手动解析行内容:

import os
import boto3
from configparser import ConfigParser

mfa_serial_number = "arn:aws:iam::xxxxxxxxxxxx:mfa/your-iam-user-here"
mfa_otp = input("Enter your otp: ")

def update_temp_credentials(mfa_serial, mfa_code):
    # 获取临时凭证
    session = boto3.Session(profile_name='default', region_name='us-east-1')
    sts_client = session.client('sts')
    
    if mfa_serial:
        response = sts_client.get_session_token(
            SerialNumber=mfa_serial,
            TokenCode=mfa_code
        )
    else:
        response = sts_client.get_session_token()
    
    temp_creds = response['Credentials']
    
    # 处理AWS凭证文件
    creds_path = os.path.expanduser("~/.aws/credentials")
    config = ConfigParser()
    # 读取现有配置(如果文件不存在会自动创建)
    config.read(creds_path)
    
    # 配置或覆盖temp-token section
    config['temp-token'] = {
        'aws_access_key_id': temp_creds['AccessKeyId'],
        'aws_secret_access_key': temp_creds['SecretAccessKey'],
        'aws_session_token': temp_creds['SessionToken']
    }
    
    # 写回凭证文件
    with open(creds_path, 'w') as f:
        config.write(f)
    
    print("临时凭证已成功更新到[temp-token]配置文件")

update_temp_credentials(mfa_serial_number, mfa_otp)

优化点说明

  • 用configparser自动处理INI格式,避免手动解析行的繁琐和错误
  • 用os.path.expanduser适配不同系统的用户家目录,无需硬编码路径
  • 不管[temp-token]是否存在,直接赋值即可覆盖/新增,逻辑更简洁
  • 完整保留原有配置文件中的其他section,不会破坏已有配置

内容的提问来源于stack exchange,提问作者koda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:45:31