AWSTemplateFormatVersion: '2010-09-09'
Description: FCJ Workshop 000069 - S3 Security Best Practices lab environment
Parameters:
  LatestAmiId:
    Type: AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
    Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
  InstanceType:
    Type: String
    Default: t3.micro
  PermissionsBoundaryArn:
    Type: String
    Default: ''
    Description: Optional IAM permissions boundary ARN for the EC2 role (leave empty if not required)
Conditions:
  HasBoundary: !Not [!Equals [!Ref PermissionsBoundaryArn, '']]
Resources:
  Vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.20.0.0/16
      EnableDnsHostnames: true
      EnableDnsSupport: true
      Tags: [{Key: Name, Value: SID-vpc}]
  Igw:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags: [{Key: Name, Value: SID-igw}]
  IgwAttach:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties: {VpcId: !Ref Vpc, InternetGatewayId: !Ref Igw}
  Subnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref Vpc
      CidrBlock: 10.20.1.0/24
      AvailabilityZone: !Select [0, !GetAZs '']
      MapPublicIpOnLaunch: true
      Tags: [{Key: Name, Value: SID-public-subnet}]
  RouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref Vpc
      Tags: [{Key: Name, Value: SID-routes}]
  DefaultRoute:
    Type: AWS::EC2::Route
    DependsOn: IgwAttach
    Properties: {RouteTableId: !Ref RouteTable, DestinationCidrBlock: 0.0.0.0/0, GatewayId: !Ref Igw}
  SubnetRta:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties: {SubnetId: !Ref Subnet, RouteTableId: !Ref RouteTable}
  InstanceSg:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: SID-instance-sg
      GroupDescription: Lab instance - no inbound rules, access via Session Manager
      VpcId: !Ref Vpc
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: !Join ['-', ['sid-security', !Select [0, !Split ['-', !Select [2, !Split ['/', !Ref 'AWS::StackId']]]]]]
      OwnershipControls:
        Rules: [{ObjectOwnership: ObjectWriter}]
      PublicAccessBlockConfiguration:
        BlockPublicAcls: false
        IgnorePublicAcls: false
        BlockPublicPolicy: true
        RestrictPublicBuckets: true
      Tags: [{Key: Project, Value: fcj-s3-security}]
  Role:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub FCJ-S3Security-EC2-Role-${AWS::Region}
      PermissionsBoundary: !If [HasBoundary, !Ref PermissionsBoundaryArn, !Ref 'AWS::NoValue']
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal: {Service: ec2.amazonaws.com}
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
      Policies:
        - PolicyName: lab-bucket-access
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: s3:*
                Resource:
                  - !GetAtt Bucket.Arn
                  - !Sub '${Bucket.Arn}/*'
  Profile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      InstanceProfileName: !Sub FCJ-S3Security-EC2-Profile-${AWS::Region}
      Roles: [!Ref Role]
  Instance:
    Type: AWS::EC2::Instance
    DependsOn: DefaultRoute
    Properties:
      ImageId: !Ref LatestAmiId
      InstanceType: !Ref InstanceType
      SubnetId: !Ref Subnet
      SecurityGroupIds: [!Ref InstanceSg]
      IamInstanceProfile: !Ref Profile
      Tags: [{Key: Name, Value: SID-security-instance}]
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash
          echo "export bucket=${Bucket}" > /etc/profile.d/sid-lab.sh
          echo "export AWS_DEFAULT_REGION=${AWS::Region}" >> /etc/profile.d/sid-lab.sh
          echo "app1 sample data" > /tmp/file1
          aws s3 cp /tmp/file1 s3://${Bucket}/app1/file1 --region ${AWS::Region}
Outputs:
  BucketName: {Value: !Ref Bucket}
  VpcId: {Value: !Ref Vpc}
