Currently, I have several AWS EC2 instances that are set up to run some heavy processing workloads on startup (there are several mechanisms to start them at the appropriate times). However, when any of them are re-created or modified, the resulting instance is immediately started up, which means that they have to be stopped manually to avoid having them run these workloads.
The instances are created as aws_instance
resources within a module:
resource "aws_instance" "processing_instance" {
ami = var.ami_id
instance_type = var.instance_type
key_name = var.ec2_key_pair
subnet_id = var.aws_subnet_id
user_data = "some heavy processing tasks"
vpc_security_group_ids = [var.aws_security_group_id]
iam_instance_profile = aws_iam_instance_profile.instance_profile.name
associate_public_ip_address = true
root_block_device {
volume_size = var.volume_size
}
lifecycle {
ignore_changes = [associate_public_ip_address]
}
}
The instances then run the compute tasks and write the result to a bucket, which then triggers an EventBridge event that turns off the current instance and runs the next one:
resource "aws_cloudwatch_event_rule" "transition-rule" {
for_each = local.steps # map with fields containing what key prefix to trigger on
name = "${each.key}-event-rule"
description = "Trigger next step in data flow"
event_pattern = jsonencode({
"source" : ["aws.s3"],
"detail-type" : ["Object Created"],
"detail" : {
"bucket": {
"name": [aws_s3_bucket.bucket.bucket]
},
"object": {
"key": [{
"prefix": "${each.value.prefix}/"
}]
}
}
})
}
The whole process is kicked off by a Scheduler event.
I would prefer to have Terraform create these instances without starting them, to avoid the hassle of stopping them and removing the possibility of having them run at the wrong time. What would be the best way to do this?