AWSTemplateFormatVersion: '2010-09-09'
Description: 'Creates an S3 bucket and grants read/write access to an external IAM role'

Parameters:
  BucketName:
    Type: String
    Description: 'Name for the S3 bucket (must be globally unique)'
    Default: 'snowflake-landing-zone'

Resources:
  S3Bucket:
    Type: 'AWS::S3::Bucket'
    Properties:
      BucketName: !Ref BucketName
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: AES256

  S3BucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      Bucket: !Ref S3Bucket
      PolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Sid: 'AllowExternalRoleReadWrite'
            Effect: 'Allow'
            Principal:
              AWS: 'arn:aws:iam::791778434480:role/zeroadmin-production'
            Action:
              - 's3:GetObject'
              - 's3:GetObjectVersion'
              - 's3:PutObject'
              - 's3:PutObjectAcl'
              - 's3:DeleteObject'
              - 's3:DeleteObjectVersion'
            Resource: !Sub 'arn:aws:s3:::${S3Bucket}/*'
          - Sid: 'AllowExternalRoleListBucket'
            Effect: 'Allow'
            Principal:
              AWS: 'arn:aws:iam::791778434480:role/zeroadmin-production'
            Action:
              - 's3:ListBucket'
              - 's3:ListBucketVersions'
              - 's3:GetBucketLocation'
            Resource: !Sub 'arn:aws:s3:::${S3Bucket}'

Outputs:
  BucketName:
    Description: 'Name of the created S3 bucket'
    Value: !Ref S3Bucket
    Export:
      Name: !Sub '${AWS::StackName}-BucketName'
