Terraform

Terraform 실습 해보기 - 2

황동리 2023. 12. 22. 18:23
반응형

오늘은 1일차에 이어 진행해보도록 하겠습니다.

12. wordpress rds 연결 스크립트 작성

우선 user_data에 사용할 wordpress와 rds 연결하는 스크립트를 먼저 만들어 줍니다.

=> install.sh

#! /bin/bash

wget https://ko.wordpress.org/wordpress-5.7.8-ko_KR.tar.gz
tar -xvf wordpress-5.7.8-ko_KR.tar.gz
yum install -y httpd
cp -r wordpress/* /var/www/html/
amazon-linux-extras enable php8.0
yum install -y php php-fpm php-pdo php-mysqlnd
cp /var/www/html/wp-config-sample.php /var/www/html/wp-config.php
sed -i 's/DirectoryIndex index.html/DirectoryIndex index.php/g' /etc/httpd/conf/httpd.conf
sed -i 's/database_name_here/wordpress/g' /var/www/html/wp-config.php
sed -i 's/username_here/root/g' /var/www/html/wp-config.php
sed -i 's/password_here/It12345!/g' /var/www/html/wp-config.php
sed -i 's/localhost/{rds의 엔드포인트}/g' /var/www/html/wp-config.php
systemctl enable --now httpd

그리고 user_data에 위 스크립트를 넣어준다.

=> ec2.tf

resource "aws_instance" "ksh-ec2_weba" {
  ami                    = "ami-084e92d3e117f7692"
  instance_type          = "t2.small"
  key_name               = "ksh1"
  vpc_security_group_ids = [aws_security_group.ksh_sg.id]
  availability_zone      = "ap-northeast-2a"
  private_ip             = "100.0.1.11"
  subnet_id              = aws_subnet.ksh_weba.id
  user_data              = file("./install.sh")

  tags = {
    Name = "ksh-ec2-weba"
  }
}

output "ec2-weba-ip" {
  value = aws_instance.ksh-ec2_weba.id
}

13. 로드밸런서 생성

resource "aws_lb" "ksh_alb" {
  name               = "ksh-alb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.ksh_sg.id]
  subnets            = [aws_subnet.ksh_weba.id, aws_subnet.ksh_webc.id] # public 서브넷
  tags = {
    Name = "ksh-alb"
  }
}

output "alb_dns_name" {
  value = aws_lb.ksh_alb.dns_name
}

14. 로드밸런서 target 그룹 생성

로드밸런서 리스너 보다 target 그룹을 먼저 생성해야되는데, 이유는 리스너가 target 그룹에 프로토콜:포트를 전달 해야하기 때문이다.

resource "aws_lb_target_group" "ksh_albtg" {
  name     = "ksh-albtg"
  port     = 80
  protocol = "HTTP"
  vpc_id   = aws_vpc.ksh_vpc.id

  health_check {
    enabled             = true
    healthy_threshold   = 3
    interval            = 5
    matcher             = "200"
    path                = "/health.html"
    port                = "traffic-port"
    protocol            = "HTTP"
    timeout             = 2
    unhealthy_threshold = 3
  }

  tags = {
    Name = "ksh-albtg"
  }
}

그리고 헬스체크를 위한 health.html 페이지를 만들어 준다. 그 명령어는 install.sh에 같이 넣어준다.

#! /bin/bash

wget https://ko.wordpress.org/wordpress-5.7.8-ko_KR.tar.gz
tar -xvf wordpress-5.7.8-ko_KR.tar.gz
yum install -y httpd
cp -r wordpress/* /var/www/html/
amazon-linux-extras enable php8.0
yum install -y php php-fpm php-pdo php-mysqlnd
cp /var/www/html/wp-config-sample.php /var/www/html/wp-config.php
sed -i 's/DirectoryIndex index.html/DirectoryIndex index.php/g' /etc/httpd/conf/httpd.conf
sed -i 's/database_name_here/wordpress/g' /var/www/html/wp-config.php
sed -i 's/username_here/root/g' /var/www/html/wp-config.php
sed -i 's/password_here/It12345!/g' /var/www/html/wp-config.php
sed -i 's/localhost/{rds엔드포인트}/g' /var/www/html/wp-config.php
cat > /var/www/html/health.html << eof			# 이 부분 추가
<html><body><h1>hello</h1></body></html>		# 이 부분 추가
eof												# 이 부분 추가
systemctl enable --now httpd

15. 로드밸런서 리스너 생성

resource "aws_lb_listener" "ksh_alblis" {
  load_balancer_arn = aws_lb.ksh_alb.arn
  port              = 80
  protocol          = "HTTP"

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

16. ami 이미지 생성

오토스케일링 할 때 사용할 이미지를 생성을 해줍니다.

resource "aws_ami_from_instance" "ksh_ami" {
  name               = "ksh-ami"
  source_instance_id = aws_instance.ksh-ec2_weba.id
  depends_on = [
    aws_instance.ksh-ec2_weba
  ]
  tags = {
    Name = "ksh-ami"
  }
}

17. 오토스케일링 시작 템플릿 생성

오토스케일링 그룹을 생성하기 전에 오토스케일링이 진행 될 때 사용되는 시작 템플릿을 생성 해준다.

resource "aws_launch_template" "ksh_lt" {
  name = "ksh-lt"

  block_device_mappings {
    device_name = "/dev/sdf"
    ebs {
      volume_size = 10
      volume_type = "gp2"
    }
  }
  image_id               = aws_ami_from_instance.ksh_ami.id
  instance_type          = "t2.micro"
  key_name               = "ksh1"
  vpc_security_group_ids = [aws_security_group.ksh_sg.id]
  tag_specifications {
    resource_type = "instance"
    tags = {
      Name = "ksh-temp"
    }
  }
  #    user_data = filebase64("${path.module}/install.sh") # 반드시 암호화한 UserData 사용
}

18. 오토스케일링 그룹 생성

resource "aws_autoscaling_group" "ksh_atsg" {
  name                      = "ksh-atsg"
  min_size                  = 1
  max_size                  = 6
  desired_capacity          = 1
  health_check_grace_period = 60
  health_check_type         = "EC2"
  force_delete              = false
  vpc_zone_identifier       = [aws_subnet.ksh_weba.id,aws_subnet.ksh_webc.id]
  # vpc_zone_identifier = concat(aws_subnet.ksh_web[*].id)
  launch_template {
    id      = aws_launch_template.ksh_lt.id
    version = "$Latest"
  }
}

19. 오토스케일링 그룹을 로드밸런서에 붙이기

resource "aws_autoscaling_attachment" "ksh_atsgat" {
  autoscaling_group_name = aws_autoscaling_group.ksh_atsg.id
  lb_target_group_arn    = aws_lb_target_group.ksh_albtg.arn
}

20. RDS 생성

resource "aws_db_subnet_group" "ksh_dbsg" {
  name       = "ksh-dbsg"
  subnet_ids = [aws_subnet.ksh_dba.id,aws_subnet.ksh_dbc.id]
}

resource "aws_db_instance" "ksh_db" {
  allocated_storage      = 20
  storage_type           = "gp2"
  engine                 = "mysql"
  engine_version         = "8.0"
  instance_class         = "db.t2.micro"
  db_name                = "wordpress"
  identifier             = "mydb"
  username               = "root"
  password               = "It12345!"
  parameter_group_name   = "default.mysql8.0"
  availability_zone      = "ap-northeast-2a"
  db_subnet_group_name   = aws_db_subnet_group.ksh_dbsg.id
  vpc_security_group_ids = [aws_security_group.ksh_sg.id]
  skip_final_snapshot    = true
  tags = {
    Name = "ksh-db"
  }
}

최종 결과

반응형

'Terraform' 카테고리의 다른 글

Terraform 404 error 해결  (0) 2024.07.01
Terraform 실습 해보기 - 1  (1) 2023.12.13