Home > database >  How to conditionally use existing resource in Terraform?
How to conditionally use existing resource in Terraform?

Time:09-29

In my Terraform (0.14.10) module, I'd like to provide the option of deploying into an existing AWS VPC. I'm varying the count operator based on a boolean input use_existing_network.

If use_existing_network is false, I create a VPC network. If it's true, I retrieve the existing resource with a data block.

resource "aws_vpc" "cluster_network" {
  count = var.use_existing_network ? 0 : 1

  cidr_block = "10.0.0.0/16"

  tags = {
    Name = var.network_name
  }
}

data "aws_vpc" "cluster_network" {
  count = var.use_existing_network ? 1 : 0

  filter {
    name   = "tag:Name"
    values = [var.network_name]
  }
}

However, I get the following error when I attempt to reference the network (a tuple, since it's created with the count operator) later:

Error: Invalid index

  on ../../modules/network/main.tf line 61, in resource "aws_internet_gateway" "igw":
  61:   vpc_id = aws_vpc.cluster_network[0].id
    |----------------
    | aws_vpc.cluster_network is empty tuple

The given key does not identify an element in this collection value.

Why doesn't this work, and how can I achieve this?

CodePudding user response:

In your case cluster_network is either a resource or data source, depending on the condition. They are referred to differently. You could use local to unify that. For example with try:

locals {
   cluster_network = try(aws_vpc.cluster_network[0], data.aws_vpc.cluster_network[0])
}

Then use local.cluster_network.id in the rest of the code.

  • Related