---
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Create an EC2 instance; export logs to CloudWatch'
 # ----------------------------------------------------------------------------
 # Copyright 2017 Amazon.com, Inc. or its affiliates. 
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
 # You may obtain a copy of the License at
 #
 #    http://www.apache.org/licenses/LICENSE-2.0
 #
 # Unless required by applicable law or agreed to in writing, software
 # distributed under the License is distributed on an "AS IS" BASIS,
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
 # ----------------------------------------------------------------------------
Metadata:
  'AWS::CloudFormation::Interface':
    ParameterGroups:
    - Label:
        default: 'EC2 Parameters'
      Parameters:
      - InstanceType
      - VPCSubnet
      - EC2LogGroup
      - SecurityGroup
      - EC2InstanceIAMRoleName 
      - CFStackToDelete
Parameters:
  VPCSubnet:
    Description: 'Subnet in which to create the EC2 instance.'
    Type: AWS::EC2::Subnet::Id
  EC2InstanceIAMRoleName:
    Description: 'IAM Role name for EC2 instance'
    Type: String
  CFStackToDelete:
      Description: 'CF stack name, that should be shut down'
      Type: String    
  EC2LogGroup:
    Description: 'EC2 Log Group to use for instance log files'
    Type: String
  SecurityGroup:
    Description: 'Security group to launch this EC2 instance in.'
    Type: AWS::EC2::SecurityGroup::Id
  InstanceType:
    Description: 'Instance type of the EC2 instance.'
    Type: String
    Default: 't2.nano'
    AllowedValues:
    # AllowedValues are limited to 'cheap ones'
    - t2.nano
    - t2.micro
    - t2.small
    - t2.medium
  s3BucketForResults:
    Type: String
    Description: S3bucket to write results out to
    Default: ''
  DigitsToCalculate:
    Type: String
    Description: Number of Digits of Pi to Calculate
    Default: '15000'
Mappings:
  RegionMap:
    'ap-south-1':
      AMI: 'ami-cacbbea5'
    'eu-west-1':
      AMI: 'ami-d41d58a7'
    'ap-northeast-2':
      AMI: 'ami-a04297ce'
    'ap-northeast-1':
      AMI: 'ami-1a15c77b'
    'sa-east-1':
      AMI: 'ami-b777e4db'
    'ap-southeast-1':
      AMI: 'ami-7243e611'
    'ap-southeast-2':
      AMI: 'ami-55d4e436'
    'eu-central-1':
      AMI: 'ami-0044b96f'
    'us-east-1':
      AMI: 'ami-c481fad3'
    'us-east-2':
      AMI: 'ami-71ca9114'
    'us-west-1':
      AMI: 'ami-de347abe'
    'us-west-2':
      AMI: 'ami-b04e92d0'
