Search code examples
amazon-web-servicesamazon-s3yamlaws-cloudformation

Is there a way to conditionally add expiration policies to an S3 bucket in cloudformation


I'm defining an S3 bucket in a CloufFormation template:

Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: Private
      BucketName: !Ref BucketName

I want to optionally add a retention policy to the bucket, so:

Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: Private
      BucketName: !Ref BucketName
      LifecycleConfiguration:
        Rules:
          - ExpirationInDays: !Ref RetentionDays

I don't need the LifecycleConfiguration/ExpirationInDays on all deployments of the CF template because some buckets will retain their objects indefinitely. I've looked at the documentation, and there doesn't appear to be a value for retain indefinitely/don't expire. I'd thought about having two buckets - one with the LifecycleConfiguration, and one without, and then I could use a condition (e.g. if the RetentionDays parameter = -1) to determine which bucket gets created:

Conditions:
  HasNoRetention: !Equals [!Ref RetentionDays, -1]
  HasRetention: !Not [Condition: HasNoRetention]
Resources:
  Bucket:
    Type: AWS::S3::Bucket
    Condition: HasNoRetention
    Properties:
      AccessControl: Private
      BucketName: !Ref BucketName
  BucketWithRetention:
    Type: AWS::S3::Bucket
    Condition: HasRetention
    Properties:
      AccessControl: Private
      BucketName: !Ref BucketName
      LifecycleConfiguration:
        Rules:
          - ExpirationInDays: !Ref RetentionDays

The issue here is that the buckets have different names in the YAML definition ("Bucket", and "BucketWithRetention") - so it would be difficult to !Ref the correct bucket in other resources later on as you'd have to determine which bucket was created.


Solution

  • I think the following should work using Fn::If:

    LifecycleConfiguration:
      Rules:
        !If 
          - RetentionDays
          - - ExpirationInDays: !Ref RetentionDays
          - !Ref 'No::Value'