Terraform如何在资源块内部作为变量访问资源的本地名称

huangapple go评论52阅读模式
英文:

Terraform how to access resource local name as a variable inside the resource block itself

问题

resource "aws_subnet" "goodsubnet" {
vpc_id = "VPCID"
cidr_block = "x.x.x.x/x"
availability_zone = "xyz"
tags =
{
tagname1 = "$something"
}
}
我希望标签"tagname1"的值可以动态地使用资源的本地名称,即"goodsubnet"。是否有一个我可以使用的变量?

谢谢

英文:
resource "aws_subnet" "goodsubnet" {
  vpc_id     = "VPCID"
  cidr_block = "x.x.x.x/x"
  availability_zone = "xyz"
  tags = 
    {
      tagname1 = "$something"
    }
  
}

I want the tag "tagname1" to dynamically have the value of the resource local name i.e "goodsubnet" Is there a variable I can use?

Thanks

答案1

得分: 3

以下是翻译好的部分:

这不是您想要的方式。不过,Terraform 具有变量的概念,您可以使用它来为参数分配值。这可以是本地值[1]或输入变量[2]。例如,输入变量的定义:

variable "subnet_name_tag" {
  type        = string
  description = "子网的标签名称。"
}

然后,在您的代码中,您可以这样做:

resource "aws_subnet" "goodsubnet" {
  vpc_id     = "VPCID"
  cidr_block = "x.x.x.x/x"
  availability_zone = "xyz"
  tags = 
    {
      tagname1 = var.subnet_name_tag
    }
}

或者,您可以定义一个本地值:

locals {
  subnet_tag_name = "goodsubnet"
}

然后是:

resource "aws_subnet" "goodsubnet" {
  vpc_id     = "VPCID"
  cidr_block = "x.x.x.x/x"
  availability_zone = "xyz"
  tags = 
    {
      tagname1 = local.subnet_name_tag
    }
}

[1] https://developer.hashicorp.com/terraform/language/values/locals

[2] https://developer.hashicorp.com/terraform/language/values/variables

英文:

That is not possible the way you want to do it. However, Terraform has a concept of variables, which you can use to assign values to arguments. That could be either a local value [1] or an input variable [2]. For example, an input variable definition:

variable "subnet_name_tag" {
  type        = string
  description = "Tag name for a subnet."
}

Then, in your code you would do:

resource "aws_subnet" "goodsubnet" {
  vpc_id     = "VPCID"
  cidr_block = "x.x.x.x/x"
  availability_zone = "xyz"
  tags = 
    {
      tagname1 = var.subnet_name_tag
    }
}

Alternatively, you could define a local value:

locals {
  subnet_tag_name = "goodsubnet"
}

Followed by:

resource "aws_subnet" "goodsubnet" {
  vpc_id     = "VPCID"
  cidr_block = "x.x.x.x/x"
  availability_zone = "xyz"
  tags = 
    {
      tagname1 = local.subnet_name_tag
    }
}

[1] https://developer.hashicorp.com/terraform/language/values/locals

[2] https://developer.hashicorp.com/terraform/language/values/variables

huangapple
  • 本文由 发表于 2023年2月16日 16:05:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469361.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定