resource "aws_cloudwatch_event_rule" "ec2_terminate" { name = "ec2_terminate" description = "Remove record from R53 on EC2 scale down" event_pattern = <<PATTERN { "source": [ "aws.ec2" ], "detail-type": [ "EC2 Instance State-change Notification" ], "detail": { "state": [ "terminated" ] } } PATTERN } resource "aws_cloudwatch_event_target" "lambda" { rule = "${aws_cloudwatch_event_rule.ec2_terminate.name}" target_id = "SendToLambda" arn = "${aws_lambda_function.remove_ec2_from_route53.arn}" } resource "aws_iam_role" "iam_for_lambda" { name = "iam_lambda_remove_ec2_from_route53" assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Action": "sts:AssumeRole", "Principal": { "Service": "lambda.amazonaws.com" }, "Effect": "Allow", "Sid": "" } ] } EOF } resource "aws_iam_role_policy" "lambda_role_policy" { name = "lambda_remove_ec2_from_route53_policy" role = "${aws_iam_role.iam_for_lambda.id}" policy = <<EOF { "Statement": [ { "Effect": "Allow", "Action": [ "ec2:Describe*", "ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface", "ec2:DescribeNetworkInterfaces", "route53:ChangeResourceRecordSets", "route53:TestDNSAnswer" ], "Resource": "*" } ] } EOF } resource "aws_iam_policy" "lambda_logging" { name = "lambda_logging" path = "/" policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Action": [ "logs:CreateLogStream", "logs:PutLogEvents" ], "Resource": "arn:aws:logs:*:*:*", "Effect": "Allow" } ] } EOF } resource "aws_iam_role_policy_attachment" "lambda_logs" { role = "${aws_iam_role.iam_for_lambda.name}" policy_arn = "${aws_iam_policy.lambda_logging.arn}" } data "archive_file" "lambda_function" { type = "zip" source_file = "files/remove_ec2_from_route53.py" output_path = "files/remove_ec2_from_route53.zip" } resource "aws_security_group" "lambda" { name = "allow lambda to internet" description = "Allow outgoing traffic for Lambda" vpc_id = "${aws_vpc.sysops.id}" egress { from_port = 0 to_port = 0 protocol = "-1" cidr_blocks = ["0.0.0.0/0"] } } resource "aws_cloudwatch_log_group" "remove_r53" { name = "/aws/lambda/remove_ec2_from_route53" retention_in_days = 14 } resource "aws_lambda_function" "remove_ec2_from_route53" { filename = "files/remove_ec2_from_route53.zip" function_name = "remove_ec2_from_route53" role = "${aws_iam_role.iam_for_lambda.arn}" handler = "remove_ec2_from_route53.lambda_handler" source_code_hash = "${data.archive_file.lambda_function.output_base64sha256}" runtime = "python3.7" vpc_config { subnet_ids = ["${aws_subnet.sysops_private_subnets.*.id}"] security_group_ids = ["${aws_security_group.lambda.id}"] } depends_on = ["aws_iam_role_policy_attachment.lambda_logs", "aws_cloudwatch_log_group.remove_r53"] } resource "aws_lambda_permission" "allow_cloudwatch" { statement_id = "AllowExecutionFromCloudWatch" action = "lambda:InvokeFunction" function_name = "${aws_lambda_function.remove_ec2_from_route53.function_name}" principal = "events.amazonaws.com" }