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

时间:2019-02-04 06:40:08

标签: amazon-s3 amazon-ec2 amazon-cloudformation amazon-iam user-data

我正在尝试在启动时在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

1 个答案:

答案 0 :(得分:1)

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

---
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实例,然后添加用于授予对该角色适当访问权限的存储桶策略的最佳实践。