hache cheche
hache cheche

Reputation: 163

Conditional tags in terraform

I have a resource task to create nodes in EKS. My problem begin when I'm trying to define some tags according to the value of a specific variable and if not, don't declare the tag. Something like that:

resource "aws_eks_node_group" "managed_workers" {
  for_each = var.nodegroups[terraform.workspace]

  cluster_name    = aws_eks_cluster.cluster.name
  node_group_name = each.value.Name
  node_role_arn   = aws_iam_role.managed_workers.arn
  subnet_ids      = aws_subnet.private.*.id

  tags = merge(
      var.tags[terraform.workspace], {
      
    if somevar = value then
      "topology.kubernetes.io/zone" = "us-east-2a"  <--- THIS TAG IS CONDITIONAL
    fi
      "type" = each.value.type
      "Name" = each.value.Name
      "ob"   = each.value.ob
      "platform" = each.value.platform
  })      

Is there possible?

Upvotes: 1

Views: 3234

Answers (2)

Kyle Gibson
Kyle Gibson

Reputation: 1220

Here's an example that does not use the ... operator. This works in terraform v1.3.1:

resource "aws_eks_node_group" "managed_workers" {
  for_each = var.nodegroups[terraform.workspace]

  cluster_name    = aws_eks_cluster.cluster.name
  node_group_name = each.value.Name
  node_role_arn   = aws_iam_role.managed_workers.arn
  subnet_ids      = aws_subnet.private.*.id

  tags = merge(
      var.tags[terraform.workspace], 
      {      
        "type" = each.value.type
        "Name" = each.value.Name
        "ob"   = each.value.ob
        "platform" = each.value.platform
      },
      var.somevar != "value" ? {} :
      {
        "topology.kubernetes.io/zone" = "us-east-2a"
      },
  )
}

Upvotes: 2

Marcin
Marcin

Reputation: 238209

Yes, you can do this. For example:

resource "aws_eks_node_group" "managed_workers" {
  for_each = var.nodegroups[terraform.workspace]

  cluster_name    = aws_eks_cluster.cluster.name
  node_group_name = each.value.Name
  node_role_arn   = aws_iam_role.managed_workers.arn
  subnet_ids      = aws_subnet.private.*.id

  tags = merge(
      var.tags[terraform.workspace], {      
      "type" = each.value.type
      "Name" = each.value.Name
      "ob"   = each.value.ob
      "platform" = each.value.platform},
      [somevar == value  ? {"topology.kubernetes.io/zone" = "us-east-2a"} : null]...)
} 

The ... is for expanding-function-arguments.

Upvotes: 4

Related Questions