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

使用Python Boto3获取EC2实例名称遇InvalidInstanceID.Malformed错误求助

问题分析与解决建议

核心错误原因

  • 传错参数:你在循环里写的get_instance_name ('line')是把字符串'line'传给函数,而不是当前读取到的实例ID变量line,这直接导致EC2收到无效的ID。
  • 行内容未清理:从文件读的每行默认带换行符\n,如果文件里的ID带单引号,这些多余字符会被当成ID的一部分,触发格式错误。

修正后的代码

import boto3
AWS_REGION = "us-west-2"
AWS_PROFILE = "profilex"
session=boto3.session.Session(profile_name=AWS_PROFILE)
ec2 = session.resource('ec2', region_name=AWS_REGION)

def get_instance_name(fid):
    i = ec2.Instance(fid)
    instancename = ''
    for tags in i.tags:
        if tags["Key"] == 'Name':
            instancename = tags["Value"]
    return instancename

with open('ids.txt') as f:
    for line in f:
        # 清理掉换行符、前后空白和多余的单引号
        instance_id = line.strip().strip("'")
        # 跳过空行
        if not instance_id:
            continue
        try:
            name = get_instance_name(instance_id)
            print(f"实例 {instance_id} 的名称: {name}")
        except Exception as e:
            print(f"处理实例 {instance_id} 失败: {str(e)}")

额外优化提示

  • 加异常处理:避免单个无效ID导致整个程序崩溃。
  • 过滤空行:跳过文件里的空行,减少无效调用。
  • 提前校验ID:可以加个判断,比如if instance_id.startswith('i-'),过滤明显不符合格式的内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 12:48:29