使用Terraform创建AWS RDS实例?

时间:2019-08-12 12:01:56

标签: amazon-web-services terraform

我正在尝试使用terraform在AWS上创建RDS实例,并出现以下错误

此代码可以吗?

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}


resource "aws_subnet" "private-subnet1" {
  vpc_id = "${aws_vpc.main.id}"
  cidr_block = "10.0.1.0/24"
}

resource "aws_subnet" "private-subnet2" {
  vpc_id = "${aws_vpc.main.id}"
  cidr_block = "10.0.2.0/24"
}

resource "aws_db_subnet_group" "db-subnet" {
  name       = "DB subnet group"
  subnet_ids = ["${aws_subnet.private-subnet1.id}", "${aws_subnet.private-subnet2.id}"]
}


resource "aws_db_instance" "db" {
  allocated_storage    = "20"
  storage_type         = "gp2"
  engine               = "mysql"
  engine_version       = "5.7.22"
  instance_class       = "db.t2.micro"
  name                 = "mydb"
  username             = "admin"
  password             = "admin"
  parameter_group_name = "db-mysql"
  db_subnet_group_name = "db-subnet"
}

我在进行地形应用时遇到此错误

Error: Error creating DB Subnet Group: DBSubnetGroupDoesNotCoverEnoughAZs: DB Subnet Group doesn't meet availability zone coverage requirement. Please add subnets to cover at least 2 availability zones. Current coverage: 1
    status code: 400, request id: 1bc7f2db-3ad7-41d9-93d0-6cbe3c0adfec

  on terraform.tf line 24, in resource "aws_db_subnet_group" "db-subnet":
  24: resource "aws_db_subnet_group" "db-subnet" {



Error: Error creating DB Instance: DBSubnetGroupNotFoundFault: DBSubnetGroup 'db-subnet' not found.
    status code: 404, request id: a4264af9-c9ac-4241-993f-e8c62e348247

  on terraform.tf line 30, in resource "aws_db_instance" "db":
  30: resource "aws_db_instance" "db" {

1 个答案:

答案 0 :(得分:2)

关于这些问题的错误非常清楚,因此让我们对其进行分解。

第一个错误与以下事实有关:在创建每个子网时没有指定availability zone。 db子网组必须跨越至少2个az才能获得高可用性,并且您没有为子网指定az,因此它们是在同一子网中创建的。将availability_zone参数添加到两个子网中,并使用与您所使用的区域不同的z。

resource "aws_subnet" "private-subnet1" {
  vpc_id = "${aws_vpc.main.id}"
  cidr_block = "10.0.1.0/24"
  availability_zone = "<an az from your region>"
}

resource "aws_subnet" "private-subnet2" {
  vpc_id = "${aws_vpc.main.id}"
  cidr_block = "10.0.2.0/24"
  availability_zone = "<a different az from your region>"
}

第二个错误与以下事实有关:在aws_db_instance中,您没有引用正在创建的子网组资源,而是通过名称指定了一个硬编码的子网组。 Terraform不了解依赖关系,并在尝试创建您定义的依赖关系时并行使用不存在的依赖关系。将其更改为

db_subnet_group_name = "${aws_db_subnet_group.db-subnet.name}"

第二个错误将消失,然后您可以解决第一个问题。