Terraform: How to append the server count and assign servers to multiple AZ's?

流过昼夜 提交于 2019-12-23 22:12:23

问题


main.tf

resource "aws_instance" "service" {
  ami           = "${lookup(var.aws_winamis, var.awsregion)}"
  count         = "${var.count}"
  key_name      = "${var.key_name}"
  instance_type = "t2.medium"
  subnet_id     = "${aws_subnet.private.id}"
  # private_ip    = "${lookup(var.server_instance_ips, count.index)}"
  vpc_security_group_ids = ["${aws_security_group.private-sg.id}"]
  associate_public_ip_address = false
  availability_zone           = "${var.awsregion}a"
  tags {
    Name        = "${format("server-%01d", count.index + 1)}"
    Environment = "${var.environment}"
  }
}

Variable.tf

variable "awsregion" {default =""}
variable "count" {default = ""}
variable "server_instance_ips" {default = ""}

dev.tfvars

server_instance_ips = ["10.0.2.25", "10.0.2.26"] #doesn't work as a list but works with single IP address
count = "4"
awsregion = "us-east-1"

I want the servers to have tags - dla-server-1/2/3/4 after they're created but with my above code I can only do server-1/2/3/4 but not dla/sla/pla depending on the environments; IP addresses are randomly assigned to the servers as I'm not able to pass the list of IP's and lastly, how can I create servers in different AZ's i.e. 2 servers in AZ1a and 2 servers in AZ1b?


回答1:


The first answer is easy: add the prefix in the tag name.

tags {
  Name        = "${var.environment}-${format("server-%01d", count.index + 1)}"
  Environment = "${var.environment}"
}

You need to specify the type of the variable to be a list:

variable "server_instance_ips"
{
  type = "list"
  default = []
}

The last question can be solved in many ways, I would go for something similar

availability_zone = "${data.aws_availability_zones.available.names[count.index]}"


来源:https://stackoverflow.com/questions/51156262/terraform-how-to-append-the-server-count-and-assign-servers-to-multiple-azs

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