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

Terraform配置AWS SNS Topic Policy报错及变量插值问题求助

Terraform SNS Topic Policy 错误修复与变量插值方法

错误原因

执行terraform plan时出现的Expected the start of an expression, but found an invalid expression token和Argument or block definition required错误,是因为在policy的JSON字符串中直接写入了Terraform变量/资源属性引用(如aws_sns_topic.topic_name.arn、local.account_id),但未使用Terraform的插值语法,导致Terraform无法解析这些内容,将其判定为无效表达式。

Heredoc中变量插值的正确方法

在Terraform的Heredoc字符串中引用变量、资源属性或本地值,必须使用${变量/属性路径}的插值语法,Terraform会在生成最终字符串时自动替换对应的值。同时要保证JSON格式的正确性,插值内容需放在JSON的双引号内部。

修改后的完整代码

resource "aws_sns_topic_policy" "default" {
  arn    = aws_sns_topic.topic_name.arn
  policy = <<EOF
{
  "Version": "2008-10-17",
  "Id": "__default_policy_ID",
  "Statement": [
    {
      "Sid": "__default_statement_ID",
      "Effect": "Allow",
      "Principal": {
        "AWS": "*"
      },
      "Action": [
        "SNS:GetTopicAttributes",
        "SNS:SetTopicAttributes",
        "SNS:AddPermission",
        "SNS:RemovePermission",
        "SNS:DeleteTopic",
        "SNS:Subscribe",
        "SNS:ListSubscriptionsByTopic",
        "SNS:Publish"
      ],
      "Resource": "${aws_sns_topic.topic_name.arn}",
      "Condition": {
        "StringEquals": {
          "AWS:SourceOwner": "${local.account_id}"
        }
      }
    },
    {
      "Sid": "AWSEvents_Datasync",
      "Effect": "Allow",
      "Principal": {
        "Service": "events.amazonaws.com"
      },
      "Action": "sns:Publish",
      "Resource": "${aws_sns_topic.topic_name.arn}"
    }
  ]
}
EOF
}

更推荐的方案:使用jsonencode生成Policy

手动编写JSON字符串容易出现格式错误,推荐使用Terraform的jsonencode函数自动生成符合格式要求的JSON policy,无需手动处理引号和插值符号,直接引用变量即可:

resource "aws_sns_topic_policy" "default" {
  arn    = aws_sns_topic.topic_name.arn
  policy = jsonencode({
    Version = "2008-10-17"
    Id      = "__default_policy_ID"
    Statement = [
      {
        Sid       = "__default_statement_ID"
        Effect    = "Allow"
        Principal = {
          AWS = "*"
        }
        Action = [
          "SNS:GetTopicAttributes",
          "SNS:SetTopicAttributes",
          "SNS:AddPermission",
          "SNS:RemovePermission",
          "SNS:DeleteTopic",
          "SNS:Subscribe",
          "SNS:ListSubscriptionsByTopic",
          "SNS:Publish"
        ]
        Resource = aws_sns_topic.topic_name.arn
        Condition = {
          StringEquals = {
            "AWS:SourceOwner" = local.account_id
          }
        }
      },
      {
        Sid       = "AWSEvents_Datasync"
        Effect    = "Allow"
        Principal = {
          Service = "events.amazonaws.com"
        }
        Action   = "sns:Publish"
        Resource = aws_sns_topic.topic_name.arn
      }
    ]
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 07:25:00