Ubuntu Server 16.04 LTS(HVM) 起動のCloudFormationテンプレート


EC2起動の時に選択肢に表示されるUbuntu起動のテンプレートです.
CloudFormationのメタデータ取得や変更検知、状態通知などを行うヘルパースクリプトのインストールに手間取ったのであげておきます.
pipでインストールしてるので長くなっちゃってますが、wgetでファイル取って来る方法も取れそうです.

参考:

- [CloudFormation ヘルパースクリプトリファレンス](https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/cfn-helper-scripts-reference.html)
- [AWS CloudFormation helper scripts on Ubuntu - aws-cfn-bootstrap（海外の個人ブログ）](https://commscentral.net/tech/?post=50)

```
AWSTemplateFormatVersion: '2010-09-09'
Description: CFn template for ubuntu
Parameters:
  InstanceType:
    Description: EC2 instance type
    Type: String
    Default: t2.nano
    AllowedValues:
      - t2.nano 
    ConstraintDescription: must be a valid EC2 instance type.
  KeyName: 
    Description: Name of an existing Amazon EC2 key pair for SSH access
    Type: AWS::EC2::KeyPair::KeyName
  SSHLocation:
    Description: The IP address range that can be used to SSH to the EC2 instances
    Type: String
    MinLength: 9
    MaxLength: 18
    AllowedPattern: (\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})
    ConstraintDescription: must be a valid IP CIDR range of the form x.x.x.x/x.  
Mappings:
  AWSRegion2AMI:
    ap-northeast-1: 
      ubuntu: ami-ea4eae8c
Resources:
  ServerInstance:
    Type: AWS::EC2::Instance
    Metadata:
      Comment: Simple example for cfn-init
      AWS::CloudFormation::Init:
        config:
          packages:
            apt:
              httpd: [] 
          files:
            /etc/cfn/cfn-hup.conf:  # CFn側の変更検知のための設定
              content: !Sub |
                [main]
                stack=${AWS::StackId}
                region=${AWS::Region}
              mode: '000400'
              owner: root
              group: root
            /etc/cfn/hooks.d/cfn-auto-reloader.conf:  # 自動で更新を実行するための設定
              content: !Sub |
                [cfn-auto-reloader-hook]
                triggers=post.update
                path=Resources.DeepLeargingServerInstance.Metadata.AWS::CloudFormation::Init
                action=/usr/local/bin/cfn-init -s ${AWS::StackId} -r ServerInstance --region ${AWS::Region}
                runas=root
          services:
            sysvinit:
              cfn-hup:
                enabled: 'true'
                ensureRunning: 'true'
                files:
                  - /etc/cfn/cfn-hup.conf
                  - /etc/cfn/hooks.d/cfn-auto-reloader.conf
    Properties:
      ImageId: !FindInMap [AWSRegion2AMI, !Ref 'AWS::Region', ubuntu]      
      InstanceType: !Ref 'InstanceType'
      SecurityGroups:
        - !Ref 'ServerSecurityGroup'
      KeyName: !Ref 'KeyName'
      UserData: !Base64
        Fn::Sub: |
          #!/bin/bash -xe
          apt-get update
          # python 2.7, pipインストール
          apt-get -y install build-essential
          apt-get -y install python-dev python-pip
          # aws-cloudformation-bootstrapのインストール
          pip install https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz
          # cfn-hupの設定
          cp -a /usr/local/init/ubuntu/cfn-hup /etc/init.d/cfn-hup
          chmod u+x /etc/init.d/cfn-hup
          update-rc.d cfn-hup defaults  # シンボリックリンク作成
          service cfn-hup start
          # メタデータからのファイルとパッケージのロード
          /usr/local/bin/cfn-init -v --stack ${AWS::StackName} --resource ServerInstance --region ${AWS::Region}
          # cfn-init から取得したの状態の通知
          /usr/local/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource ServerInstance --region ${AWS::Region}
    CreationPolicy:
      ResourceSignal:
        Timeout: PT10M
  ServerSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Enable HTTP access via port 22
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '22'
          ToPort: '22'
          CidrIp: !Ref 'SSHLocation'
Outputs:
  WebsiteURL:
    Description: Application URL(Not Work, Just Sample)
    Value: !Sub 'http://${ServerInstance.PublicDnsName}'
```