【问题标题】:I need to get Public IPv4 address on response of newly created instance by this Lambda Function?我需要通过此 Lambda 函数获取新创建实例的响应的公共 IPv4 地址吗?
【发布时间】:2022-01-02 18:52:41
【问题描述】:

我正在使用 boto3 创建一个实例,我想在 response 上打印公共 ip 地址。请协助完成此代码,但代码保留显示错误有人可以帮助更正此代码以显示打印公共 ipv4 地址

import boto3
import json
 
AMI = 'AMI'
INSTANCE_TYPE = 'INSTANCE_TYPE'
KEY_NAME = 'KEY_NAME'
REGION = 'REGION'
SUBNET_ID = 'SUBNET_ID'
SECURITYGROUP_ID = 'SECURITYGROUP_ID'
 

def lambda_handler(event, context):

    ec2 = boto3.client('ec2', region_name=event['REGION'])

        
    instance = 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 ("New instance created:")
    instance_id = instance['Instances'][0]['InstanceId']
    print (instance_id)
    
    for instance in instance:
    IP = instance.public_ip_address
    print(IP)
        
    return instance_id**

错误信息显示如下

errorMessage": "'str' object has no attribute 'public_ip_address'",

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 aws-lambda


    【解决方案1】:

    run_instances() 之后将不提供公共 IP 地址,因为分配给实例需要一段时间。

    您应该反复调用describe_instances(),直到提供公共 IP 地址。我建议在每次通话之间等待几秒钟。

    调用后:

    response = describe_instances(InstanceIds=[instance_id])
    

    您可以检查是否提供了值:

    instance = response['Reservations'][0]['Instances'][0]
    
    if 'PublicIpAddress' in instance:
        public_ip = instance['PublicIpAddress']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-26
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 2018-08-24
      • 2016-12-05
      • 1970-01-01
      相关资源
      最近更新 更多