Reputation: 17392
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.
Upvotes: 9
Views: 16040
Reputation: 581
You can put something like below:
output "cc_redis" {
value = var.env == "demo" : null ? aws_elasticache_cluster.cc_redis.cache_nodes.0.address
}
Output also accept null, and if its null, it will ignore it at the time of execution.
Upvotes: 0
Reputation: 41
For the people that are coming from google to this thread this is the terraform newer version of handling this: tolist method with the square brackets is the new approach.
value = "${element(concat(aws_elasticache_cluster.cc_redis.cache_nodes.*. address, tolist([""])), 0)}"
Upvotes: 0
Reputation: 2430
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.
Upvotes: 8
Reputation: 2175
Change your output to the following:
output "cc_redis_host" {
value = "${element(concat(aws_elasticache_cluster.cc_redis.cache_nodes.*. address, list("")), 0)}"
}
It is documented somewhere on the terraform website.
Upvotes: 0