Wednesday 16 October 2019

Python Code to Stop AWS EC2 Instances Using Filters


import sys
import boto3
from botocore.exceptions import ClientError

region = 'xx-east-x'

InstanceList = []

try:
        ec2 = boto3.client('ec2', region_name=region)
except Exception as e:
        print(e)
        sys.exit(1)

response = ec2.describe_instances(
        Filters=[{
'Name': '<tagname>',
'Values': ['<value>']
},
                {
                        'Name' : 'instance-state-name',
                        'Values' : ['stopped']
                }]
)
#print (response)
for reservation in response['Reservations']:
for instance in reservation['Instances']:
InstanceList.append(instance['InstanceId'])

#print InstanceList
for instanceid in InstanceList:
startec2 = ec2.start_instances(InstanceIds=[instanceid])

No comments:

Post a Comment