Home > Back-end >  CFN condition for the replication configuration on S3 buckets
CFN condition for the replication configuration on S3 buckets

Time:07-25

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

CodePudding user response:

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:
    ShloudCreateReplicationConfiguration:
        !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
               - ShloudCreateReplicationConfiguration
               - Role: !GetAtt SpeedDialBucketReplicationRole.Arn
                 Rules:
                   - Status: Enabled
                     Destination:
                       Bucket: !Join [ '', [ 'arn:aws:s3:::', !Join  [ '-', [ !Ref SpeedDialBucketName, 'second', !Ref StageName ]]]]
                       StorageClass: STANDARD   
               - !Ref "AWS::NoValue"
  • Related