我正在使用Terraform 0.12。我正在尝试为项目批量构建EC2,而不是顺序命名ec2,而是通过提供唯一的名称来命名实例。
我想到了使用动态标签,但是不确定如何将其合并到代码中。
resource "aws_instance" "tf_server" {
count = var.instance_count
instance_type = var.instance_type
ami = data.aws_ami.server_ami.id
associate_public_ip_address = var.associate_public_ip_address
##This provides sequential name.
tags = {
Name = "tf_server-${count.index +1}"
}
key_name = "${aws_key_pair.tf_auth.id}"
vpc_security_group_ids = ["${var.security_group}"]
subnet_id = "${element(var.subnets, count.index)}"
}
答案 0 :(得分:0)
以下内容与您追求的内容类似吗?
将名称前缀列表定义为变量,然后使用element函数循环浏览命名前缀。
variable "name_prefixes" {
default = ["App", "Db", "Web"]
}
...
##This provides sequential name.
tags = {
Name = "${element(var.name_prefixes, count.index)}${count.index + 1}"
}
...
结果将是App1,Db2,Web3,App4,Db5 ...编号不理想,但至少每个实例具有不同的名称。
我想顺序命名它们的唯一方法(例如App1,App2,Db1,Db2等)将需要每种类型实例的单独资源,然后仅在名称上使用count.index即可,例如原始代码。
答案 1 :(得分:0)
如果我正确理解您的要求,则可以将VM名称列表作为terraform变量传递,并使用count.index根据计数从列表中的特定位置获取名称。
# variables.tf
# Length of list should be the same as the count of instances being created
variable "instance_names" {
default = ["apple", "banana", "carrot"]
}
#main.tf
resource "aws_instance" "tf_server" {
count = var.instance_count
instance_type = var.instance_type
ami = data.aws_ami.server_ami.id
associate_public_ip_address = var.associate_public_ip_address
##This provides names as per requirement from the list.
tags = {
Name = "${element(var.instance_names, count.index)}"
}
key_name = "${aws_key_pair.tf_auth.id}"
vpc_security_group_ids = ["${var.security_group}"]
subnet_id = "${element(var.subnets, count.index)}"
}