2

I want to start an ec2 instances depends on the state of other ec2 instances through lambda functions.For example, Webserver ec2 instances has to start once Database instances will start.As of now i am using the sleep method of time component but thinking that there should be a way to do my requirement and it's not good for product having a 1-2 minutes of downtime to start just ec2 instances.

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))  

Suggestions are welcome and thanks.

1 Answer 1

1
  1. Check the instance states

    db_1 = ec2.Instance(id1).state
    db_2 = ec2.Instance(id2).state
    
  2. Set some flag which becomes True only if both instances are running

    check_flag = True
    if db_1 == 'running' and db_2 == 'running':
        check_flag = False
    
  3. Combine both , and add the web startup snippet

    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)
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.