Skip to content

start, stop, reboot or terminate AWS EC2 instances on scheduled times

Notifications You must be signed in to change notification settings

wakumaku/terraform-aws-ec2-instanceswitcher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

AWS EC2 Instance Switcher

start, stop, reboot or terminate AWS EC2 instances on scheduled times

Example use case:

  • We want to start a development environment at 8 and stop it at 18 every workday.
  • We want to start a development environment at 10 and stop it at 16 on saturdays.
  • We want to start a development environment at 10 and stop it at 14 on sundays.
data "aws_instances" "dev" {
  filter {
    name = "tag:Name"
    values = [
      "dev_1",
      "dev_db",
      "devel_platform",
    ]
  }
}

module "instanceswitcher" {
  source  = "wakumaku/ec2-instanceswitcher/aws"
  version = "x.y.z"

  # Prefix to be used in created resources
  prefix = "devel_stack"

  # Which instances will be affected
  instance_list = data.aws_instances.dev.ids

  # Schedules in cron expression format
  # https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html#CronExpressions
  schedules = {
    start = [
      "0 8 ? * MON-FRI *",
      "0 10 ? * SAT,SUN *",
    ]
    stop = [
      "0 18 ? * MON-FRI *",
      "0 16 ? * SAT *",
      "0 14 ? * SUN *",
    ]
    terminate = []
    reboot    = []
    switch    = []
  }

  tags = {
    Name      = "Dev Maintenance"
    project   = "operations"
    component = "devmaintainer"
  }
}
Plan: 23 to add, 0 to change, 0 to destroy.

This code will create 5 EventBridge Rules, one for each scheduled time, that will execute a lambda to perform the action.

EventBridge Rules:

eventbridge rule list

Lambda created to perform the actions with the linked triggers:

function overview

function triggers