Ravichandran
Ravichandran

Reputation: 481

How to use environment variables in terraform using TF_VAR_name?

I'm trying to export list variables and use them via TF_VAR_name and getting error while combining them with toset function.

Success scenario:

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
}

Failure scenario:

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

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.

Upvotes: 0

Views: 2321

Answers (1)

yvesonline
yvesonline

Reputation: 4837

You'll need to specify the type (i.e. type = list(string) in your case) of your variable then it should work.

I tested it with the following configuration:

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

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

  triggers = {
    name = each.key
  }
}

Then a TF_VAR_sg_name='["SG1", "SG2", "SG3", "SG4", "SG5"]' terraform apply works.

If I remove the type = list(string) it errors out as you say.

Upvotes: 2

Related Questions