How to set TTL on a Blob in Google Cloud Storage using Java?
Asked Answered
W

2

9

Using Java, is it possible to set the time to live (TTL) on a blob that is being created in Google Cloud Storage?

I do not want to set TTL on the Bucket - only on the items within the Bucket.

For example, 14 days after its creation date, I would like any files that are stored in a specific bucket to be deleted.

Here is an example of how I am creating my blob: WriteChannel writer = storage.writer(BlobInfo.newBuilder(blobId).setContentType("application/json").build());

I was looking for a way to set the TTL upon creation but have not been able to find a solution. Please advise

Whitesell answered 10/8, 2017 at 1:3 Comment(1)
Google Cloud Storage uses Object Lifecycle Management feature to Time to Live (TTL) for objects, archiving older versions of objects, or "downgrading" storage classes of objects to help manage costs. Consider the given link for solution. I hope it would help you. cloud.google.com/storage/docs/lifecycleNeurology
P
11

It is not currently possible to set a per-object TTL, you can only configure a bucket-wide TTL that applies to all objects in the bucket by setting the buckets LifeCycle configuration. https://cloud.google.com/storage/docs/lifecycle

Setting a TTL of 14 days on the bucket via LifeCycle will not cause the bucket itself to be deleted after 14 days, instead it will cause each object uploaded to that bucket to be deleted 14 days after it was created.

Parol answered 10/8, 2017 at 17:7 Comment(2)
It wasn't clear to me in the documentation that it would only delete the objects within a bucket and not the bucket itself so I tested this out and it worked! For anyone wondering, you can enable the lifecycle on an existing bucket in the console: Storage > Browser or through gsutl: 1. Create a JSON lifecycle policy file - e.g. create a file name life.json: { "rule": [ { "action": {"type": "Delete"}, "condition": {"age": 14} } ] } 2. Set the policy: gsutil lifecycle set life.json gs://[BUCKET_NAME]Whitesell
Doc for setting this TTL lifecycle rule through TerraformWildee
T
1

You can do that by using the DaysSinceCustomTime rule in the bucket lifecycle configuration: https://cloud.google.com/storage/docs/lifecycle#dayssincecustomtime

blob.custom_time = pd.Timestamp('now', tz='UTC') + pd.offsets.Second(ttl)
#blob.patch()
blob.update() # they seem to have a bug with the custom_time setter, so using .update() instead of .patch()

If you do that and the DaysSinceCustomTime will be set for 1 day for example, the object would be deleted after ttl + 1 day.

Tiffanitiffanie answered 22/11, 2020 at 13:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.