AWSTemplateFormatVersion: '2010-09-09'
Description: >-
  An EC2 Image Builder pipeline that produces a patched Amazon Linux 2023 AMI.
  It defines what to install (component), what to build from (recipe), where to
  build it (infrastructure configuration), and ties them together as a pipeline
  that runs on demand.

Parameters:
  BaselineVpcStack:
    Type: String
    Description: Name of the base network stack to import the VPC and subnet from.

  MasterAMI:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
    Description: >-
      Public SSM parameter resolving to the newest Amazon Linux 2023 AMI, used as
      the parent image. Every build therefore starts from an up to date base.

  Ver:
    Type: String
    Default: "1.0.0"
    Description: Version applied to the component and the image recipe.

  BuildInstanceType:
    Type: String
    Default: t3.medium
    AllowedValues:
      - t3.small
      - t3.medium
      - t3.large
    Description: Instance size used to build the image.

  EnableInspectorScanning:
    Type: String
    Default: "false"
    AllowedValues: [ "true", "false" ]
    Description: >-
      Scan the output AMI for vulnerabilities with Amazon Inspector. Only enable
      this if Inspector is already activated for Amazon EC2 in the account.

Conditions:
  UseInspectorScanning: !Equals [ !Ref EnableInspectorScanning, "true" ]

Resources:

  #############
  # COMPONENT: the work performed inside the build instance
  #############
  ComponentConfigureOS:
    Type: 'AWS::ImageBuilder::Component'
    Properties:
      Name: !Sub "${AWS::StackName}-ConfigureOSComponent"
      Platform: 'Linux'
      Version: !Ref Ver
      Description: 'Apply all available operating system updates'
      SupportedOsVersions:
        - 'Amazon Linux 2023'
      Tags:
        Name: !Sub "${AWS::StackName}-ConfigureOS"
        ResourceType: awsstudygroup-000099-imagebuilder
      Data: |
        name: ConfigureOS
        description: Update the operating system to the latest available packages
        schemaVersion: 1.0
        phases:
          - name: build
            steps:
              - name: UpdateOS
                action: UpdateOS

  #############
  # RECIPE: parent image plus the components to run on it
  #############
  Pattern3ImageRecipe:
    Type: 'AWS::ImageBuilder::ImageRecipe'
    Properties:
      Name: !Sub "${AWS::StackName}-ImageRecipe"
      Version: !Ref Ver
      ParentImage: !Ref MasterAMI
      Description: !Sub "${AWS::StackName}-ImageRecipe"
      Components:
        - ComponentArn: !GetAtt ComponentConfigureOS.Arn
      Tags:
        Name: !Sub "${AWS::StackName}-Pattern3ImageRecipe"
        ResourceType: awsstudygroup-000099-imagebuilder

  ##############
  # INFRASTRUCTURE CONFIGURATION: the temporary instance used for the build.
  # It sits in a private subnet and reaches the internet through the NAT
  # Gateway to download packages and register with Systems Manager.
  ##############
  Pattern3InfraConfig:
    Type: 'AWS::ImageBuilder::InfrastructureConfiguration'
    Properties:
      Name: !Sub "${AWS::StackName}-InfraConfig"
      InstanceProfileName: !Ref Pattern3InstancePfl
      InstanceTypes:
        - !Ref BuildInstanceType
      TerminateInstanceOnFailure: true
      InstanceMetadataOptions:
        HttpTokens: required
        HttpPutResponseHopLimit: 2
      SecurityGroupIds:
        - !Ref Pattern3InstanceSG
      SubnetId:
        Fn::ImportValue: !Sub "${BaselineVpcStack}-PrivateSubnet1"
      Logging:
        S3Logs:
          S3BucketName: !Ref Pattern3LoggingBucket
          S3KeyPrefix: !Sub "Pattern3ImagePipeline/${Ver}"
      ResourceTags:
        ResourceType: awsstudygroup-000099-imagebuilder
      Tags:
        Name: !Sub "${AWS::StackName}-Pattern3InfraConfig"
        ResourceType: awsstudygroup-000099-imagebuilder

  Pattern3LoggingBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      OwnershipControls:
        Rules:
          - ObjectOwnership: BucketOwnerEnforced
      LifecycleConfiguration:
        Rules:
          - Id: ExpireBuildLogs
            Status: Enabled
            ExpirationInDays: 7
      Tags:
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder

  Pattern3InstanceSG:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: >-
        Build instance security group. No inbound rules are needed, only the
        default outbound access so the instance can download packages.
      VpcId:
        Fn::ImportValue: !Sub "${BaselineVpcStack}-VpcId"
      Tags:
        - Key: Name
          Value: !Sub "${AWS::StackName}-BuildAMIInstanceSecurityGroup"
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder

  Pattern3InstancePfl:
    Type: "AWS::IAM::InstanceProfile"
    Properties:
      Path: "/"
      Roles:
        - !Ref Pattern3InstanceRole

  Pattern3InstanceRole:
    Type: AWS::IAM::Role
    Properties:
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
        - arn:aws:iam::aws:policy/EC2InstanceProfileForImageBuilder
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: [ ec2.amazonaws.com ]
            Action:
              - sts:AssumeRole
      Policies:
        - PolicyName: Pattern3WriteBuildLogsToS3
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - s3:PutObject
                Resource: !Sub "${Pattern3LoggingBucket.Arn}/*"
              - Effect: Allow
                Action:
                  - s3:GetBucketLocation
                  - s3:ListBucket
                Resource: !GetAtt Pattern3LoggingBucket.Arn
      Path: /
      Tags:
        - Key: ResourceType
          Value: awsstudygroup-000099-imagebuilder

  ##############
  # PIPELINE: no schedule, because Systems Manager triggers it on demand
  ##############
  Pattern3ImagePipeline:
    Type: 'AWS::ImageBuilder::ImagePipeline'
    Properties:
      Name: !Sub "${AWS::StackName}-ImagePipeline"
      Description: 'Builds a patched golden AMI for the workshop'
      ImageRecipeArn: !Ref Pattern3ImageRecipe
      InfrastructureConfigurationArn: !Ref Pattern3InfraConfig
      EnhancedImageMetadataEnabled: true
      ImageTestsConfiguration:
        ImageTestsEnabled: false
        TimeoutMinutes: 90
      ImageScanningConfiguration:
        ImageScanningEnabled: !If [ UseInspectorScanning, true, false ]
      Status: 'ENABLED'
      Tags:
        Name: !Sub "${AWS::StackName}-Pattern3ImagePipeline"
        ResourceType: awsstudygroup-000099-imagebuilder

Outputs:
  Pattern3ImagePipeline:
    Description: Pipeline ARN, needed by the Systems Manager automation
    Value: !Ref Pattern3ImagePipeline
    Export:
      Name: !Sub "${AWS::StackName}-ImageBuilderPipeline"
  Pattern3ParentImageId:
    Description: Parent AMI this pipeline builds from
    Value: !Ref MasterAMI
  Pattern3LoggingBucketName:
    Description: Bucket holding the build logs. Empty it before deleting the stack.
    Value: !Ref Pattern3LoggingBucket
    Export:
      Name: !Sub "${AWS::StackName}-LoggingBucket"
