You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Terraform部署运行Apache2的AWS EC2实例并配置ELB弹性负载均衡

项目规范与实现指导

一、推荐的项目文件夹结构

terraform-aws-elb-apache-demo/
├── main.tf                 # 核心资源定义
├── variables.tf            # 可配置变量定义
├── outputs.tf              # 部署后输出信息
├── terraform.tfvars        # 变量赋值(可选,注意加入.gitignore)
└── .gitignore              # Git忽略规则

每个文件职责单一,便于后续迭代维护,也符合Terraform社区通用规范。

二、核心配置示例

前提条件:已在本地配置好AWS访问凭证(存放在~/.aws/credentials或者配置对应环境变量),Terraform版本>=1.0,AWS Provider版本>=4.0。

variables.tf 示例

variable "aws_region" {
  type        = string
  description = "AWS部署区域"
  default     = "cn-north-1"
}

variable "instance_type" {
  type        = string
  description = "EC2实例规格"
  default     = "t2.micro" # 符合免费 tier 要求
}

variable "ec2_key_name" {
  type        = string
  description = "AWS账户中已存在的密钥对名称,用于SSH登录EC2"
}

main.tf 示例

#  Provider 配置
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

# ELB安全组:放通公网80端口入站,全部出站
resource "aws_security_group" "elb_sg" {
  name        = "elb-apache-sg"
  description = "Allow HTTP access to ELB"

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# EC2安全组:仅允许ELB访问80端口,放通SSH登录
resource "aws_security_group" "ec2_sg" {
  name        = "ec2-apache-sg"
  description = "Allow HTTP from ELB and SSH access"

  ingress {
    from_port       = 80
    to_port         = 80
    protocol        = "tcp"
    security_groups = [aws_security_group.elb_sg.id]
  }

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"] # 生产环境建议替换为你的公网IP段
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

# EC2启动模板,自动安装Apache2
resource "aws_launch_template" "apache_launch_tpl" {
  name_prefix   = "apache-server-"
  image_id      = "ami-08e0ca2a4af4157e7" # Amazon Linux 2 AMI(北京区),其他区域请替换为对应区域的AMI ID
  instance_type = var.instance_type
  key_name      = var.ec2_key_name
  security_group_ids = [aws_security_group.ec2_sg.id]

  user_data = base64encode(<<-EOF
              #!/bin/bash
              yum update -y
              yum install -y httpd
              systemctl start httpd
              systemctl enable httpd
              echo "<h1>Apache Server deployed by Terraform</h1>" > /var/www/html/index.html
              EOF
  )
}

# 负载均衡目标组
resource "aws_lb_target_group" "apache_tg" {
  name     = "apache-target-group"
  port     = 80
  protocol = "HTTP"
  vpc_id   = data.aws_vpc.default.id
}

# 应用负载均衡
resource "aws_lb" "apache_elb" {
  name               = "apache-elb"
  internal           = false
  load_balancer_type = "application"
  security_groups    = [aws_security_group.elb_sg.id]
  subnets            = data.aws_subnets.default.ids

  enable_deletion_protection = false # 测试环境可关闭,生产环境建议开启
}

# ELB监听器,转发80端口请求到目标组
resource "aws_lb_listener" "elb_listener" {
  load_balancer_arn = aws_lb.apache_elb.arn
  port              = 80
  protocol          = "HTTP"

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

# 自动扩缩容组,启动2台EC2实例
resource "aws_autoscaling_group" "apache_asg" {
  name_prefix          = "apache-asg-"
  min_size             = 2
  max_size             = 4
  desired_capacity     = 2
  vpc_zone_identifier  = data.aws_subnets.default.ids
  target_group_arns    = [aws_lb_target_group.apache_tg.arn]

  launch_template {
    id      = aws_launch_template.apache_launch_tpl.id
    version = "$Latest"
  }

  tag {
    key                 = "Name"
    value               = "apache-server"
    propagate_at_launch = true
  }
}

# 调用默认VPC数据
data "aws_vpc" "default" {
  default = true
}

# 调用默认VPC下的公网子网数据
data "aws_subnets" "default" {
  filter {
    name   = "vpc-id"
    values = [data.aws_vpc.default.id]
  }
}

outputs.tf 示例

output "elb_dns_name" {
  description = "负载均衡的公网访问地址"
  value       = aws_lb.apache_elb.dns_name
}

.gitignore 示例

# Terraform 缓存和状态文件
.terraform/
*.tfstate
*.tfstate.backup
*.tfvars
.terraform.lock.hcl

三、部署步骤

  • 进入项目文件夹,执行 terraform init 初始化依赖的Provider
  • 执行 terraform plan 预览将要创建的资源,确认配置无误
  • 执行 terraform apply 启动部署,输入yes后等待执行完成
  • 部署完成后输出的elb_dns_name就是Apache服务的访问地址,直接在浏览器打开即可验证

四、注意事项

  • 生产环境不要将SSH端口对0.0.0.0/0开放,替换为你自己的公网IP段
  • 敏感信息不要写入配置文件,建议通过环境变量或者AWS IAM角色传递
  • 测试完成后执行 terraform destroy 销毁资源,避免产生不必要的费用

内容的提问来源于stack exchange,提问作者learning_bunny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 13:27:01