简体   繁体   English

如何在 Terraform 中为 AWS EC2 应用不同的 TAG

[英]How to apply different TAGs for AWS EC2 in Terraform

I have applied the code for tagging AWS ec2 instances in Terraform, when the code runs it only created singe TAG.我在 Terraform 中应用了标记 AWS ec2 实例的代码,当代码运行时它只创建了单个 TAG。 How can we add multiple TAGs eg我们如何添加多个标签,例如

  1. It add Auto creation DATE.它添加自动创建日期。
  2. It add Auto OS detection (like it is windows or linux)它添加自动操作系统检测(比如它是 windows 或 linux)

Please see TAG detail in Screenshot请在截图中查看 TAG 详细信息

Gurus, your kind support will be highly appreciated.大师们,您的支持将不胜感激。

I have added the following code for Tagging.我为标记添加了以下代码。

# Block for create EC2 Instance
resource "aws_instance" "ec2" {
  count                  = var.instance_count
  ami                    = "ami-005835d578c62050d"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [var.security_group_id]
  subnet_id              = var.subnet_id
  key_name               = var.key
  **tags = {
    Name = "${var.name}-${count.index + 1}"**
  }
}

You can add other tags by simply adding to your Tags , For example:您可以通过简单地添加到您的标签来添加其他Tags ,例如:

  tags = {
    Name = "${var.name}-${count.index + 1}"
    CreationDate = timestamp()
    OS           = "Linux"
  }

tags attribute accepts a map of strings and you can also use terraform functions like merge to merge default tags if available in your used case with custom resource-specific tags. tags属性接受 map 个字符串,您还可以使用 terraform 函数(如merge )合并默认标签(如果在您的用例中可用)和自定义资源特定标签。

# Block for create EC2 Instance
resource "aws_instance" "ec2" {
  count                  = var.instance_count
  ami                    = "ami-005835d578c62050d"
  instance_type          = "t2.micro"
  vpc_security_group_ids = [var.security_group_id]
  subnet_id              = var.subnet_id
  key_name               = var.key
  tags = merge(var.default_ec2_tags,
    {
      Name = "${var.name}-${count.index + 1}"
    }
  )
}

variable "default_ec2_tags" {
  type = map(string)
  description = "(optional) default tags for ec2 instances"
  default = {
    managed_by = "terraform"
    environment = "dev"
  }
}

Something very specific to terraform-aws-provider and a very handy feature is default_tags which you can configure on the provider level and these tags will be applied to all resources managed by the provider. default_tagsterraform-aws-provider特有的一个非常方便的功能,您可以在提供商级别配置它,这些标签将应用于提供商管理的所有资源。

Click to view Tutorial from hashicorp on default-tags-in-the-terraform-aws-provider单击以查看来自 hashicorp 的关于 default-tags-in-the-terraform-aws-provider 的教程

It's not possible to get the OS type tag natively as mentioned by @Marcin already in the comments.不可能像@Marcin 已经在评论中提到的那样本地获取操作系统类型标签。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM