0
1

More than 3 years have passed since last update.

NLBとAuto Scallingを連携させる

Posted at

NLBのターゲットにAuto Scallingグループを指定できます。

AWS公式のドキュメントとしてはAuto Scaling グループにロードバランサーのアタッチにやり方が書いてあります。

今回はこれをTerraformでやる方法を残しておきます。

ざっくりとは普通にNLB、リスナー、ターゲットグループを作成し、Auto Scallingグループをターゲットグループにアタッチしています。

nlb.tf

nlb.tf
resource "aws_lb" "nlb" {
  name               = "${var.base_name}-nlb"
  internal           = false
  load_balancer_type = "network"
  subnets            = var.public_subnet_ids

  tags = {
    "Name" = "${var.base_name}-nlb",
  }
}

nlb-listener.tf

nlb-listener.tf
resource "aws_lb_listener" "listener" {
  load_balancer_arn = aws_lb.nlb.arn
  port              = var.listener_port
  protocol          = "TCP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.target-group.arn
  }

  tags = {
    "Name" = "${var.base_name}-listener"
  }
}

nlb-target-group.tf

nlb-target-group.tf
resource "aws_lb_target_group" "target-group" {
  name     = "${var.base_name}-target-group"
  port     = var.target_port
  protocol = "TCP"
  vpc_id   = var.vpc_id

  tags = {
    "Name" = "${var.base_name}-target-group"
  }
}

nlb-autoscaling-attachment.tf

今回のキモです。パラメータ名はalb_target_group_arnですがNLBTのターゲットグループでもちゃんと紐付けてくれます。また、今回はEKSのマネージドノードグループをターゲットとしたかったため、マネージドノードグループからAuto Scallingグループ名を引っ張ってくる書き方をしています。

nlb-autoscaling-attachment.tf
resource "aws_autoscaling_attachment" "attachment" {
  autoscaling_group_name = aws_eks_node_group.worker.resources.0.autoscaling_groups.0.name
  alb_target_group_arn   = aws_lb_target_group.target-group.arn
}

variables.tf

variables.tf
variable "base_name" {
  description = "作成するリソースに付与する接頭語"
  type        = string
}

variable "vpc_id" {
  description = "リソース群をデプロイするVPCのID"
  type        = string
}

variable "public_subnet_ids" {
  description = "パブリックサブネットのID"
  type        = list(string)
}

variable "listener_port" {
  type = number
}

variable "target_port" {
  type = number
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1