Get first element of a tuple in terraform

9/17/2021

I'm trying to deploy my EKS nodes with only one subnet but I dont know how to give to the resource only one. I show you my code:

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

On the other hand I have a normal task to create the subnets and give the ouput to all my code:

resource "aws_subnet" "private" {
  count = length(local.subnet_priv)
  vpc_id = var.vpc_id[terraform.workspace]
  cidr_block = local.subnet_priv[count.index]
  availability_zone = element(lookup(var.availability_zones, terraform.workspace), count.index)
  map_public_ip_on_launch = false

So.. I don't know how to get from my subnet_ids argument only the first subnet of the tuple. Now, as you can see, I'm getting all of them but I tried different ways to do but with no success (aws_subnet.private[0].*.id , aws_subnet.private[0].id, etc)

Any idea?

Thanks a lot!

-- hache cheche
amazon-eks
amazon-web-services
kubernetes
terraform

1 Answer

9/17/2021

EKS node group subnet_ids arguments expects a tuple. In the original example subnet_ids = aws_subnet.private.*.id the splat operator is used. The spear operator (*) essentially creates a tuple with all the available resources, in our case all the available subnets.

If we want to pass only one subnet from all the available ones, we have to create a tuple with a single element. We could do that by taking the first element from all the existing ones, for example:

subnet_ids = [aws_subnet.private[0].id]

Although, this might work, I personally don't really consider it to be elegant solution. Certainly a better way to accomplish the same result is to modify the local.subnet_priv tuple to contain only one subnet id.

-- Ervin Szilagyi
Source: StackOverflow