When creating autostopping rules by hand in the harness UI, scale can be a real problem. With many aws accounts and many instances to manage we need to lean on infrastructure as code to create these rules and schedules automatically.
To do this we can leverage the AWS and Harness Terraform providers to query for instances to stop and create the rules/schedules accordingly.
First we can use the AWS provider and a data resource for EC2 instances to get instances that have a specific tag. In this case I am looking for instances which engineers have tagged with Schedule
equal to us-work-hours
.
data "aws_instances" "this" {
instance_tags = {
Schedule = "us-work-hours"
}
}
We can also get RDS instances this way.
data "aws_db_instances" "this" {
tags = {
Schedule = "us-work-hours"
}
}
Once we have our instances we can create autostopping rules for them using the Harness provider.
# ec2
resource "harness_autostopping_rule_vm" "this" {
for_each = toset(data.aws_instances.this.ids)
name = "${each.key} us-work-hours"
cloud_connector_id = "rileyharnessccm"
idle_time_mins = 5
filter {
vm_ids = [
each.key
]
regions = [
data.aws_instances.this.id # region of instances
]
}
}
# rds
resource "harness_autostopping_rule_rds" "this" {
for_each = toset(data.aws_db_instances.this.instance_identifiers)
name = "${each.key} us-work-hours"
cloud_connector_id = "rileyharnessccm"
idle_time_mins = 5
database {
id = each.key
region = data.aws_db_instances.this.id
}
}
Now that we have all the rules created, we can make a schedule and attach it to each rule.
resource "harness_autostopping_schedule" "this" {
name = "usworkhours"
schedule_type = "uptime"
time_zone = "EST"
repeats {
days = ["MON", "TUE", "WED", "THU", "FRI"]
start_time = "11:00"
end_time = "17:00"
}
rules = concat([
for rule in harness_autostopping_rule_vm.this : rule.id
], [
for rule in harness_autostopping_rule_rds.this : rule.id
])
}
With this we have autostopping rules and a schedule created for each instance that has our target tag and value. You can repeat this for every schedule type you want to support, across all accounts and regions.