我正在撰寫 Terraform 來部署一個 S3 存盤桶和一個 lambda。需要 S3 存盤桶,因為這是存盤 zip 物件以準備部署到 lambda 的位置。
我的頂級 main.tf 中有兩個模塊:
module "s3" {
count = var.enable_s3 ? 1 : 0
source = "./modules/s3"
}
module "lambdas" {
count = var.enable_lambdas ? 1 : 0
source = "./modules/lambdas"
bucket_id = module.s3.lambda_bucket_id
}
s3 模塊:
主檔案
resource "aws_s3_bucket" "lambda_bucket" {
bucket = "lunchboxd-lambdas"
tags = {
Owner = "Terraform",
Description = "A bucket to hold the lambdas zip"
}
}
輸出.tf
output "lambda_bucket_id" {
value = aws_s3_bucket.lambda_bucket.id
description = "ID of the bucket holding the lambda functions."
}
lambda 模塊:
變數.tf
variable "bucket_id" {}
主檔案
data "archive_file" "lambda_hello_world" {
type = "zip"
source_dir = "${path.module}/hello-world"
output_path = "${path.module}/hello-world.zip"
}
resource "aws_s3_object" "lambda_hello_world" {
bucket = var.bucket_id
key = "hello-world.zip"
source = data.archive_file.lambda_hello_world.output_path
etag = filemd5(data.archive_file.lambda_hello_world.output_path)
}
resource "aws_lambda_function" "hello_world" {
function_name = "HelloWorld"
s3_bucket = var.bucket_id
s3_key = aws_s3_object.lambda_hello_world.key
runtime = "nodejs12.x"
handler = "hello.handler"
source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256
role = aws_iam_role.lambda_exec.arn
}
resource "aws_cloudwatch_log_group" "hello_world" {
name = "/aws/lambda/${aws_lambda_function.hello_world.function_name}"
retention_in_days = 30
}
resource "aws_iam_role" "lambda_exec" {
name = "serverless_lambda"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Sid = ""
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
resource "aws_iam_role_policy_attachment" "lambda_policy" {
role = aws_iam_role.lambda_exec.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
當我嘗試驗證我的 terraform 時,我收到以下錯誤:
?
│ Error: Unsupported attribute
│
│ on main.tf line 36, in module "lambdas":
│ 36: bucket_id = module.s3.aws_s3_bucket.lambda_bucket.id
│ ├────────────────
│ │ module.s3 is a list of object, known only after apply
│
│ Can't access attributes on a list of objects. Did you mean to access an attribute for a specific element of the list, or across all elements of the list?
?
我遵循了關于輸出和模塊組合的檔案,但我不確定我做錯了什么。所有幫助表示贊賞。
uj5u.com熱心網友回復:
您的塊module "s3"具有元引數,因此參考實體下的檔案適用于此處。count
具體來說,module.s3是一個物件串列,而不僅僅是一個物件(如錯誤訊息中所暗示的那樣),因此當您參考它時,您需要指定要參考該串列的哪些元素。
在您的情況下,您只有零個或一個模塊實體,因此module.s3將是零個或一個元素的串列。module.s3因此,您需要向Terraform解釋如果module.lambdas.
如果在沒有存盤桶時bucket_id變數 in為 null 是可以接受的,那么撰寫它的一種方法是使用該函式將串列轉換為單個值(如果它有一個元素或如果它沒有元素):module "lambdas"onenull
bucket_id = one(module.s3.aws_s3_bucket[*].lambda_bucket.id)
此運算式首先使用splat 運算子[*]將物件串列轉換為僅包含id值的串列,然后用于one轉換為單個字串或 null。
如果bucket_id在沒有實體的情況下需要其他值,module.s3則需要在此處指定一些其他邏輯來描述在這種情況下如何填充此變數。具體做什么取決于您需要的翻譯規則;您可以使用任何 Terraform 語言運算式或函式在此處做出動態決策。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/456603.html
