CloudFormation创建LightSail实例时Metadata的packages被忽略如何解决
问题修复方案
核心错误原因
- 属性层级配置错误:
UserData是AWS::Lightsail::Instance顶层Properties的配置项,原模板错误将其放在了Metadata块下,导致用户数据注入失效。 - 元数据键名拼写错误:官方规定的元数据键为
AWS::CloudFormation::Init,原模板中Formation的首字母F小写,导致CloudFormation无法识别对应的包安装配置。 - 实例权限缺失:Lightsail实例默认没有调用CloudFormation API的权限,
cfn-init无法拉取栈内的元数据配置,因此返回执行失败。 - 依赖缺失:Ubuntu 20.04默认未安装
python3-setuptools,会导致easy_install命令执行失败。
具体调整步骤
- 提前创建IAM角色和实例配置文件
角色信任策略允许lightsail.amazonaws.com代入,附加如下权限策略:{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "cloudformation:DescribeStackResource", "cloudformation:SignalResource" ], "Resource": "*" } ] } - 调整后的CloudFormation模板如下:
Description: AWS CloudFormation Temp to create LightSail Instance with apache2 Resources: LightSail: Type: AWS::Lightsail::Instance Properties: BlueprintId: ubuntu_20_04 BundleId: micro_2_0 InstanceName: test # 替换为你创建好的实例配置文件ARN IamInstanceProfileArn: arn:aws:iam::你的AWS账号ID:instance-profile/你的实例配置文件名 UserData: !Sub | apt-get -y update apt-get -y install python3-setuptools wget mkdir -p /opt/aws/bin wget https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-py3-latest.tar.gz python3 -m easy_install --script-dir /opt/aws/bin aws-cfn-bootstrap-py3-latest.tar.gz # Start cfn-init /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource LightSail --region ${AWS::Region} # cfn-init completed so signal success or not /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource LightSail --region ${AWS::Region} Metadata: AWS::CloudFormation::Init: config: packages: apt: apache2: []
验证方法
实例启动2分钟后,登录实例执行systemctl status apache2,可以看到apache2服务正常运行,说明Metadata中的packages配置已经生效。
内容的提问来源于stack exchange,提问作者Not An Alien
相关产品推荐
相关产品推荐

