如何在 Terraform 中使用 AWS account_id 变量

Joh*_*ner 57 amazon-s3 amazon-web-services terraform

我想在 terraform 中访问我的 AWS 账户 ID。aws_caller_identity我可以根据文档找到它。那么我如何使用我创建的变量呢?在下面的情况下,我尝试在 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}"
}
Run Code Online (Sandbox Code Playgroud)

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

luk*_*302 97

如果你有一个

data "aws_caller_identity" "current" {}
Run Code Online (Sandbox Code Playgroud)

那么你需要local为该值定义 a :

locals {
    account_id = data.aws_caller_identity.current.account_id
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它

output "account_id" {
  value = local.account_id
}

resource "aws_s3_bucket" "test-bucket" {
  bucket = "test-bucket-${local.account_id}"
}
Run Code Online (Sandbox Code Playgroud)

Terraformlocals根据它们的依赖关系解析,以便您可以创建locals依赖于 other locals、 on resources、 ondata块等的内容。


aas*_*yas 10

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

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

同样,您可以按如下方式构造存储桶名称的字符串。

resource "aws_s3_bucket" "test-bucket" {
  bucket = "test-bucket-${data.aws_caller_identity.current.account_id}"
}
Run Code Online (Sandbox Code Playgroud)

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

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