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

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命令执行失败。

具体调整步骤

  1. 提前创建IAM角色和实例配置文件
    角色信任策略允许lightsail.amazonaws.com代入,附加如下权限策略:
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "cloudformation:DescribeStackResource",
            "cloudformation:SignalResource"
          ],
          "Resource": "*"
        }
      ]
    }
    
  2. 调整后的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:36:02