【问题标题】:How to use AWS account_id variable in Terraform如何在 Terraform 中使用 AWS account_id 变量
【发布时间】:2021-09-24 14:34:25
【问题描述】:

我想在 terraform 中访问我的 AWS 账户 ID。我可以通过aws_caller_identitythe documentation 来解决它。然后如何使用我创建的变量?在以下情况下,我尝试在 S3 存储桶名称中使用它:

data "aws_caller_identity" "current" {}
output "account_id" {
  value = data.aws_caller_identity.current.account_id
}

resource "aws_s3_bucket" "test-bucket" {
  bucket = "test-bucket-${account_id}"
}

尝试以这种方式使用account_id 变量会给我错误A reference to a resource type must be followed by at least one attribute access, specifying the resource name. 我希望我没有正确调用它?

【问题讨论】:

  • "test-bucket-${account_id}" 应该是 "test-bucket-${data.aws_caller_identity.current.account_id}" - 或者定义一个具有相同值的 locals
  • 我希望有办法不必一遍又一遍地重复ata.aws_caller_identity.current.account_id。知道如何定义分配给 account_id 的本地人吗?

标签: amazon-web-services amazon-s3 terraform


【解决方案1】:

如果你有

data "aws_caller_identity" "current" {}

那么您需要为该值定义一个local

locals {
    account_id = data.aws_caller_identity.current.account_id
}

然后像这样使用它

output "account_id" {
  value = local.account_id
}

resource "aws_s3_bucket" "test-bucket" {
  bucket = "test-bucket-${local.account_id}"
}

Terraform 根据它们的依赖关系解析locals,因此您可以创建依赖于其他localsresourcesdata 块等的locals

【讨论】:

    【解决方案2】:

    每当您在 terraform 中创建数据源时,它都会导出与该数据源相关的一些属性,以便您可以在配置中的其他位置引用它并以各种方式对其进行插值。

    在您的情况下,您已经在 output 块中引用了您的帐户 ID 的值

    同样的方式,你可以构造桶名的字符串,如下所示。

    resource "aws_s3_bucket" "test-bucket" {
      bucket = "test-bucket-${data.aws_caller_identity.current.account_id}"
    }
    

    我强烈建议您阅读 terraform 语法,它可以帮助您更好地理解资源、数据源和表达式

    https://www.terraform.io/docs/language/expressions/references.html

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2021-07-06
      • 2023-02-22
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 2020-10-22
      相关资源
      最近更新 更多