【问题标题】:How do I assign unique "Name" tag to the EC2 instance(s)?如何为 EC2 实例分配唯一的“名称”标签?
【发布时间】:2019-12-01 22:40:37
【问题描述】:

我使用的是 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)}"
}

【问题讨论】:

  • 如果你不想只是增加数字后缀,你想给他们起什么样的名字?
  • 可能是服务器a、服务器b、服务器c。一旦选项是创建多个资源记录并给出名称,但我试图避免。
  • 那你为什么不希望它只是一个数字呢?看来你这里没有明确的要求,何必复杂化呢?
  • 要求是我们需要基于服务器的功能与顺序名称具有唯一名称

标签: terraform terraform-provider-aws


【解决方案1】:

如果我正确理解您的要求,您可以将 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)}"
}

【讨论】:

    【解决方案2】:

    以下内容是否与您所追求的相似?

    将名称前缀列表定义为变量,然后使用元素函数在命名前缀之间循环。

    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。

    【讨论】:

    • 谢谢@tedsmitt,我想我可能不得不按照客户的要求创建每个资源和标签。
    • 没问题,很抱歉无法提供更多帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多