DEV Community

Yash
Yash

Posted on

Terraform modules to write once and reuse forever

Terraform modules to write once and reuse forever

Module 1: Standard ALB

resource "aws_lb" "main" {
  name = var.name; load_balancer_type = "application"
  security_groups = [aws_security_group.alb.id]; subnets = var.public_subnet_ids
  drop_invalid_header_fields = true; enable_deletion_protection = true
}
resource "aws_lb_listener" "https" {
  load_balancer_arn = aws_lb.main.arn; port = 443; protocol = "HTTPS"
  ssl_policy = "ELBSecurityPolicy-TLS13-1-2-2021-06"; certificate_arn = var.certificate_arn
  default_action { type = "fixed-response"
    fixed_response { content_type = "text/plain"; status_code = "404" } }
}
resource "aws_lb_listener" "redirect" {
  load_balancer_arn = aws_lb.main.arn; port = 80; protocol = "HTTP"
  default_action { type = "redirect"
    redirect { port = "443"; protocol = "HTTPS"; status_code = "HTTP_301" } }
}
output "arn_suffix"     { value = aws_lb.main.arn_suffix }
output "https_listener" { value = aws_lb_listener.https.arn }
Enter fullscreen mode Exit fullscreen mode

Module 2: ECS IAM roles

resource "aws_iam_role" "execution" {
  name = "${var.service}-${var.env}-execution"
  assume_role_policy = jsonencode({ Version = "2012-10-17"
    Statement = [{ Effect = "Allow"
      Principal = { Service = "ecs-tasks.amazonaws.com" }; Action = "sts:AssumeRole" }]})
}
resource "aws_iam_role_policy_attachment" "execution" {
  role       = aws_iam_role.execution.name
  policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
resource "aws_iam_role" "task" {
  name = "${var.service}-${var.env}-task"
  assume_role_policy = jsonencode({ Version = "2012-10-17"
    Statement = [{ Effect = "Allow"
      Principal = { Service = "ecs-tasks.amazonaws.com" }; Action = "sts:AssumeRole" }]})
}
output "execution_role_arn" { value = aws_iam_role.execution.arn }
output "task_role_arn"      { value = aws_iam_role.task.arn }
Enter fullscreen mode Exit fullscreen mode

Composing a full project (6 module calls)

module "vpc"       { source = "../../../modules/vpc"; ... }
module "alb"       { source = "../../../modules/alb"; ... }
module "api_iam"   { source = "../../../modules/ecs-iam"; ... }
module "api"       { source = "../../../modules/ecs-service"; ... }
module "monitoring"{ source = "../../../modules/service-monitoring"; ... }
module "alerting"  { source = "../../../modules/alerting"; ... }
Enter fullscreen mode Exit fullscreen mode

VPC + ALB + IAM + ECS service + monitoring in ~30 lines.

Step2Dev generates and manages this library for every project.

👉 step2dev.com

Top comments (0)