Powering Off AWS EC2 Instances via Tags (Python)

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']},

# try to stop instances
for instance in instances:
        print(f'{instance} stopped')
        print(f'Error stopping {instance}')

Python 3 code to stop AWS EC2 instances that are tagged with appropriate tag