EC2 ASG 생성하기

AWS Auto Scaling Group은 Amazon Web Services(AWS)에서 제공하는 서비스로, 클라우드 인프라 내의 리소스를 자동으로 확장하거나 축소할 수 있게 해주는 기능입니다. 사용자의 애플리케이션이 겪는 트래픽의 변화에 따라 필요한 컴퓨팅 리소스를 동적으로 조정하여, 최적의 성능을 유지하면서 비용을 효율적으로 관리할 수 있습니다.

Auto Scaling Group의 주요 기능은 다음과 같습니다:

  • Elastic: 트래픽이 증가할 때 자동으로 EC2 인스턴스를 추가하여 처리 능력을 증가시키고, 트래픽이 감소할 때는 인스턴스를 자동으로 줄여 비용을 절약할 수 있습니다.

  • High Availability: 여러 가용 영역(Availability Zones)에 걸쳐 인스턴스를 분산시켜, 하나의 영역에 문제가 생겼을 때도 애플리케이션이 계속 작동할 수 있게 합니다.

  • Load balancing: Auto Scaling Group은 AWS Elastic Load Balancing(ELB)과 통합되어, 인스턴스 간에 들어오는 트래픽을 자동으로 분산시킬 수 있습니다.

service.tf

##### ASG

resource "aws_launch_template" "lt" {
  name_prefix   = "${var.service_name}-${var.vpc_name}-LT"
  image_id      = var.image_id
  instance_type = var.instance_type
  key_name      = var.key_name

  vpc_security_group_ids = [aws_security_group.ec2.id]

  tag_specifications {
    resource_type = "instance"
    tags = {
      Name = "${var.service_name}-${var.vpc_name}-LaunchTemplate"
    }
  }
}

resource "aws_autoscaling_group" "asg" {
  launch_template {
    id      = aws_launch_template.lt.id
    version = "$Latest"

  }

  min_size         = var.min_size
  max_size         = var.max_size
  desired_capacity = var.desired_capacity
  vpc_zone_identifier = var.private_subnets

  target_group_arns = [aws_lb_target_group.internal.arn]

  tag {
    key                 = "Name"
    value               = "${var.service_name}-${var.vpc_name}-asg"
    
    propagate_at_launch = true
  }
}

### variables.tf

variable "image_id" {
  description = "AMI ID for instance"
  type        = string
  default     = "ami-0032724dd60a24c31"
}

variable "instance_type" {
  description = "EC2 Instance type"
  type        = string
  default     = "t3.small"
}

variable "key_name" {
  description = "EC2 key-pair"
  type        = string
}

variable "min_size" {
  description = "Auto Scaling min size"
  type        = number
  default     = 1
}

variable "max_size" {
  description = "Auto Scaling max size"
  type        = number
  default     = 1
}

variable "desired_capacity" {
  description = "Auto Scaling desired capacity"
  type        = number
  default     = 1
}

Last updated