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

Lambda使用boto3创建EC2实例如何获取返回结果中的公网IPv4地址

错误原因
  • 你直接遍历了run_instances返回的整个响应字典,循环变量拿到的是字典的字符串键,所以触发了'str'对象没有对应属性的报错
  • boto3的client接口返回的所有实例数据都是字典结构,只有resource接口返回的实例对象才能用.public_ip_address属性取值,你用的调用方式不对
  • EC2实例刚创建完成时公网IP还未分配,直接从创建响应中取值大概率会拿到空值,需要等实例进入运行状态后再查询取值
修正后代码
import boto3
import json
 
def lambda_handler(event, context):
    ec2 = boto3.client('ec2', region_name=event['REGION'])
    # 创建EC2实例
    run_response = ec2.run_instances(
        ImageId=event['AMI'],
        InstanceType=event['INSTANCE_TYPE'],
        KeyName=event['KEY_NAME'],
        SubnetId=event['SUBNET_ID'],
        SecurityGroupIds = ['my-sg'],
        MaxCount=1,
        MinCount=1,
        InstanceInitiatedShutdownBehavior="terminate",
        TagSpecifications=[
        {
            'ResourceType': 'instance',
            'Tags': [
                {
                    'Key': 'Name',
                    'Value': 'my-instance'
                },
            ]
        },
    ],
    )
    print ("新实例创建成功,实例ID:")
    instance_id = run_response['Instances'][0]['InstanceId']
    print(instance_id)
    
    # 等待实例进入运行状态,确保公网IP分配完成
    waiter = ec2.get_waiter('instance_running')
    waiter.wait(InstanceIds=[instance_id])
    
    # 查询实例最新详情
    desc_response = ec2.describe_instances(InstanceIds=[instance_id])
    instance_info = desc_response['Reservations'][0]['Instances'][0]
    # 从字典中取公网IP
    public_ip = instance_info.get('PublicIpAddress')
    print(f"实例公网IPv4地址:{public_ip}")
        
    return instance_id
修改点说明
  • 重命名了响应变量,避免变量名冲突,原代码里创建实例的响应和循环变量都叫instance,逻辑混乱
  • 新增实例运行状态等待逻辑,确保公网IP分配完成后再查询
  • 调用describe_instances接口拉取实例最新属性,直接从返回的字典中按key取值,符合client接口的使用规范
  • 用get方法取值避免IP未分配时报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:15:03