Terraform变量化AWS Lambda Layer代码报错求助:Invalid resource name与Invalid string literal问题排查
Hey there! I see you're just getting started with Terraform and ran into a common gotcha with resource naming. Let's break down what's going wrong and fix it quickly.
Why You're Getting These Errors
The two errors you're seeing boil down to one key Terraform rule: the internal resource name (the string right after the resource type) must be a static, fixed identifier—you can’t use variable interpolation like ${var.project} here.
- The first error flags the resource name as invalid because it starts with
${instead of a letter or underscore, violating Terraform's naming rules. - The second error clarifies that template sequences (like variable interpolations) aren’t allowed in this specific spot.
This internal name is only for Terraform to track the resource in its state file—it’s not the actual name that appears in AWS. The layer_name parameter is where you set the AWS-facing name, and that does support variable interpolation!
Corrected Code
Your variables.tf is totally fine as-is:
variable "project" { default = "test" }
Update your Lambda Layer resource in lambda-function.tf to this:
resource "aws_lambda_layer_version" "project_lambda_layer" { filename = "python_modules.zip" layer_name = "${var.project}_lambda_layer" compatible_runtimes = ["python3.8"] }
What Changed?
- I replaced the interpolated resource name
${var.project}_lambda_layerwith a static, valid name:project_lambda_layer(follows Terraform's rules: starts with a letter, uses underscores). - Kept the
layer_namefield using${var.project}_lambda_layer—this is exactly where you want to use the variable, since this sets the name that will appear in your AWS account.
Now if you run terraform plan again, those errors should disappear, and your Lambda Layer will be created with the name test_lambda_layer (or whatever value you set for the project variable) in AWS.
内容的提问来源于stack exchange,提问作者Nin

