Building DevSecOps solutions using AWS, Terraform and Kubernetes

AWS is not expensive - Part 1

  • 1st October 2020

In every AWS account I review, I always manage to save hundreds of dollars a month in costs in the first two hours.

The mistake everyone makes when they first start using AWS is to migrate over their classic server into a single EC2 instance, then scale vertically and wonder why they are paying thousands of pounds a year more than they need to.

Switch off the lights

When you're the last one out of the office you don't leave the lights on, so why do you leave your staging servers turned on?

AWS doesn't bill you for running a server while it's stopped, so make big savings quickly by setting up a crontask in CloudWatch to turn off your instance at 6pm each night.

Step 1) Create Python Lambda

Create the lambda as normal, and copy the code. Then find your staging instance ids from EC2 and add replace the instance ids with them.



import json
import boto3

region = 'eu-west-1'
instances = ['i-12ab3456cdef78a9b']

ec2 = boto3.client('ec2', region_name=region)

def lambda_handler(event, context):
    ec2.stop_instances(InstanceIds=instances)
    print('Stopped your instances: ' + str(instances))

    return {
        'statusCode': 200,
        'body': json.dumps('Stopped instance!')
    }

Step 2) Create CloudWatch Rule



And that's it, you can repeat and tweak these steps with minimal effort to turn the instances back on every morning and cut your staging EC2 instance costs in half.

Rhuaridh

Please get in touch through my socials if you would like to ask any questions - I am always happy to speak tech!