Rotem jackoby
Rotem jackoby

Reputation: 22058

Terraform lookup function - Error: Expected to be number, actual type is String

I'm using Terraform in order to build some AWS VPC components like the aws_route below.

I'm trying to scale the number of NAT gateways dynamically with the count parameter:

resource "aws_route" "my_nat_gw" {
  route_table_id         = "${var.rt_id}"
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id         = "${nat_gw_id}"

  #I have an error here - on the "lookup" term
  count = "${length(var.azs) * lookup(map(var.enable_nat_gateway, 1), "true", 0)}"
}

For the sake of brevity let's ignore the part of length(var.azs) in the count calculation.

I'm getting the following error on the lookup(map(var....) part:

Expected to be number, actual type is String more

The enable_nat_gateway variable is boolean.

I tried also the following:

lookup(map(true, 1), true, 0)}
lookup(map("true", 1), "true", 0)}

But still no good.

Any idea how to fix it?


Some calculations for those who are not familiar with the map and lookup syntax:

If the enable_nat_gateway is equal to true then 'map' is equal to{true=1} and the total lookup term should be equal to 1.

Else:

If the enable_nat_gateway is equal to false then 'map' is equal to{true=0} and the total lookup term should be equal to 0.


Notice that I'm using Terraform 0.11.11 so the map function is still supported.

Upvotes: 1

Views: 829

Answers (1)

ydaetskcoR
ydaetskcoR

Reputation: 56839

If you're trying to conditionally add n route resources then you should be using a ternary statement here with something like:

resource "aws_route" "my_nat_gw" {
  count = "${var.enable_nat_gateway ? length(var.azs) : 0}"

  route_table_id         = "${var.rt_id}"
  destination_cidr_block = "0.0.0.0/0"
  nat_gateway_id         = "${var.nat_gw_id}"
}

This checks if the enable_nat_gateway variable evaluates to true and if so creates a resource for each element in the azs variable. If it's not true then it won't create any resources.

Upvotes: 1

Related Questions