How to schedule (start and stop) EC2 instances easily

Everyone would like to schedule EC2 instances and save a couple of bucks. Today, I’m bringing you a small Python that can help you. The steps are the following ones:

1) Create a lambda function called: ec2_scheduler
2) Copy and paste the following cod…


This content originally appeared on DEV Community and was authored by Federico Navarrete

Everyone would like to schedule EC2 instances and save a couple of bucks. Today, I'm bringing you a small Python that can help you. The steps are the following ones:

1) Create a lambda function called: ec2_scheduler
2) Copy and paste the following code:

import boto3
import os
import json

region = os.environ['REGION']
ec2 = boto3.client('ec2', region_name=region)

instances = []

def lambda_handler(event, context):
    action = event['Action']
    response = ec2.describe_instances(Filters=[{'Name' : 'instance-state-name','Values' : [action]}, {'Name': 'tag-key', 'Values': ['auto-scheduled']}])
    reservations = response['Reservations']
    for reservation in reservations:
        for instance in reservation['Instances']:
            instanceId = instance['InstanceId']
            for tag in instance['Tags']:
                if tag['Key'] == 'auto-scheduled' and tag['Value'] == 'true':
                    instances.append(instanceId)

    if (action == 'stopped'):
        if (len(instances) > 0):
            ec2.start_instances(InstanceIds=instances)
    else
        if (len(instances) > 0):
            ec2.stop_instances(InstanceIds=instances)

3) Set a tag to your EC2 instance called: auto-scheduled that has a value assigned as true.

4) Add a new Policy in the configuration and permission section of your Lambda that contains:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:Start*",
                "ec2:Stop*",
                "ec2:Describe*"
            ],
            "Resource": "*"
        }
    ]
}

5) Schedule your Lambda as triggers with a cron expressions like these ones:

  • For starting: cron(0 6 ? * MON-FRI *)
  • For stopping: cron(0 16 ? * MON-FRI *)

6) Set a JSON that contains the following expression to know if it's starting or stopping:

  • For starting:
{
    "Action": "stopped"
}
  • For stopping:
{
    "Action": "running"
}

And that's all!

sponsor me

Cover credits:

https://tridentsys.net/howto-schedule-ec2/


This content originally appeared on DEV Community and was authored by Federico Navarrete


Print Share Comment Cite Upload Translate Updates
APA

Federico Navarrete | Sciencx (2022-01-24T13:24:05+00:00) How to schedule (start and stop) EC2 instances easily. Retrieved from https://www.scien.cx/2022/01/24/how-to-schedule-start-and-stop-ec2-instances-easily/

MLA
" » How to schedule (start and stop) EC2 instances easily." Federico Navarrete | Sciencx - Monday January 24, 2022, https://www.scien.cx/2022/01/24/how-to-schedule-start-and-stop-ec2-instances-easily/
HARVARD
Federico Navarrete | Sciencx Monday January 24, 2022 » How to schedule (start and stop) EC2 instances easily., viewed ,<https://www.scien.cx/2022/01/24/how-to-schedule-start-and-stop-ec2-instances-easily/>
VANCOUVER
Federico Navarrete | Sciencx - » How to schedule (start and stop) EC2 instances easily. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/01/24/how-to-schedule-start-and-stop-ec2-instances-easily/
CHICAGO
" » How to schedule (start and stop) EC2 instances easily." Federico Navarrete | Sciencx - Accessed . https://www.scien.cx/2022/01/24/how-to-schedule-start-and-stop-ec2-instances-easily/
IEEE
" » How to schedule (start and stop) EC2 instances easily." Federico Navarrete | Sciencx [Online]. Available: https://www.scien.cx/2022/01/24/how-to-schedule-start-and-stop-ec2-instances-easily/. [Accessed: ]
rf:citation
» How to schedule (start and stop) EC2 instances easily | Federico Navarrete | Sciencx | https://www.scien.cx/2022/01/24/how-to-schedule-start-and-stop-ec2-instances-easily/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.