Terraform中如何对拼接字符串执行子串截取操作?
Hey there! That parse error you're hitting comes from incorrectly nesting Terraform's interpolation syntax (${}) inside the substr function arguments. Let's work through the fix step by step.
Why Your Original Code Failed
Your initial attempt had nested ${} calls inside the substr parameters, which Terraform doesn't allow—once you're inside an interpolation block (${}), you don't need to wrap variables or expressions in another set of ${}. Here's the problematic line for reference:
# ❌ Wrong syntax - nested interpolation is unnecessary here "${substr(${var.owner}-${var.role}-specific- 0, min(length(var.name_prefix_full), 32))}"
Correct Approach 1: Inline Truncation
You can fix this by properly passing the full concatenated prefix as the first argument to substr, then using min to cap the length at 32 characters:
resource "aws_iam_role_policy" "role" { name_prefix = "${substr("${var.owner}-${var.role}-specific-", 0, min(length("${var.owner}-${var.role}-specific-"), 32))}" # ... add your other resource attributes here }
This works, but repeating the full prefix string twice makes the code a bit messy.
Correct Approach 2: Use a Local Variable (Recommended)
For cleaner, more maintainable code, define the full prefix and its truncated version in a locals block first. This lets you reuse the truncated value anywhere you need it:
locals { # Build the complete untruncated prefix name_prefix_full = "${var.owner}-${var.role}-specific-" # Truncate to 32 chars if the full prefix is too long; use the full length otherwise truncated_name_prefix = substr(local.name_prefix_full, 0, min(length(local.name_prefix_full), 32)) } resource "aws_iam_role_policy" "role" { name_prefix = local.truncated_name_prefix # ... add your other resource attributes here }
How It All Works
length(local.name_prefix_full)calculates the total length of your concatenated prefix.min(..., 32)ensures we never try to extract more than 32 characters, even if the full prefix is shorter.substr(..., 0, ...)grabs the substring starting at index 0 (the start of the string) up to the capped length.
内容的提问来源于stack exchange,提问作者Adam Matan

