How to check if an ec2 instance is running or not with an if statement?

Question:

I have an instance-id of an ec2 instance. How to check if that ec2 instance is running or not using an if statement? I am using Python and Boto3.

Asked By: jbot

||

Answers:

Using the boto3 Resource method:

import boto3

ec2_resource = boto3.resource('ec2', region_name='ap-southeast-2')

instance = ec2_resource.Instance('i-12345')
if instance.state['Name'] == 'running':
    print('It is running')

Using the boto3 Client method:

import boto3

ec2_client = boto3.client('ec2', region_name='ap-southeast-2')

response = ec2_client.describe_instance_status(InstanceIds=['i-12345'])
if response['InstanceStatuses'][0]['InstanceState']['Name'] == 'running':
    print('It is running')
Answered By: John Rotenstein

I think that important thing is that by default, only running instances are described. So if you want to check the state of instance that not necessary is running, than you need to specify "IncludeAllInstances" option. So it should looks like this:

response = ec2_client.describe_instance_status(InstanceIds=['i-12345'], IncludeAllInstances=True)
if response['InstanceStatuses'][0]['InstanceState']['Name'] == 'running':
    print('It is running')
Answered By: AGR
response = ec2_client.describe_instances(InstanceIds=[instance_id])
if "".join([ "Running" if x['State']['Name'] == "running" else "Stopped" for r in response['Reservations'] for x in r['Instances']]) == "Running":
    print("Instances is running")
else:
    print("Instances is not running")
Answered By: Sudhar balaji