实例启动后,aws-python中的任何事件监听器

时间:2019-11-12 06:33:42

标签: python amazon-ec2 aws-lambda

我想通过lambda函数启动ec2实例取决于其他ec2实例的状态。例如,一旦数据库实例启动,Webserver ec2实例必须启动。到目前为止,我正在使用时间组件的sleep方法,但是认为应该有一种方法可以满足我的要求,这对于只有1-2分钟的停机时间才能启动ec2实例的产品不利。

import boto3
import time
region = 'us-west-1'
db_instances = ['i-12345cb6de4f78g9h', 'i-08ce9b2d7eccf6d26']
web_instances = ['i-12345cb6de4f78h8g', 'i-08ce9b2d7eccf6548']
ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.start_instances(InstanceIds=db_instances)
    print('started your instances: ' + str(db_instances))
    time.sleep(60)
    ec2.start_instances(InstanceIds=web_instances)
    print('started your instances: ' + str(web_instances))  

建议和感谢。

1 个答案:

答案 0 :(得分:0)

  1. 检查实例states

    db_1 = ec2.Instance(id1).state
    db_2 = ec2.Instance(id2).state
    
  2. 设置一些仅在两个实例都在运行时才变为True的标志

    check_flag = True
    if db_1 == 'running' and db_2 == 'running':
        check_flag = False
    
  3. 同时合并两者,并添加网络启动摘要

    check_flag = True
    while check_flag:
        db_1 = ec2.Instance(id1).state
        db_2 = ec2.Instance(id2).state
        if db_1 == 'running' and db_2 == 'running':
            check_flag = False
    ec2.start_instances(InstanceIds=web_instances)