问题
I have the following configuration:
variable "private_subnets" {
default = ["subnet-A", "subnet-B"]
}
resource "random_shuffle" "az" {
input = ["${var.private_subnets}"]
result_count = 1
}
module "server" {
source = "./modules/aws-ec2"
instance_count = 3
name = "${var.env}-server"
stack = "server"
role = "server"
ami = "${lookup(var.aws_amis, var.aws_region, "")}"
instance_type = "t2.micro"
subnet_id = "${random_shuffle.az.result[0]}"
vpc_security_group_ids = ["${var.security_groups}"]
}
I was expecting Terraform would selected a random subnet_id
for every instance but it's always selecting the first item in the list which is subnet-A. What is the best/suggested way of randomly selecting an item off a list based on the number of instances to be created?
Thanks in advance!
回答1:
random_shuffle
like most Terraform resources accepts the count
parameter so if you do this like this:
resource "random_shuffle" "az" {
input = ["${var.private_subnets}"]
result_count = 1
count = 3
}
It will give you 3 arrays with 1 subnet each. Accessing it will depend on how exactly you create the instances inside your module but most you're using count on aws_instance resource
so it will be something like:
resource "aws_instance" "foo" {
count = 3
subnet_id = ${element(random_shuffle.az, count.index)}
}
来源:https://stackoverflow.com/questions/49271475/weird-behavior-of-terraforms-random-shuffle-provider