Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save erikdw/03302a29f768222cb11383313fee43cf to your computer and use it in GitHub Desktop.
Save erikdw/03302a29f768222cb11383313fee43cf to your computer and use it in GitHub Desktop.
Attempt to create a route on an ALB to be redirected to a Lambda WIP
# input vars
variable "environment" {
default = "Dev"
}
# local vars
locals {
name = "hello"
env = "${lower(var.environment)}"
lb_name = "${join("-", list("TF", var.environment, local.name))}"
zip_path = "${local.name}.zip"
tags = {
env = "${local.env}"
}
}
# data sources
data "aws_vpc" "default" {
tags {
env = "${local.env}"
}
}
data "aws_subnet_ids" "default" {
vpc_id = "${data.aws_vpc.default.id}"
tags {
env = "${local.env}"
}
}
data "aws_security_groups" "default" {
tags {
env = "${local.env}"
}
}
data "aws_iam_role" "base" {
name = "lambda-base-role"
}
# alb and lambda resources
resource "aws_lambda_function" "lambda" {
# Lambda zip File config
filename = "${local.zip_path}"
source_code_hash = "${base64sha256(file(local.zip_path))}"
# Function definition
function_name = "${local.name}"
role = "${data.aws_iam_role.base.arn}"
handler = "main.handle"
runtime = "python3.7"
memory_size = "128"
timeout = "30"
publish = false
# Network config
vpc_config {
subnet_ids = ["${data.aws_subnet_ids.default.ids}"]
security_group_ids = ["${data.aws_security_groups.default.ids}"]
}
tags {
env = "${local.env}"
}
}
resource "aws_lb" "default" {
name = "${local.lb_name}"
internal = false
load_balancer_type = "application"
security_groups = ["${data.aws_security_groups.default.ids}"]
subnets = ["${data.aws_subnet_ids.default.ids}"]
enable_deletion_protection = true
}
resource "aws_lb_target_group" "default" {
name = "${local.lb_name}-TG"
target_type = "lambda"
}
resource "aws_lb_listener" "default" {
load_balancer_arn = "${aws_lb.default.arn}"
port = "80"
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = "${aws_lb_target_group.default.arn}"
}
}
resource "aws_lb_listener_rule" "lambda" {
listener_arn = "${aws_lb_listener.default.arn}"
priority = 100
action {
type = "forward"
target_group_arn = "${aws_lb_target_group.default.arn}"
}
condition {
field = "path-pattern"
values = ["/lambda/${local.name}"]
}
}
resource "aws_lambda_permission" "with_lb" {
statement_id = "AllowExecutionFromLB"
action = "lambda:InvokeFunction"
function_name = "${local.name}"
principal = "elasticloadbalancing.amazonaws.com"
source_arn = "${aws_lb_target_group.default.arn}"
}
resource "aws_lb_target_group_attachment" "default" {
target_group_arn = "${aws_lb_target_group.default.arn}"
target_id = "${aws_lambda_function.lambda.arn}"
}
# return base url
output "base_url" {
value = "${aws_lb.default.public_dns}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment