4. 部署AWS RDS数据库

任务目标

使用 Terraform 在 AWS 上创建一个 MySQL RDS 实例,同时配置安全组以允许特定来源访问数据库端口,并创建自定义参数组以调整数据库引擎配置。

环境依赖

  • Terraform >= 1.0
  • AWS Provider >= 5.0
  • AWS 账号凭证(环境变量 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY,或已配置的默认凭证链)

实现代码

创建 main.tf 文件,内容如下:

# 配置 AWS Provider(区域可自行修改)
provider "aws" {
  region = "us-east-1"
}

# 创建安全组,允许外部访问 MySQL 端口 3306
resource "aws_security_group" "rds_sg" {
  name        = "mysql-rds-sg"
  description = "Allow MySQL access from specified CIDR"

  ingress {
    from_port   = 3306
    to_port     = 3306
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]  # 生产环境建议限制为具体 IP 或 VPC CIDR
  }

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

  tags = {
    Name = "mysql-rds-sg"
  }
}

# 创建 MySQL 参数组,设置时区为 UTC
resource "aws_db_parameter_group" "mysql_params" {
  name   = "mysql-custom-params"
  family = "mysql8.0"

  parameter {
    name  = "time_zone"
    value = "UTC"
  }

  parameter {
    name  = "max_connections"
    value = "100"
  }
}

# 创建 MySQL RDS 实例
resource "aws_db_instance" "mysql" {
  identifier     = "mysql-rds-instance"
  engine         = "mysql"
  engine_version = "8.0.35"
  instance_class = "db.t3.micro"

  allocated_storage     = 20
  storage_type          = "gp2"
  db_name               = "appdb"
  username              = "admin"
  password              = "YourStrongP@ssw0rd!"  # 生产环境建议使用 secrets 管理
  parameter_group_name  = aws_db_parameter_group.mysql_params.name
  vpc_security_group_ids = [aws_security_group.rds_sg.id]

  skip_final_snapshot = true
  publicly_accessible = true  # 仅用于演示,生产环境应设为 false

  tags = {
    Name = "mysql-rds-instance"
  }
}

# 输出数据库连接信息
output "rds_endpoint" {
  value = aws_db_instance.mysql.endpoint
}

output "rds_port" {
  value = aws_db_instance.mysql.port
}

运行与验证

  1. 在 main.tf 所在目录执行 terraform init 初始化工作目录。
  2. 执行 terraform plan 查看将要创建的资源计划,确认无误。
  3. 执行 terraform apply 并输入 yes 确认创建资源。
  4. 创建完成后,观察输出中的 rds_endpoint 和 rds_port 值。

验证通过条件:

  • terraform apply 成功完成,无错误信息。
  • AWS 控制台 RDS 页面出现名为 mysql-rds-instance 的实例,状态为 Available。
  • 安全组 mysql-rds-sg 存在且入站规则包含 3306 端口。
  • 参数组 mysql-custom-params 已关联到该实例,且 time_zone 值为 UTC。
  • 使用 MySQL 客户端从允许的 IP 执行 mysql -h <endpoint> -P 3306 -u admin -p 能成功连接。

清理资源

完成验证后,执行 terraform destroy 并输入 yes 释放所有资源,避免产生持续费用。