Terraform 이어서

번외. 모듈 사용

디렉토리
--------
root/
├── main.tf
├── modules/
│   ├── ec2/
│   │   ├── main.tf
│   │   ├── variables.tf
│   │   └── outputs.tf
│   └── eip/
│       ├── main.tf
│       ├── variables.tf
루트(main.tf)에서 모듈로 변수 전달 -> 모듈 내부에서 사용
- [루트 main.tf] -> [모듈 variabels.tf / main.tf]
-----------------------------------------------
# root/main.tf
module "ec2" {
	source = "./modules/ec2"
	ami = "ami-123"
	name = "web"
}

# modules/ec2/variables.tf
variable "ami" { type = string }
variable "name" { type = string }

# modules/ec2/main.tf
resource "aws_instance" "this" {
  ami = var.ami
  tags = {
    Name = var.name
  }
}
=>
루트 main.tf에서 ami,name같은 변수를 module "ec2"로 넘김
이 값은 /ec2/variabels.tf에서 받아서 /ec2/main.tf의 리소스에 사용

모듈 내부 리소스 값을 루트에서 꺼내 쓰기
- [모듈 outputs.tf] -> [루트 main.tf] -> 다른 리소스에서 참조
------------------------------------------------------------
# modules/ec2/output.tf
output "instance_id" {
	instance_id = aws_instance.this.id
}

# root/main.tf
module "eip" {
	source = "./modules/eip"
	ec2_id = module.ec2.instance_id
}

# modules/eip/variables.tf
variabels "ec2_id" {
	type = string
}

# modules/eip/main.tf
resource "aws_eip" "this" {
	instance = var.ec2_id
}

웹 서버 클러스터 배포

image.png

ASG 생성

variable "server_port" {
    type = number
    default = 8080
}

# instance 명 example의 subnet_id를 public_ip 변수로 저
# output "public_ip" {
#    value = aws_instance.example.public_id
#    description = "The public IP"
#}

# data = 기존에 aws에 있던 리소스의 값을 가져
data "aws_vpc" "default" {
    default=true
}

data "aws_subnets" "default" {
    filter {
        name = "vpc-id"
        values = [data.aws_vpc.default.id]
    }
}

resource "aws_launch_configuration" "example" {
    image_id = "ami-08943a151bd468f4e"
    instance_type = "t3.micro"
    security_groups = [aws_security_group.instance.id]

    user_data = <<-EOF
        #!/bin/bash
        echo "Hello, World" > index.html
        nohup busybox httpd -f -p ${var.server_port} &
        EOF
    
    # Required when using a launch configuration with an auto scaling group.
    lifecycle {
        create_before_destroy = true
    }
}

resource "aws_autoscaling_group" "example" {
    launch_configuration = aws_launch_configuration.example.name
    vpc_zone_identifier = data.aws_subnets.default.ids
    target_group_arns = [aws_lb_target_group.asg.arn]
    health_check_type = "ELB"
    min_size = 2
    max_size = 10

    tag {
        key = "Name"
        value = "terraform-asg-example"
        propagate_at_launch = true
    }
}
=>
현재는 자동 확장/축소 설정이 안되어 있어서 min값인 2개의 ec2로 유지

resource "aws_security_group" "instance" {
    name = "terraform-example-instance"

    ingress {
        from_port = var.server_port
        to_port = var.server_port
        protocol = "tcp"
        cidr_blocks = [ "0.0.0.0/0" ]
    }
}

로드밸런서 배포

image.png