AWS EC2 instances can be powered off (or on) via a few lines of Python and the Boto3 library. Below is an example I’m currently playing about with. The instances segment filters on all EC2 instances that are running and contain a tag of “office_hours”, great to run at the end of the day to power off any EC2’s that are not required outside of office hours.
If using Terraform to create the instances then they could be tagged at creation, and if you like AWS Lambda then the code could be scheduled to run as a Lambda function.
import boto3
# region EC2 instances are in
region = 'eu-west-2'
ec2 = boto3.resource('ec2', region_name=region)
# find all instances that are running and have tag of office_hours
instances = ec2.instances.filter(
Filters = [{'Name': 'instance-state-name', 'Values': ['running']},
{'Name':'tag:office_hours','Values':['true']}]
)
# try to stop instances
for instance in instances:
try:
instance.stop()
print(f'{instance} stopped')
except:
print(f'Error stopping {instance}')

You must be logged in to post a comment.