是否有Terraform方法可以创建多个Aurora DB集群?我试图使cluster_name成为一个列表,但看起来像";cluster_identifier";resource需要一个String,而不是一个字符串列表。我可以为一个集群创建多个实例,但我看不到在Terraform中创建多个DB集群的方法。
# The Aurora cluster (which contains database instances created below).
resource "aws_rds_cluster" "aurora_cluster" {
engine = var.rds_engine
engine_version = var.rds_engine_version
cluster_identifier = var.rds_cluster_name
master_username = local.aurora_creds.username
master_password = local.aurora_creds.password
db_subnet_group_name = var.subnet_group_name
iam_roles = var.rds_iam_roles
vpc_security_group_ids = var.security_groups
lifecycle {
create_before_destroy = true
}
}
resource "aws_rds_cluster_instance" "aurora_instance" {
engine = var.rds_engine
engine_version = var.rds_engine_version
count = var.instance_count
identifier = "${var.rds_cluster_name}-${count.index}"
cluster_identifier = var.rds_cluster_name
instance_class = var.rds_instance_class
db_subnet_group_name = var.subnet_group_name
availability_zone = lookup(element(var.subnet_zones, count.index), "zone")
publicly_accessible = false
lifecycle {
create_before_destroy = true
}
}
有几种方法可以在Terraform中提供x
数量的资源。
您可以在资源本身中使用count属性。
locals {
instance_count = 2
}
resource "aws_rds_cluster_instance" "aurora_instance" {
count = local.instance_count
engine = var.rds_engine
engine_version = var.rds_engine_version
identifier = "${var.rds_cluster_name}-${count.index}"
cluster_identifier = var.rds_cluster_name
instance_class = var.rds_instance_class
db_subnet_group_name = var.subnet_group_name
availability_zone = lookup(element(var.subnet_zones, count.index), "zone")
publicly_accessible = false
lifecycle {
create_before_destroy = true
}
}
或者可以使用for_each属性。
locals {
zones = ["us-west-2a", "us-west-2b"]
}
resource "aws_rds_cluster_instance" "aurora_instance" {
for_each = toset(local.zones)
engine = var.rds_engine
engine_version = var.rds_engine_version
identifier = "${var.rds_cluster_name}-${each.key}"
cluster_identifier = var.rds_cluster_name
instance_class = var.rds_instance_class
db_subnet_group_name = var.subnet_group_name
availability_zone = each.key
publicly_accessible = false
lifecycle {
create_before_destroy = true
}
}
我建议您为此使用一个模块,然后使用1efty的方法进行foreach计数,该模块将在内部为您创建实例:https://registry.terraform.io/modules/terraform-aws-modules/rds-aurora/aws
例如:
module "cluster" {
source = "terraform-aws-modules/rds-aurora/aws"
for_each = {
cluster_one = "a"
cluster_two = "b"
}
name = "test-aurora-db-postgres96"
engine = "aurora-postgresql"
engine_version = "14.5"
instance_class = "db.r6g.large"
instances = {
one = {}
2 = {
instance_class = "db.r6g.2xlarge"
}
}
vpc_id = "vpc-12345678"
db_subnet_group_name = "db-subnet-group"
security_group_rules = {
ex1_ingress = {
cidr_blocks = ["10.20.0.0/20"]
}
ex1_ingress = {
source_security_group_id = "sg-12345678"
}
}
storage_encrypted = true
apply_immediately = true
monitoring_interval = 10
enabled_cloudwatch_logs_exports = ["postgresql"]
tags = {
Environment = "dev"
Terraform = "true"
}
}