Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform variables and count = 0

Tags:

terraform

We use the same terraform definitions across all environments. So far that worked well, but now I face a problem I couldn't solve yet. I have a RDS and ElastiCache for a service that I don't need in the demo env that I'm setting up right now, so I set the count to 0. For the other environments, I need to expose them via an output var:

resource "aws_elasticache_cluster" "cc_redis" {
  cluster_id = "cc-${var.env}"
  engine = "redis"
  node_type = "cache.t2.small"
  security_group_ids = ["..."]
  count = "${var.env == "demo" ? 0 : 1}"
}

output "cc_redis_host" {
  value = "${aws_elasticache_cluster.cc_redis.cache_nodes.0.address}"
}

Now I'm getting this error:

output.cc_redis_host: Resource 'aws_elasticache_cluster.cc_redis' not found
for variable 'aws_elasticache_cluster.cc_redis.cache_nodes.0.address'

I don't mind (much) having a useless variable set, but I can't get it to work in the first place. A simple conditional doesn't resolve this, since terraform evaluates the false side of conditionals even though it's not used. I found this hack but couldn't get it to work either.

like image 232
iGEL Avatar asked Aug 02 '18 13:08

iGEL


1 Answers

Try this:

output "cc_redis" {
  value = "${element(concat(aws_elasticache_cluster.cc_redis.*.cache_nodes.0.address, list("")), 0)}"
}

TF doesn't seem to care that the count may be 0 if you wildcard higher up the chain.

This may output more than you want, but you can parse out what you need from it.

like image 140
KJH Avatar answered Sep 28 '22 02:09

KJH