8
1

More than 1 year has passed since last update.

TerraformでALBを構築してみる

Posted at

はじめに

Terraformの勉強を始めたので備忘録を兼ねて行ったことを投稿しようと思います。
以下の4つの投稿内容を実施した上でALBの構築を行なっています。
TerraformをインストールしてTerraformでAWS上にEC2作ってみる
TerraformでIAMを設定してEC2にセッションマネージャー経由で接続してみる
Terraformでセキュリティグループを設定してEC2にhttp接続する
TerraformでVPCを構築してみる

TerrafromにALBの定義を追加

ALB

alb.tf
resource "aws_lb" "test_alb" {
  name               = "test_alb"
  internal           = false
  load_balancer_type = "application"
  security_groups = [aws_security_group.test.id]

  subnets = [
    aws_subnet.demo_subnet_a.id,
    aws_subnet.demo_subnet_c.id
  ]

  ip_address_type = "ipv4"

  tags = {
    Name = "tf_test_alb"
  }
}

security_groupsには以下で作成したhttp接続を許可するセキュリティグループを設定
http接続用のセキュリティグループを定義

subnetsには以下で作成したサブネットを設定
サブネットを定義

ターゲットグループ

alb.tf
resource "aws_lb_target_group" "test_target_group" {
  name             = "test_target_group"
  target_type      = "instance"
  protocol_version = "HTTP1"
  port             = 80
  protocol         = "HTTP"

  vpc_id = aws_vpc.test_vpc.id

  tags = {
    Name = "tf_test_target_group"
  }

  health_check {
    interval            = 30
    path                = "/"
    port                = "traffic-port"
    protocol            = "HTTP"
    timeout             = 5
    healthy_threshold   = 5
    unhealthy_threshold = 2
    matcher             = "200,301"
  }
}

vpc_idには以下で作成したVPCを設定
VPCを定義

ターゲットグループのインスタンス設定

alb.tf
resource "aws_lb_target_group_attachment" "test_target_ec2" {
  target_group_arn = aws_lb_target_group.test_target_group.arn
  target_id        = aws_instance.test.id
}

target_idには以下でサブネットを指定したEC2インスタンスを設定
EC2を構築するサブネット指定する
※本来は複数のインスタンスを設定しますが、テストなので一つしか設定していません

リスナーの設定

alb.tf
resource "aws_lb_listener" "test_listener" {
  load_balancer_arn = aws_lb.test_alb.arn
  port              = "80"
  protocol          = "HTTP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.test_target_group.arn
  }
}

Terraformで定義したALBを反映

Terraformのplan applyを実行

terraformのplan applyを実行して、AWS上にリソースを反映します。

terraform plan
terraform apply

http接続を行う

AWSコンソールのALBのページを開き、作成したALBのDNS nameをコピーして
ブラウザからアクセスできるか確認します。

作成したリソースの削除

terraformのdestroyを実行して、AWS上のリソースを削除します。

terraform destroy

さいごに

今回でWEBアプリケーションの構築に必要なリソースを一通り作成できました。
次回はansibleを使って、ミドルウェアの部分をコード化できるようにしようと思います。

8
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
8
1