According to my cloudwatch logs, my lambda functions never fire on the initial launch of my autoscaling group. The only time I have ever seen the eventbridge send an event to my lambda function is when i increased the desired capacity from 0 to 1. Whenever my desired capacity starts at 1 I get absolutely nothing. My goal ultimately is to assign an elastic ip address to all my autoscaled instances. I’m trying to use a lambda function to accomplish this, however its proving to not be simple.
Has anyone ever had a similar problem to this?
resource "aws_autoscaling_group" "ssh_proxy_group" {
launch_template {
id = xxx
version = "$Latest"
}
desired_capacity = 0
min_size = 0
max_size = 20
}
resource "aws_autoscaling_policy" "scale_out_policy" {
name = "ScaleOutPolicy"
scaling_adjustment = 1 # Number of instances to add
adjustment_type = "ChangeInCapacity"
cooldown = 300 # Time between scaling activities (5 minutes)
autoscaling_group_name = aws_autoscaling_group.ssh_proxy_group.name
}
resource "aws_cloudwatch_event_rule" "instance_launch_rule" {
name = "instance-launch-rule"
description = "Triggers when an EC2 instance is successfully launched by the Auto Scaling group."
event_pattern = jsonencode({
source = ["aws.autoscaling"],
"detail-type" = ["EC2 Instance Launch Successful"],
detail = {
AutoScalingGroupName = [aws_autoscaling_group.ssh_proxy_group.name]
}
})
}
resource "aws_lambda_permission" "allow_eventbridge" {
statement_id = "AllowExecutionFromEventBridge"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.allocate_ip_to_ec2.function_name
principal = "events.amazonaws.com"
source_arn = aws_cloudwatch_event_rule.instance_launch_rule.arn
}
resource "aws_cloudwatch_event_target" "trigger_lambda" {
rule = aws_cloudwatch_event_rule.instance_launch_rule.name
arn = aws_lambda_function.allocate_ip_to_ec2.arn
depends_on = [aws_lambda_permission.allow_eventbridge]
}