Home > Blockchain >  Terraform append string to for_each each.key
Terraform append string to for_each each.key

Time:10-23

I want to append some text to the Name tag for each resource created. I want the name to be the 'key' name "a string"

resource "aws_vpc_peering_connection" "commerce_vpc_pc" {
for_each      = local.requester_vpcs

  peer_vpc_id   = data.aws_vpc.tf_commerce_vpc.id
  vpc_id        = each.value.vpc_id
  auto_accept   = true

  tags = {
    Name = [each.key] "_pc_commerce"
  }
}

This give the error:

│ Error: Invalid operand
│ 
│   on main.tf line 34, in resource "aws_vpc_peering_connection" "commerce_vpc_pc":
│   34:     Name = [each.key] "-to-commerce_vpc"
│ 
│ Unsuitable value for right operand: a number is required.

which makes sense. However is it possible to append some text to the each.key key?

CodePudding user response:

resource "aws_vpc_peering_connection" "commerce_vpc_pc" {
for_each      = local.requester_vpcs

  peer_vpc_id   = data.aws_vpc.tf_commerce_vpc.id
  vpc_id        = each.value.vpc_id
  auto_accept   = true

  tags = {
    Name = "${each.key}_pc_commerce"
  }
}

See this another example of provisioning a customer gateway.

################################################################################
# Customer Gateways
################################################################################

resource "aws_customer_gateway" "this" {
  for_each = var.customer_gateways

  bgp_asn     = each.value["bgp_asn"]
  ip_address  = each.value["ip_address"]
  device_name = lookup(each.value, "device_name", null)
  type        = "ipsec.1"

  tags = merge(
    { Name = "${var.name}-${each.key}" },
    var.tags,
    var.customer_gateway_tags,
  )
}
  • Related