问题
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