postgresql 如何使用terraform在postgressql的参数组上动态添加自定义rds参数?

35g0bw71  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(149)

我已经使用下面的代码来编辑使用terraform的aws上的参数组上的postgresssql参数的值。
main.tf

resource "aws_db_parameter_group" "education" {
  name   = "education"
  family = var.family

  parameter {
    apply_method = "immediate"
    name         = "name_of_parameter_1"
    value        = "value for parameter 1"
  }
  parameter {
    apply_method = "immediate"
    name         = "name_of_prameter_2"
    value        = "value_for_parameter_2"
  }

}

resource "aws_db_instance" "education" {
  identifier             = "education"
  instance_class         = "db.t3.micro"
  allocated_storage      = 5
  engine                 = "postgres"
  engine_version         = "14.1"
  username               = "edu"
  password               = var.db_password
  db_subnet_group_name   = aws_db_subnet_group.education.name
  vpc_security_group_ids = [aws_security_group.rds.id]
  parameter_group_name   = aws_db_parameter_group.education.name
  publicly_accessible    = true
  skip_final_snapshot    = true
}

字符串
来自variables.tf的代码片段

variable "family" {
  description = "The family of the DB parameter group"
  type        = string
}


如何重构上面的代码,以便将参数添加到terraform.tfvars文件的列表中,并将它们动态加载到aws_db_parameter_group中,而不是像上面的示例那样将它们硬编码在那里?

sc4hvdpw

sc4hvdpw1#

列表是错误的数据结构,在.tfvars文件中需要参数名和参数值,这自然会用map表示。
terraform.tfvars文件可能看起来像这样:

rds_parameters = {
  param1 = "param 1 value",
  param2 = "param 2 value",
  param3 = "param 3 value",
}

字符串
variables.tf中的输入变量看起来像这样:

variable "rds_parameters " {
  description = "The map of DB parameter names and values"
  type        = map(string)
}


最后,您将使用Terraform dynamic block从该Map创建DB参数:

resource "aws_db_parameter_group" "education" {
  name   = "education"
  family = var.family

  dynamic "parameter " {
    for_each = var.rds_parameters
    content {
      apply_method = "immediate"
      name = setting.key
      value = setting.value
    }
  }
}

相关问题