Resources:
  EC2InstanceProfile:
    Type: 'AWS::IAM::InstanceProfile'
    Properties:
      Path: '/'
      Roles:
      - !Ref EC2InstanceIAMRoleName      
  EC2Instance: 
    Type: 'AWS::EC2::Instance'
    Metadata:
      'AWS::CloudFormation::Init':
        configSets:
          default:
            [config]
        config:
          packages:
            yum:
              awslogs: []
              jq: []
          files:
            '/etc/awslogs/awscli.conf':
              content: !Sub |
                [default]
                region = ${AWS::Region}
                [plugins]
                cwlogs = cwlogs
              mode: '000644'
              owner: root
              group: root
            '/etc/awslogs/awslogs.conf':
              content: !Sub |
                [general]
                state_file = /var/lib/awslogs/agent-state
                [/var/log/dmesg]
                file = /var/log/dmesg
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/dmesg
                log_group_name = ${EC2LogGroup}
                [/var/log/messages]
                datetime_format = %b %d %H:%M:%S
                file = /var/log/messages
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/messages
                log_group_name = ${EC2LogGroup}
                [/var/log/secure]
                datetime_format = %b %d %H:%M:%S
                file = /var/log/secure
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/secure
                log_group_name = ${EC2LogGroup}
                [/var/log/cron]
                datetime_format = %b %d %H:%M:%S
                file = /var/log/cron
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/cron
                log_group_name = ${EC2LogGroup}
                [/var/log/cloud-init.log]
                datetime_format = %b %d %H:%M:%S
                file = /var/log/cloud-init.log
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/cloud-init.log
                log_group_name = ${EC2LogGroup}
                [/var/log/cfn-init.log]
                datetime_format = %Y-%m-%d %H:%M:%S
                file = /var/log/cfn-init.log
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/cfn-init.log
                log_group_name = ${EC2LogGroup}
                [/var/log/cfn-hup.log]
                datetime_format = %Y-%m-%d %H:%M:%S
                file = /var/log/cfn-hup.log
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/cfn-hup.log
                log_group_name = ${EC2LogGroup}
                [/var/log/cfn-init-cmd.log]
                datetime_format = %Y-%m-%d %H:%M:%S
                file = /var/log/cfn-init-cmd.log
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/cfn-init-cmd.log
                log_group_name = ${EC2LogGroup}
                [/var/log/cloud-init-output.log]
                file = /var/log/cloud-init-output.log
                log_stream_name = ${AWS::StackName}/{instance_id}/var/log/cloud-init-output.log
                log_group_name = ${EC2LogGroup}
              mode: '000644'
              owner: root
              group: root
            '/etc/cfn/cfn-hup.conf':
              content: !Sub |
                [main]
                stack=${AWS::StackId}
                region=${AWS::Region}
                interval=1
              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.EC2Instance.Metadata.AWS::CloudFormation::Init
                action=/opt/aws/bin/cfn-init --verbose --stack=${AWS::StackName} --region=${AWS::Region} --resource=EC2Instance
                runas=root
          services:
            sysvinit:
              awslogs:
                enabled: true
                ensureRunning: true
                packages:
                  yum:
                  - awslogs
                files:
                - '/etc/awslogs/awslogs.conf'
                - '/etc/awslogs/awscli.conf'
              cfn-hup:
                enabled: true
                ensureRunning: true
                files:
                - '/etc/cfn/cfn-hup.conf'
                - '/etc/cfn/hooks.d/cfn-auto-reloader.conf'
    Properties:
      EbsOptimized: false
      SubnetId: !Ref VPCSubnet
      IamInstanceProfile: !Ref EC2InstanceProfile
      ImageId: !FindInMap [RegionMap, !Ref 'AWS::Region', AMI]
      InstanceType: !Ref InstanceType
      #Tenancy: dedicated
      SecurityGroupIds:
      - !Ref SecurityGroup
      UserData:
        'Fn::Base64': !Sub |
          #!/bin/bash -x
          # Use the line below to ensure the CloudFormation helper scripts are updated to the latest version
          # Per: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-helper-scripts-reference.html 
          yum install -y aws-cfn-bootstrap
          yum update -y      
          /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource EC2Instance --configsets default --region ${AWS::Region}
          INSTANCEID=$(curl -s -m 60 http://169.254.169.254/latest/meta-data/instance-id)
          /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --region ${AWS::Region} --resource=EC2Instance
          
          # Do something!
          filename="/tmp/PiCalculation-`date +%s`.out"
          curl http://169.254.169.254/latest/meta-data/instance-id > $filename
          date >> $filename
          echo "scale=${DigitsToCalculate}; 4*a(1)" | bc -l >> $filename
          aws s3 cp $filename s3://${s3BucketForResults}/Picalc/
          echo "Done calculating"
          #aws cloudformation delete-stack --stack-name ${CFStackToDelete} --region ${AWS::Region} 
          
    CreationPolicy:
      ResourceSignal:
        Timeout: PT10M
Outputs:
  EC2InstanceId:
    Description: EC2 instance created by this stack
    Value:
      Ref: EC2Instance
    Export:
      Name:
        Fn::Sub: "${AWS::StackName}-EC2InstanceId"  
