AWS CloudFormation用户数据映射报错,请求正确配置方案
AWS CloudFormation 按AMI类型配置用户数据的正确方法
你遇到的Fn::Sub错误,本质是使用该函数时参数格式不符合要求——要么没传入字符串作为第一个参数,要么映射参数结构错误。下面直接给出能实现需求的完整模板,并说明关键细节:
完整可运行模板示例
AWSTemplateFormatVersion: "2010-09-09" Parameters: selectAMI: Type: String Description: 选择要部署的AMI类型 AllowedValues: - AmazonLinux2 - UbuntuServer Default: AmazonLinux2 Conditions: IsAmazonLinux2: !Equals [!Ref selectAMI, "AmazonLinux2"] IsUbuntuServer: !Equals [!Ref selectAMI, "UbuntuServer"] Resources: WebServerInstance: Type: AWS::EC2::Instance Properties: InstanceType: t2.micro # 替换为你所在区域的对应AMI ID,可通过AWS控制台或aws cli命令获取 ImageId: !If - IsAmazonLinux2 - ami-0c55b159cbfafe1f0 - ami-08c40ec9ead489470 UserData: !Base64 !If - IsAmazonLinux2 - | #!/bin/bash yum update -y yum install -y httpd systemctl start httpd systemctl enable httpd - | #!/bin/bash apt update -y apt install -y apache2 systemctl start apache2 systemctl enable apache2 Tags: - Key: Name Value: !Sub WebServer-${selectAMI}
关键细节说明
参数与条件定义:
- 通过
Parameters限定可选的AMI类型,避免非法输入 - 用
Conditions创建两个判断条件,分别对应两种操作系统
- 通过
用户数据核心逻辑:
- 用
Fn::If根据条件返回对应系统的脚本,无需嵌套错误的Fn::Sub结构 - 必须用
Fn::Base64编码用户数据,这是EC2实例识别用户数据的要求 - 脚本开头必须加
#!/bin/bash,确保系统能正确执行命令
- 用
正确使用
Fn::Sub的场景:
如果需要在脚本中引用CloudFormation参数/资源,要保证Fn::Sub的第一个参数是字符串(支持多行),比如:UserData: !Base64 !If - IsAmazonLinux2 - !Sub | #!/bin/bash yum update -y yum install -y httpd echo "部署的AMI类型:${selectAMI}" > /var/www/html/index.html systemctl start httpd systemctl enable httpd - !Sub | #!/bin/bash apt update -y apt install -y apache2 echo "部署的AMI类型:${selectAMI}" > /var/www/html/index.html systemctl start apache2 systemctl enable apache2
注意事项
- 替换模板中的
ImageId为你所在AWS区域的对应镜像ID,可通过aws ec2 describe-images命令或AWS控制台查询 - 确保EC2实例所在的安全组允许HTTP(80端口)流量,否则无法验证服务是否正常启动
内容的提问来源于stack exchange,提问作者Rorschach
相关产品推荐
相关产品推荐

