我有一个env
变量,用于定义不同的环境:
env = {
"dev" = {
"environment" = "development",
"create_RDS" = false,
"db_password" = "postgres",
},
"int" = {
"environment" = "integration",
"create_RDS" = false,
"db_password" = "postgres"
},
"pre" = {
"environment" = "staging",
"create_RDS" = true,
"db_password" = "",
},
"pro" = {
"environment" = "production",
"create_RDS" = true,
"db_password" = ""
}
}
每个名称都绑定到一个地形工作区(dev、int、pre、pro…(
以下是数据库的创建:
locals {
vpc_id = data.aws_vpc.this.id
create_RDS = var.env[terraform.workspace]["create_RDS"]
db_password = var.env[terraform.workspace]["db_password"] != "" ? var.env[terraform.workspace]["db_password"] : random_password.db_password.result
depends_on = [random_password.db_password]
}
module "db" {
source = "terraform-aws-modules/rds/aws"
version = "~> 2.0"
identifier = terraform.workspace
count = local.create_RDS == true ? 1 : 0
# Disable creation of RDS instance(s)
create_db_instance = true
engine = "postgres"
engine_version = "11.10"
family = "postgres11"
instance_class = "db.t3.micro"
#instance_class = var.env[terraform.workspace]["db_instance_class"]
major_engine_version = "11"
allocated_storage = 5
storage_encrypted = true
name = "aqn${terraform.workspace}"
username = "user_${terraform.workspace}"
password = local.db_password
port = "5432"
iam_database_authentication_enabled = false
vpc_security_group_ids = [module.db_security_group.security_group_id]
maintenance_window = "Mon:00:00-Mon:03:00"
backup_window = "03:00-06:00"
# Enhanced Monitoring - see example for details on how to create the role
# by yourself, in case you don't want to create it automatically
monitoring_interval = "0"
monitoring_role_name = "${terraform.workspace}-RDSMonitoringRole"
create_monitoring_role = true
tags = local.common_tags
# DB subnet group
subnet_ids = local.create_RDS ? data.aws_subnet_ids.private[0].ids : []
# Database Deletion Protection
deletion_protection = var.env[terraform.workspace].environment == "production" ? true : false
}
如果我修改env
变量的任何内容,即使在不同的环境部分,terraform也会尝试删除数据库。
只是修改";dev";通过添加";foo";
env = {
"dev" = {
"environment" = "development",
"create_RDS" = false,
"db_password" = "postgres",
"FOO" = "BAR"
},
"int" = {
"environment" = "integration",
"create_RDS" = false,
"db_password" = "postgres"
},
"pre" = {
"environment" = "staging",
"create_RDS" = true,
"db_password" = "",
},
"pro" = {
"environment" = "production",
"create_RDS" = true,
"db_password" = ""
}
}
当我使用pre
工作空间terraform plan
时,terraform尝试删除数据库
以下是修改不同环境变量后pre
工作空间的地形图输出。
?为什么地形在将新地图添加到不同的环境后删除数据库?
这似乎与地形如何理解地图中的布尔变量有关。
布尔变量y已定义:
"pre" = {
"environment" = "staging",
"create_RDS" = true,
"db_password" = "",
"foo" = "bar"
},
但是随后比较布尔变量";create_RDS";terraform将其解释为字符串,因此我更改了表达式(每个布尔表达式(以比较字符串而不是布尔表达式,并且似乎运行良好:
subnet_ids = local.create_RDS == "true" ? data.aws_subnet_ids.private[0].ids : data.aws_subnet_ids.private-pre.ids