如何使用 TF_VAR_name 在 terraform 中使用环境变量?

How to use environment variables in terraform using TF_VAR_name?

我正在尝试导出列表变量并通过 TF_VAR_name 使用它们,但在将它们与 toset 函数组合时出现错误。

成功场景:

terraform apply -auto-approve

# Variables
variable "sg_name"          { default = ["SG1", "SG2", "SG3", "SG4", "SG5"] }
variable "Project"          { default = "POC" }
variable "Owner"            { default = "Me" }
variable "Environment"      { default = "Testing" }

locals {
 common_tags = {
   Project                   = var.Project
   Owner                     = var.Owner
   Environment               = var.Environment
 }
}

# Create Security Group
resource "aws_security_group" "application_sg" {
  for_each    = toset(var.sg_name)
  name        = each.value
  description = "${each.value} security group"
  tags        = merge(local.common_tags, { "Name" = each.value })
}

# Output the SG IDs
output "sg_id" {
  value = values(aws_security_group.application_sg)[*].id
}

失败场景:

TF_VAR_sg_name='["SG1", "SG2", "SG3", "SG4", "SG5"]' terraform apply -auto-approve

# Variables
variable "sg_name"          { }
variable "Project"          { default = "POC" }
variable "Owner"            { default = "Me" }
variable "Environment"      { default = "Testing" }

locals {
 common_tags = {
   Project                   = var.Project
   Owner                     = var.Owner
   Environment               = var.Environment
 }
}

# Create Security Group
resource "aws_security_group" "application_sg" {
  for_each    = toset(var.sg_name)
  name        = each.value
  description = "${each.value} security group"
  tags        = merge(local.common_tags, { "Name" = each.value })
}

# Output the SG IDs
output "sg_id" {
  value = values(aws_security_group.application_sg)[*].id
}

错误

Error: Invalid function argument

  on main.tf line 16, in resource "aws_security_group" "application_sg":
  16:   for_each    = toset(var.sg_name)
    |----------------
    | var.sg_name is "[\"SG1\", \"SG2\", \"SG3\", \"SG4\", \"SG5\"]"

Invalid value for "v" parameter: cannot convert string to set of any single
type.

您需要指定变量的类型(即 type = list(string) 在您的情况下)然后它应该可以工作。

我使用以下配置对其进行了测试:

variable "sg_name" {
  type = list(string)
}

resource "null_resource" "application_sg" {
  for_each = toset(var.sg_name)

  triggers = {
    name = each.key
  }
}

然后 TF_VAR_sg_name='["SG1", "SG2", "SG3", "SG4", "SG5"]' terraform apply 工作。

如果我删除 type = list(string) 它会像你说的那样出错。