Introduction
Imagine you accidentally delete a critical file in your S3 bucket. Without versioning, it’s gone forever. With versioning enabled, you can restore the file in seconds. In this article, we'll learn how to enable versioning and manage file versions in Amazon S3 using an EC2 instance.
Why is this useful?
- If you accidentally delete or overwrite a file, you can restore a previous version.
- You can track changes made to important files.
1. Enable Versioning on an S3 Bucket
- Select your S3 bucket
- Click on Properties
![Properties tab]()
- Scroll down to Bucket Versioning and click on edit.
![Edit]()
- Click Enable Versioning and Save.
![Save changes]()
2. Upload a File to the S3 Bucket from EC2
3. Upload a New Version of the File
4. View File Versions in S3
To see all the versions of a specific file in your S3 bucket, you can use the aws s3api list-object-versions command. This will list all versions of the file, including their version IDs.
aws s3api list-object-versions --bucket my-puma-bucket05 --prefix myfile.txt
![Difference]()
When you run this command, it will return a list of all versions of myfile.txt
in your my-puma-bucket05
bucket, along with details like version IDs and the last modified time.
5. Restore or Delete a Specific Version
Explanation
- --bucket my-puma-bucket05: Specifies the name of your S3 bucket.
- --key myfile.txt: Specifies the file name in the S3 bucket.
- --version-id z96ncmxYauLRgd_.jTlx6h0aGIIMR5Ch: Specify the version ID of the file you want to delete (the second version from your output).
6. Restore a previous version
Download an old version using its version ID.
aws s3api get-object --bucket my-puma-bucket05 --key myfile.txt --version-id C7iMMbiSsLM8lllA4gMf.HdthtsZT2oT old-myfile.txt
![Get Object]()
This will download the file as old-myfile.txt in your EC2 instance.
Conclusion
Amazon S3 versioning ensures data protection by keeping track of every change, allowing you to restore, recover, or delete file versions easily. Whether you're preventing accidental data loss or maintaining a backup, this feature is essential for efficient cloud storage management.