模板主体包含无效JSON:无效字符



我有一个CloudFormation模板,创建一个SNS主题和订阅

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources" : {
      "EmailSNSTopic": {
        "Type" : "AWS::SNS::Topic",
        "Properties" : {
          "DisplayName" : "${display_name}"
        }
      },
      "MySubscription": {
        "Type": "AWS::SNS::Subscription",
        "Properties": {
          "TopicArn" : { "Ref" : "EmailSNSTopic" },
          "${details}"
        }
      }
    },
      "Outputs" : {
        "ARN" : {
          "Description" : "Email SNS Topic ARN",
          "Value" : { "Ref" : "EmailSNSTopic" }
        }
      }
}

我正试图通过平台呼叫。

但是我一直得到这个错误Error: "template_body" contains an invalid JSON: invalid character '{' looking for beginning of object key string

我的Terraform配置是这样的。

provider "aws" {
  region = "eu-west-2"
}
data "template_file" "sns_stack" {
  template = file("${path.module}/templates/email-sns-stack.json.tpl")
  vars = {
    display_name  = var.display_name
    details = join(",", formatlist("{ "Endpoint": "%s", "Protocol": "%s"  }", var.email_list, var.protocol))
  }
}
resource "aws_cloudformation_stack" "sns_topic" {
  name          = var.stack_name
  template_body = data.template_file.sns_stack.rendered
  tags = merge(
    map("Name", var.stack_name)
  )
}

我的variables.tf是这样的

  default     = "Admin"
}
variable "email_list" {
  default = [
    "foo@foo.com",
    "bar@bar.com"
  ]
}
variable "protocol" {
  default     = "email"
}
variable "stack_name" {
  default     = "sns-test"
}

我希望${details}应该吐出我的端点和协议,但它没有。

我做错了什么?

您想要实现的目标相当复杂,但却是可行的。你可以使用下面的模板:

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources" :  ${jsonencode(
        merge({for idx, email_address in email_list: 
        "EmailSubs${idx}" => {
          Type = "AWS::SNS::Subscription"
          Properties = {
                "Endpoint" = email_address
                "Protocol" = protocol
                "TopicArn" = { "Ref" = "EmailSNSTopic" }      
          }      
      }},
      {
        "EmailSNSTopic" = {
        "Type" = "AWS::SNS::Topic",
        "Properties" = {
          "DisplayName" = "${display_name}"
        }
      }}
      
      ))},
  "Outputs" : {
        "ARN" : {
          "Description" : "Email SNS Topic ARN",
          "Value" : { "Ref" : "EmailSNSTopic" }
        }
      }      
        
}

和TF代码:

locals {
  template_body = templatefile("./email-sns-stack2.json.tpl", {
    display_name  = var.display_name
    email_list = var.email_list
    protocol = var.protocol
   })
}
resource "aws_cloudformation_stack" "sns_topic" {
  name          = var.stack_name
  template_body = local.template_body
  tags = merge(
    map("Name", var.stack_name)
  )
}

最新更新