Terraform 如何为EC2实例分配唯一的“Name”标记?
我正在使用Terraform 0.12。我试图为一个项目批量构建EC2,而不是顺序命名EC2,我将通过提供唯一的名称来命名实例 但是,我想使用动态标记,但不太确定如何将其合并到代码中Terraform 如何为EC2实例分配唯一的“Name”标记?,terraform,terraform-provider-aws,Terraform,Terraform Provider Aws,我正在使用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
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)}"
}
以下内容是否与您所追求的内容类似 将名称前缀列表定义为变量,然后使用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。如果我正确理解您的要求,您可以将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"]
}
如果你不想增加数字后缀,你想给他们什么样的名字?可以是服务器a、服务器b、服务器c。一旦选项是创建多个资源记录并给出名称,但我试图避免。为什么不希望它只是一个数字呢?似乎您在这里没有明确的要求,那么为什么要把它复杂化呢?要求是我们需要基于服务器功能的唯一名称,而不是顺序名称感谢@tedsmitt,我想我可能必须按照客户机的要求创建每个资源和标记。没问题,对不起,不能提供更多帮助!
#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)}"
}