9625

<h3>Question</h3>
We have a bunch of instances (I know... cattle, not pets, but in this case, these are really pets)
resource "aws_instance" "read_00" {
count = "${var.read_00_count}"
resource "aws_instance" "read_01" {
count = "${var.read_01_count}"
And we have an ELB where we want to dynamically add the instances based on their count variable, like so:
resource "aws_elb" "read_slaves" {
instances = ["${aws_instance.read_.*.id}"]
But that doesn't work, of course.
Is it possible to dynamically create a list of instance ids ONLY if their count is not zero?
I know this goes against the grain, but if this is possible, that would be awesome.
<h3>Answer1:</h3>
With Terraform 0.12 that will be much easier, but for now something like this would do:
[...]
resource "aws_instance" "read_01" {
[...]
count = "${var.read_01_count}"
tags {
Role = "read_slave"
}
}
data "aws_instances" "read-slaves" {
instance_tags {
Role = "read_slave"
}
// optional filters
}
resource "aws_elb" "read_slaves" {
instances = ["${data.aws_instances.read-slaves.ids}"]
listener {
...
}
}
Thus:
<ul><li>tagging each instance which acts as a read slave</li> <li>collect the list ofaws_intances
</li>
<li>create the aws_elb
based on the collected data</li>
</ul>来源:https://stackoverflow.com/questions/53280855/terraform-create-list-based-on-resource-count