You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Terraform中如何对拼接字符串执行子串截取操作?

Fixing Terraform Substring Truncation for Long Name Prefixes

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.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:32:12