AWS-打印启动lambda的实例的详细信息

时间:2020-09-15 05:00:45

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

我是AWS的新手,一直在创建一些自动化脚本。

此脚本正在启动EC2实例。我想做的就是还返回并打印代码本身正在启动的实例的“实例ID”和“公共IP”。

import boto3

ec2 = boto3.resource('ec2')

def lambda_handler(event, context):
    # create a new EC2 instance
    instances = ec2.create_instances(
     ImageId='ami-*******',
     MinCount=1,
     MaxCount=1,
     InstanceType='t2.micro',
     KeyName='*****'
     )

    return

1 个答案:

答案 0 :(得分:2)

此处的棘手问题是,执行create_instances后,公共IP可能不立即可用。因此,要克服此计时问题,您可以实现基本的while循环以等待IP。

import json
from time import sleep

import boto3

ec2 = boto3.resource('ec2')
ec2r = boto3.resource('ec2')

def lambda_handler(event, context):
    
    instances = ec2.create_instances(
         ImageId='ami-0c94855ba95c71c99',
         MinCount=1,
         MaxCount=1,
         InstanceType='t2.micro',
         KeyName='xxxxxxx'
    )
    
    instance = instances[0]
    
    while instance.public_ip_address is None:
        print('Wait 2 seconds and check again for public ip')
        sleep(2)
        instance = ec2r.Instance(instance.instance_id)

    print('Public IP available')
    
    return [instance.instance_id, instance.public_ip_address]

相关问题