CloudFormation and PowerShell: Template format error: unsupported structure with

CloudFormation and PowerShell: Template format error: unsupported structure with

在使用 PowerShell 时,我无法获取任何 CloudFormation 模板来部署或验证,但使用确切的模板时,我可以使用 AWS CLI 或使用 AWS 控制台进行操作。

让我们使用一个基本的 CloudFormation 模板,我们将其命名为 Test.template

{
  "AWSTemplateFormatVersion" : "2010-09-09",
  "Description" : "Simple template.",
  "Parameters" : {    
    "KeyName" : {
      "Type" : "String", 
      "Description" : "Name of an existing EC2 KeyPair to enable SSH access to the web server"
    }
  }, 

  "Resources" : {
    "Ec2Instance" : {
      "Type" : "AWS::EC2::Instance", 
      "Properties" : {        
        "KeyName" : "test",        
      }
    }
  }
}

没什么特别的,很基础。忽略创建 EC2 资源时会失败的情况,这是格式正确的 JSON CloudFormation 模板。

现在,如果我使用 AWS CLI 运行 此命令,它会成功返回并输出参数:

aws cloudformation validate-template --template-body file://c:/temp/Test.template

使用完全相同的文件,如果我在 PowerShell 中 运行 出现此错误:

Test-CFNTemplate -TemplateBody file://c:/temp/Test.template

Test-CFNTemplate : Template format error: unsupported structure. At line:1 char:1 + Test-CFNTemplate -TemplateBody file://c:/temp/Test.template + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (Amazon.PowerShe...NTemplateCmdlet:TestCFNTemplateCmdlet) [Test-CFNTemplate], InvalidOperationException + FullyQualifiedErrorId : Amazon.CloudFormation.AmazonCloudFormationException,Amazon.PowerShell.Cmdlets.CFN.TestCFNTemplateCmdlet

我在使用 AWS 控制台或使用 aws cloudformation create-stack 部署此模板时也没有任何问题,我只是想不通为什么我不能使用 PowerShell 来完成此操作。

New-CFNStack 也返回上面相同的错误:

Template format error: unsupported structure.

我安装了最新版本的 AWS PowerShell 模块,我正在 运行ning Powershell 5.1.14409.1012

我发现的关于此错误的所有其他信息都来自那些有问题的人,因为他们没有在 TemplateBody 中使用 file://,但这里似乎并非如此。

显然 -TemplateBody 不支持本地文件 URI。您首先需要将模板读入一个变量,然后像下面这样使用它。

$content = [IO.File]::ReadAllText("c:\test.template")
Test-CFNTemplate -TemplateBody $content

完成之后,它现在会为您提供预期的输出。

Test-CFNTemplate -TemplateBody $content

Capabilities       : {}
CapabilitiesReason : 
DeclaredTransforms : {}
Description        : Simple template.
Parameters         : {KeyName}

可惜-TemplateBody不支持本地文件URI。幸运的是,您仍然可以指定内联文件。

Test-CFNTemplate -TemplateBody (get-content c:\test.template -Raw)

命令应该return预期的结果。

Test-CFNTemplate -TemplateBody (get-content c:\test.template -Raw)

Capabilities       : {}
CapabilitiesReason : 
DeclaredTransforms : {}
Description        : Simple template.
Parameters         : {KeyName}

我不能说这是我的解决方案,因为我是从这个博客上读到的:https://matthewdavis111.com/aws/test-cloudformation-powershell/