AWSTemplateFormatVersion: '2010-09-09'
Description: >-
  Creates a Systems Manager Automation runbook that performs the whole patch
  cycle end to end: run the Image Builder pipeline, wait for the new AMI, then
  update the application stack so the new AMI rolls out with no downtime.
  This stack creates only the runbook. Nothing runs until you start it.

Parameters:
  ImageBuilderPipelineStack:
    Type: String
    Description: Name of the pipeline stack, used to look up the pipeline ARN.
  ApplicationStack:
    Type: String
    Description: Name of the application stack that will receive the new AMI.

Outputs:
  Pattern3CreateImageOutput:
    Description: Runbook name. Pass this to 'aws ssm start-automation-execution'.
    Value: !Ref Pattern3CreateImage

Resources:
  Pattern3CreateImage:
    Type: "AWS::SSM::Document"
    Properties:
      DocumentType: Automation
      Tags:
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder
      Content:
        description: >-
          Build a patched AMI with EC2 Image Builder, then update the application
          stack so the Auto Scaling Group replaces its instances with the new AMI.
        schemaVersion: '0.3'
        parameters:
          # Both parameters get defaults from the CloudFormation stack, so the
          # runbook can be started without passing anything.
          ImageBuilderPipeline:
            default:
              Fn::ImportValue: !Sub "${ImageBuilderPipelineStack}-ImageBuilderPipeline"
            description: (Required) ARN of the Image Builder pipeline to run.
            type: String
          ApplicationStack:
            default: !Ref ApplicationStack
            description: (Required) Application stack to deploy the new AMI to.
            type: String
        outputs:
          - GetBuiltImage.image
        mainSteps:
          - name: ExecuteImageCreation
            action: aws:executeAwsApi
            maxAttempts: 3
            timeoutSeconds: 600
            onFailure: Abort
            inputs:
              Service: imagebuilder
              Api: StartImagePipelineExecution
              imagePipelineArn: '{{ ImageBuilderPipeline }}'
            outputs:
              - Name: imageBuildVersionArn
                Selector: $.imageBuildVersionArn
                Type: String

          # The build itself takes 20 to 30 minutes, hence the long timeout.
          - name: WaitImageComplete
            action: aws:waitForAwsResourceProperty
            maxAttempts: 3
            timeoutSeconds: 5400
            onFailure: Abort
            inputs:
              Service: imagebuilder
              Api: GetImage
              imageBuildVersionArn: '{{ ExecuteImageCreation.imageBuildVersionArn }}'
              PropertySelector: image.state.status
              DesiredValues:
                - AVAILABLE

          - name: GetBuiltImage
            action: aws:executeAwsApi
            maxAttempts: 3
            timeoutSeconds: 600
            onFailure: Abort
            inputs:
              Service: imagebuilder
              Api: GetImage
              imageBuildVersionArn: '{{ ExecuteImageCreation.imageBuildVersionArn }}'
            outputs:
              - Name: image
                Selector: $.image.outputResources.amis[0].image
                Type: String

          - name: UpdateCluster
            action: aws:executeAwsApi
            maxAttempts: 3
            timeoutSeconds: 600
            onFailure: Abort
            inputs:
              Service: cloudformation
              Api: UpdateStack
              StackName: '{{ ApplicationStack }}'
              UsePreviousTemplate: true
              # Every parameter must be listed. UpdateStack resets any parameter
              # left out to the template default instead of keeping its value.
              Parameters:
                - ParameterKey: BaselineVpcStack
                  UsePreviousValue: true
                - ParameterKey: NumberOfInstanceCluster
                  UsePreviousValue: true
                - ParameterKey: MaxNumberOfInstanceCluster
                  UsePreviousValue: true
                - ParameterKey: InstanceType
                  UsePreviousValue: true
                - ParameterKey: LatestAmiId
                  UsePreviousValue: true
                - ParameterKey: AmazonMachineImage
                  ParameterValue: '{{ GetBuiltImage.image }}'
              Capabilities:
                - CAPABILITY_IAM

          - name: WaitDeploymentComplete
            action: aws:waitForAwsResourceProperty
            maxAttempts: 3
            timeoutSeconds: 3600
            onFailure: Abort
            inputs:
              Service: cloudformation
              Api: DescribeStacks
              StackName: '{{ ApplicationStack }}'
              PropertySelector: Stacks[0].StackStatus
              DesiredValues:
                - UPDATE_COMPLETE
