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

Viewed 5026

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

2 Answers

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.

Related