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}')


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

Welcome to GeekTechStuff

my home away from home and where I will be sharing my adventures in the world of technology and all things geek.

The technology subjects have varied over the years from Python code to handle ciphers and Pig Latin, to IoT sensors in Azure and Python handling Bluetooth, to Ansible and Terraform and material around DevOps.

Let’s connect