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

CloudFormation Windows UserData中cfn-init.exe换行参数错误求助

解决cfn-init参数换行导致的PowerShell执行错误

从你提供的报错信息能直接定位核心问题:cfn-init.exe的命令参数被拆分成了多行,PowerShell把每个参数(比如-r)当成独立命令执行,这才会抛出"not recognized as a cmdlet/function"的错误。

问题根源

你的UserData使用Fn::Join时,错误地把cfn-init.exe -v -s、{Ref: AWS::StackName}、-r EC2Instance拆成了Fn::Join的不同元素,用换行符\n连接后,最终生成的PowerShell脚本会变成这样:

cfn-init.exe -v -s
YourStackName
-r EC2Instance

PowerShell逐行执行时,会把YourStackName和-r EC2Instance当成独立命令,自然会报错。

修复方案

需要做两个关键调整:

1. 确保cfn-init命令在同一行

把整个cfn-init命令作为Fn::Join的单个元素,避免参数被换行拆分。

2. 修正Metadata的位置

AWS::CloudFormation::Init和AWS::CloudFormation::Authentication是EC2资源的顶层Metadata属性,不能嵌套在UserData里,需要和UserData并列。

修正后的完整代码示例

Resources:
  EC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      UserData:
        Fn::Base64:
          Fn::Join:
            - "\n"
            - - "<powershell>"
              - "cfn-init.exe -v -s ", {Ref: "AWS::StackName"}, " -r EC2Instance"
              - "</powershell>"
      # Metadata放在这里,和UserData同级
      Metadata:
        AWS::CloudFormation::Init:
          config:
            files:
              "C:\\chef\\validator.pem":
                source: "https://s3.amazonaws.com/dtcfstorage/validator.pem"
                authentication: "s3creds"
        AWS::CloudFormation::Authentication:
          s3creds:
            type: "S3"
            roleName: "awss3chefkeyaccess"

额外检查点

  • 确认你的EC2实例已经关联了awss3chefkeyaccess角色,且该角色有访问目标S3桶的权限。
  • 检查实例中C:\Windows\TEMP\UserScript.ps1文件,确保cfn-init命令是完整的一行,没有多余换行或无效内容(比如报错里的cloudinittest,大概率是UserData里不小心混入的冗余字符,需要清理)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:28:58