TECHIES WORLD

For Techs.... Techniques.... Technologies....

AWSLinux

How to configure boto3 to wait till EC2 instance be running or stopped state

We can automate EC2 start and stop processes using the Python scripts using boto3 module. Usually it will take some time to complete the start or stop process once triggered.

Boto3 provides an option to pause the further steps until EC2 instance be running or stopped state.

Sample script to pause actions till EC2 instance be running state.

import boto3, argparse
from botocore.exceptions import ClientError


client = boto3.client(
        'ec2',
        region_name='',
        aws_access_key_id='',
        aws_secret_access_key=''
)

INSTANCE_ID=''

response = client.start_instances(InstanceIds=[INSTANCE_ID])
instance_runner_waiter = client.get_waiter('instance_running')
instance_runner_waiter.wait(InstanceIds=[INSTANCE_ID])
print("Instance {} started".format(INSTANCE_ID))

Where region_name, aws_access_key_id, aws_secret_access_key and INSTANCE_ID need to be updated with appropriate values.

Sample script to pause actions till EC2 instance be stopped state.

import boto3, argparse
from botocore.exceptions import ClientError


client = boto3.client(
        'ec2',
        region_name='',
        aws_access_key_id='',
        aws_secret_access_key=''
)

INSTANCE_ID=''

response = client.stop_instances(InstanceIds=[INSTANCE_ID])
instance_stopped_waiter = client.get_waiter('instance_stopped')
instance_stopped_waiter.wait(InstanceIds=[INSTANCE_ID])
print("Instance {} stopped".format(INSTANCE_ID))

Where region_name, aws_access_key_id, aws_secret_access_key and INSTANCE_ID need to be updated with appropriate values.

That's all…