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

Terraform配置GCP IAM动态时间条件角色绑定报错求助

问题:Terraform配置GCP IAM时间条件编译失败

问题场景

使用Terraform为GCP项目的自定义IAM角色添加用户,并配置30天后过期的访问条件。通过local.expiry变量(由timeadd(timestamp(), "720h")生成30天后的时间戳)动态设置条件表达式时,出现IAM策略条件表达式编译失败的错误,但硬编码时间戳可正常运行。

错误代码片段

IAM绑定配置

resource "google_project_iam_binding" "cwx_readonly_users" {
  for_each = toset(local.grantees)
  project  = "<project_id>"
  role     = google_project_iam_custom_role.my-custom-role.id
  members = [
    "user:${each.value}"
  ]
  condition {
    title       = "expires_after_30days"
    description = "Expires in 30 days from now"
    # 硬编码可正常运行
    # expression  = "request.time < timestamp('2023-04-12T00:00:00.00Z')"
    expression  = "request.time < timestamp(${local.expiry})"
  }
}

Local变量定义

locals {
  expiry = timeadd(timestamp(), "720h")
}

错误信息

Error: Request `Set IAM Binding for role "projects/xxxx/roles/xxx" on "project \"xxxxl\""` returned error: Batch request and retried single request "Set IAM Binding for role \"projects/xxx/roles/xxxx\" on \"project \\\"xxx\\\"\"" both failed. Final error: Error applying IAM policy for project "xxx": Error setting IAM policy for project "xxx": googleapi: Error 400: Condition expression compilation failed. Debug message: ERROR : ERROR: <expression>:1:36: mismatched input 'T16' expecting {'==', '!=', 'in', '<', '<=', '>=', '>', '&&', '||', '[', ')', '.', ',', '-', '?', '+', '*', '/', '%%'}
│  | request.time < timestamp(2023-09-03T16:05:22Z)
│  | ...................................^ , badRequest
│ 
│   with google_project_iam_binding.cwx_readonly_users["xxxx"],
│   on main.tf line 37, in resource "google_project_iam_binding" "cwx_readonly_users":
│ 37: resource "google_project_iam_binding" "cwx_readonly_users" {

问题原因

GCP IAM条件表达式中,timestamp()函数的参数必须是带单引号的字符串格式时间戳。当前代码插值后生成的表达式是timestamp(2023-09-03T16:05:22Z),缺少单引号,导致语法解析失败。

解决方案

修改condition块中的expression,将local.expiry用单引号包裹,确保插值后生成符合要求的语法:

condition {
  title       = "expires_after_30days"
  description = "Expires in 30 days from now"
  expression  = "request.time < timestamp('${local.expiry}')"
}

修改后,Terraform插值后的表达式会变成request.time < timestamp('2023-09-03T16:05:22Z'),符合GCP IAM条件表达式的语法规范,即可正常编译运行。


内容的提问来源于stack exchange,提问作者Python Beginner

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 03:47:10