使用 terraform 启动 aws elb 实例

launching aws elb instace using terraform

我是 terraform 和 aws 的新手,我想做的就是启动一个 aws ec2 实例,该实例带有带有 terraform 的弹性负载均衡器。我从各个站点获得了一些配置示例,但不知道实现这些配置的正确方法是什么,文件夹结构应该是什么等等。我已经使用 aws 的 GUI 完成了它,但在 terraform 方面没有得到太多帮助。

这里服务器应该是apache2.

感谢任何帮助。

提前致谢

根据您创建 Elastic Loadbalancer 的要求,使用 terraform。您将需要创建以下资源。 如果您已经创建了 EC2 实例并且只想将它们附加到 ELB。

  • 创建目标组
  • 创建ELB
  • 将目标组分配给您的 ELB
  • 将您现有的实例注册到您的目标组

如果您没有创建任何实例,

  • 创建目标组
  • 创建ELB
  • 将目标组分配给您的 ELB
  • 创建启动Template/Configuration
  • 创建ASG,将ELB分配给ASG
  • 通过ASG创建的新实例会自动注册到ELB目标组。

Terraform 资源示例,

启动配置

resource "aws_launch_configuration" "Your_Launch_Configuration" {
  name                 = "launch_conf_name"
  instance_type        = "Instance_Type"
  image_id             = "AMI_image_id"
  key_name             = "Key_Name"
  security_groups      = "security_groups_id"
  user_data            = "User Data"
  iam_instance_profile = "Instance IAM Role"
}

Auto Scaling 组

resource "aws_autoscaling_group" "Your_ASG" {
  name                 = "ASG Name"
  launch_configuration = aws_launch_configuration.Your_Launch_Configuration.id
  max_size             = "Max size"
  min_size             = "Min Size"
  desired_capacity     = "Desired Capacity"
  vpc_zone_identifier  = "Your Subnet List"
  tags = [{
    "key"                 = "Name"
    "value"               = "ASG Name"
    "propagate_at_launch" = true
  }]
  health_check_grace_period = "300"
  target_group_arns         = "set of your ELB target Group"
}

负载均衡器目标组

resource "aws_load_balancer_target_group" "Your_target_group" {
  name     = "Target_group_name"
  port     = "80"
  protocol = "HTTP"
  vpc_id   = "Your_vpcid"
  tags = {
    name = "Target_group_name"
  }

  health_check {
    enabled  = true
    interval = 300  # health check interval
    protocol = "HTTP"  
    timeout  = 300  # timeout seconds
    path     = "/" # your health check path
  }
}

负载均衡器

resource "aws_load_balancer" "your_load_balancer" {
  name               = load_balancer_name
  load_balancer_type = "application"
  internal           = true # if not internet facing
  subnets            = ["List of your subnet id"]
  security_groups    = ["List of your security group id"]

  tags = {
    "name" = load_balancer_Target_group_name
  }
}

负载均衡器监听器

resource "aws_load_balancer_listener" "your_load_balancer_Listner" {
  load_balancer_arn = listner_load_balancer_arn   #arn of your load balancer
  port              = "80"
  protocol          = "http"

  default_action {
    target_group_arn = listner_Target_group_arn  # arn of your target group
    type             = "forward"
  }
}