未在AWS CloudFormation模板上执行Userdata脚本

时间:2019-01-31 06:20:45

标签: amazon-web-services amazon-ec2 amazon-cloudformation user-data cloud-init

我正在尝试创建一个CloudFormation堆栈,该堆栈具有UserData脚本以在EC2实例启动时安装Java,tomcat,httpd和Java应用程序。 但是,使用所有资源成功创建了堆栈,但是当我连接到EC2实例以检查上述应用程序的配置时,找不到任何堆栈。我的用例是使用所有上述应用程序/软件启动一个实例,以实现自动化安装。

UserData:
   Fn::Base64: 
    Fn::Join: 
    - ' '
    - - '#!/bin/bash -xe\n'

      - 'sudo yum update && install pip && pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\n'
      - 'date > /home/ec2-user/starttime\n'
      - 'sudo yum update -y aws-cfn-bootstrap\n'

        # Initialize CloudFormation bits\n
      - ' ' 
      - '/opt/aws/bin/cfn-init -v\n'
      - '             --stack\n'
      - '!Ref AWS::StackName\n'
      - '             --resource LaunchConfig\n'
      - 'ACCESS_KEY=${HostKeys}&SECRET_KEY=${HostKeys.SecretAccessKey}\n'

       # Start servers\n
      - 'service tomcat8 start\n'
      - '/etc/init.d/httpd start\n'

      - 'date > /home/ec2-user/stoptime\n'
Metadata: 
 AWS::CloudFormation::Init:
  config: 
   packages: 
    yum:
    - java-1.8.0-openjdk.x86_64: []   
    - tomcat8: []
    - httpd: []
   services:
    sysvinit:
     httpd:
      enabled: 'true'
      ensureRunning: 'true'
  files: 
  - /usr/share/tomcat8/webapps/sample.war:
    - source: https://s3-eu-west-1.amazonaws.com/testbucket/sample.war
    - mode: 000500
    - owner: tomcat
    - group: tomcat
   CfnUser:
    Type: AWS::IAM::User
    Properties: 
     Path: '/'  
     Policies: 
     - PolicyName: Admin
       PolicyDocument: 
        Statement:
        - Effect: Allow
          Action: '*'
          Resource: '*'
   HostKeys:
    Type: AWS::IAM::AccessKey
    Properties: 
      UserName: !Ref CfnUser

1 个答案:

答案 0 :(得分:2)

问题在于您格式化UserData的方式。我建议您启动EC2实例并首先手动测试脚本。它有很多问题。

尝试像这样格式化您的UserData:

UserData:
  Fn::Base64:
    !Sub |
      #!/bin/bash -xe

      # FIXME. This won't work either.
      # sudo yum update && install pip && pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz

      date > /home/ec2-user/starttime
      sudo yum update -y aws-cfn-bootstrap

      # Initialize CloudFormation bits
      /opt/aws/bin/cfn-init -v \
        --stack ${AWS::StackName} \
        --resource LaunchConfig

      # FIXME. Not sure why these are here.
      # ACCESS_KEY=${HostKeys}
      # SECRET_KEY=${HostKeys.SecretAccessKey}

      # Start servers\n
      service tomcat8 start
      /etc/init.d/httpd start

      date > /home/ec2-user/stoptime

注意事项:

  • 您不能在此处使用!Ref表示法进行内插。请注意,我将其更改为${AWS::StackName},并注意到整个块都在!Sub内部。
  • 正如我的评论所示,yum更新行中包含无效命令。
  • 如注释中所述,注入访问密钥是一种不好的做法。另外,此脚本中的任何内容似乎都不需要键。

还请注意,在元数据中错误地将文件部分指定为数组而不是哈希键。

应该是:

  files: 
    /usr/share/tomcat8/webapps/sample.war:
      source: https://s3-eu-west-1.amazonaws.com/testbucket/sample.war
      mode: '000500'
      owner: tomcat
      group: tomcat