AWSTemplateFormatVersion: '2010-09-09'
Description: 'CloudFormation template for Cloudglue external S3 access role'

Parameters:
  BucketName:
    Type: String
    Description: 'S3 bucket name that you want to grant access to for Cloudglue'
    Default: 'your-bucket-name-here'

  ExternalId:
    Type: String
    Description: 'External ID to prevent confused deputy problem (required for third-party access)'
    MinLength: 2
    MaxLength: 1224
    AllowedPattern: '^[a-zA-Z0-9+=,.@:/-]+$'

Resources:
  CloudglueExternalS3AccessRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: cloudglue-external-s3-access-role
      Description: 'IAM role for Cloudglue external S3 access with cross-account permissions'
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              AWS: arn:aws:iam::992382634011:root
            Action: sts:AssumeRole
            Condition:
              StringEquals:
                sts:ExternalId: !Ref ExternalId
      ManagedPolicyArns: []
      Policies:
        - PolicyName: CloudglueExternalS3AccessPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Sid: AllowCrossAccountRoleReadAccess
                Effect: Allow
                Action:
                  - s3:GetObject
                  - s3:ListBucket
                  - s3:GetBucketLocation
                Resource:
                  - !Sub 'arn:aws:s3:::${BucketName}'
                  - !Sub 'arn:aws:s3:::${BucketName}/*'
              - Sid: AllowCrossAccountRoleWriteAccess
                Effect: Allow
                Action:
                  - s3:PutObject
                Resource:
                  - arn:aws:s3:::cloudglue-external-transfer
                  - arn:aws:s3:::cloudglue-external-transfer/*

Outputs:
  RoleArn:
    Description: 'ARN of the created IAM role'
    Value: !GetAtt CloudglueExternalS3AccessRole.Arn
    Export:
      Name: !Sub '${AWS::StackName}-RoleArn'

  RoleName:
    Description: 'Name of the created IAM role'
    Value: !Ref CloudglueExternalS3AccessRole
    Export:
      Name: !Sub '${AWS::StackName}-RoleName'
