我正在尝试通过使用Terraform的 for_each 和 count 参数迭代字符串列表来创建GCP SQL数据库,而另一个循环用于映射键( maindb 和副本)。
不幸的是,我得到了下面显示的错误。
是否有可能是Terraform?
variables.tf
variable "sql_var" {
default = {
"maindb" = {
"db_list" = ["firstdb", "secondsdb", "thirddb"],
"disk_size" = "20",
},
"replicadb" = {
"db_list" = ["firstdb"],
"disk_size" = "",
}
}
}
main.tf
resource "google_sql_database_instance" "master_sql_instance" {
...
}
resource "google_sql_database" "database" {
for_each = var.sql_var
name = "${element(each.value.db_list, count.index)}"
instance = "${google_sql_database_instance.master_sql_instance[each.key].name}"
count = "${length(each.value.db_list)}"
}
错误消息
错误:“ count”和“ for_each”的无效组合
../main.tf第43行中的“ google_sql_database”“数据库”:43:for_each = var.sql_var
“ count”和“ for_each”元参数是互斥的,仅 应该明确说明要使用的资源数量 已创建。
答案 0 :(得分:0)
错误消息告诉您,您不能同时使用count和for_each。看来您正在尝试创建3个主数据库和1个副本数据库,对吗?我要做的是创建2个主实例,然后转换map变量以创建数据库。
terraform {
required_version = ">=0.13.3"
required_providers {
google = ">=3.36.0"
}
}
variable "sql_instances" {
default = {
"main_instance" = {
"db_list" = ["first_db", "second_db", "third_db"],
"disk_size" = "20",
},
"replica_instance" = {
"db_list" = ["first_db"],
"disk_size" = "20",
}
}
}
locals {
databases = flatten([
for key, value in var.sql_instances : [
for item in value.db_list : {
name = item
instance = key
}
]
])
sql_databases = {
for item in local.databases :
uuid() => item
}
}
resource "google_sql_database_instance" "sql_instance" {
for_each = var.sql_instances
name = each.key
settings {
disk_size = each.value.disk_size
tier = "db-f1-micro"
}
}
resource "google_sql_database" "sql_database" {
for_each = local.sql_databases
name = each.value.name
instance = each.value.instance
depends_on = [
google_sql_database_instance.sql_instance,
]
}
然后,首先运行terraform apply -target=google_sql_database_instance.sql_instance
,然后再运行terraform apply
。