Weird behavior of Terraform's random_shuffle provider

耗尽温柔 提交于 2020-03-23 23:57:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!