Skip to content

Instantly share code, notes, and snippets.

@nitrocode
Last active December 21, 2020 20:23
Show Gist options
  • Save nitrocode/27570e9288892e086a062285316c6370 to your computer and use it in GitHub Desktop.
Save nitrocode/27570e9288892e086a062285316c6370 to your computer and use it in GitHub Desktop.
Attempt to create a route on an ALB to be redirected to a Lambda WIP
# local vars
locals {
name = "hello"
env = "dev"
lb_name = join("-", list("TF", local.env, 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 = local.tags
}
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 {
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
}
@gitgoose
Copy link

has this worked for you?

@nitrocode
Copy link
Author

@gitgoose yes!

@shvartz311
Copy link

How did you figure it out eventually?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment