无法通过 cfn-init 和 UserData 脚本使用 AWS CloudFormation 模板在 EC2 实例上部署应用程序

Unable to deploy application on EC2 instance using AWS CloudFormation template through cfn-init and UserData script

我正在尝试在启动时在 EC2 实例上部署 sample.war 应用程序。也就是说,当一个实例启动时,应用程序应该使用 cfn-init 和元数据自动部署在它上面。我添加了一个具有策略和身份验证的用户,但没有成功。如果我使用 S3 路径获取,则文件正在下载。下面是我的脚本。我在这方面缺少什么,或者有其他方法可以做到这一点吗?

---
AWSTemplateFormatVersion: 2010-09-09
Description: Test QA Template
Resources:
  MyInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !Ref AMIIdParam
      InstanceType: !Ref InstanceType
    Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              java-1.8.0-openjdk.x86_64: []
              tomcat: []
              httpd.x86_64: []
          services:
            sysvinit:
              httpd:
                enabled: true
                ensureRunning: true
          files:
            /usr/share/tomcat/webapps/sample.zip:
              source: https://s3.amazonaws.com/mybucket/sample.zip
              mode: '000500'
              owner: tomcat
              group: tomcat
              authentication: S3AccessCreds
      AWS::CloudFormation::Authentication:
        S3AccessCreds:
          type: 'S3'
          accessKeyId: !Ref HostKeys
          secretKey: Fn::GetAtt:
            - HostKeys
            - SecretAccessKey
          buckets: !Ref BucketName
  CfnUser:
    Type: AWS::IAM::User
    Properties:
      Path: '/'
      Policies:
        - PolicyName: 'S3Access'
          PolicyDocument:
           Statement:
             - Effect: 'Allow'
               Action: s3:*
               Resource: '*'
  HostKeys:
    Type: AWS::IAM::AccessKey
    Properties:
      UserName: !Ref CfnUser

我无法使用以下模板重现此内容:

---
AWSTemplateFormatVersion: 2010-09-09
Description: Test QA Template
Resources:
  MyInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-08589eca6dcc9b39c
      InstanceType: t2.micro
      KeyName: default
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash -xe
          /opt/aws/bin/cfn-init -s ${AWS::StackId} --resource MyInstance --region ${AWS::Region}
    Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              java-1.8.0-openjdk.x86_64: []
              tomcat: []
              httpd.x86_64: []
          services:
            sysvinit:
              httpd:
                enabled: true
                ensureRunning: true
          files:
            /usr/share/tomcat/webapps/sample.zip:
              source: https://s3.amazonaws.com/mybucket/sample.zip
              mode: '000500'
              owner: tomcat
              group: tomcat

(换句话说,使用上述模板允许我使用 cfn-init 安装 sample.zip 文件。)

因此,您访问 S3 存储桶的方式与权限相关。

可以说使用访问密钥是一种不好的做法。查看 this 文档,了解将 IAM 角色分配给 EC2 实例,然后添加向该角色授予适当访问权限的存储桶策略的最佳实践。