amazon-web-servicesamazon-s3aws-cloudformation

CFN condition for the replication configuration on S3 buckets


I know that there exist dynamic blocks in terraform to create specific configuration on resource, but does this exist for CloudFormation? What I am after is switching off and on replication for S3 buckets. Currently, I just comment out the replication part when deploying.

SpeedDialBucket:
  Type: AWS::S3::Bucket
  Condition: IsPrimaryRegion
  Properties:
    BucketName: !Sub "voip-speed-dial-${StageName}"
    PublicAccessBlockConfiguration:
      BlockPublicAcls: True
      BlockPublicPolicy: True
      IgnorePublicAcls: True
      RestrictPublicBuckets: True
    VersioningConfiguration:
      Status: Enabled
    # THIS HAS TO BE COMMENTED OUT ON FIRST DEPLOY in MULTIREGION
    # ReplicationConfiguration:
    #   Role: !GetAtt SpeedDialBucketReplicationRole.Arn
    #   Rules:
    #     - Status: Enabled
    #       Destination:
    #         Bucket: !Join [ '', [ 'arn:aws:s3:::', !Join  [ '-', [ !Ref SpeedDialBucketName, 'second', !Ref StageName ]]]]
    #         StorageClass: STANDARD

Solution

  • Yes, you can do this, but you need to have some condition to enable/disable this block, just like in Terraform. You can do this with Parameters, Conditions and If. For example:

    Parameters:
        CreateReplicationConfiguration:
            Type: String
            Default: false
            AllowedValues: [true, false]        
            
    Conditions:
        ShouldCreateReplicationConfiguration:
            !Equals [!Ref CreateReplicationConfiguration, true]
        
    Resources:
        SpeedDialBucket:
            Type: AWS::S3::Bucket
            Condition: IsPrimaryRegion
            Properties:
                BucketName: !Sub "voip-speed-dial-${StageName}"
                PublicAccessBlockConfiguration:
                    BlockPublicAcls: True
                    BlockPublicPolicy: True
                    IgnorePublicAcls: True
                    RestrictPublicBuckets: True
                VersioningConfiguration:
                    Status: Enabled
                ReplicationConfiguration:
                    !If
                       - ShouldCreateReplicationConfiguration
                       - Role: !GetAtt SpeedDialBucketReplicationRole.Arn
                         Rules:
                           - Status: Enabled
                             Destination:
                               Bucket: !Join [ '', [ 'arn:aws:s3:::', !Join  [ '-', [ !Ref SpeedDialBucketName, 'second', !Ref StageName ]]]]
                               StorageClass: STANDARD   
                       - !Ref "AWS::NoValue"