As part of some work I’ve been doing with Amazon Web Services, I needed to enable object versioning on all S3 buckets in an account.
However, I had three issues that I needed to accommodate for:
- There were a sufficient number of S3 buckets that enabling versioning via the S3 web console would be inconvenient.
- Some of the S3 buckets in the list already had object versioning enabled, while others in the list did not.
- I had forgotten which ones already had versioning enabled, so I’d have to check each one.
To address all three issues, I’ve written a script that uses the aws command line tool to detect which S3 buckets do not have object versioning enabled and enable it on the detected S3 buckets. For more details, see below the jump.
The script is designed to do the following:
- Check the object versioning status of all S3 buckets associated with an AWS account
- Enable object versioning on any S3 buckets where object versioning is not enabled.
It does this by using the following command to download and format a list of all the S3 buckets associated with a particular AWS account:
aws s3api list-buckets --query 'Buckets[*].Name' | sed -e 's/[][]//g' -e 's/"//g' -e 's/,//g' -e '/^$/d' -e 's/^[ \t]*//;s/[ \t]*$//'
Once it has the list, the script loops through each bucket individually to check if the S3 bucket’s object versioning is reporting the following status:
Enabled
- If the S3 bucket is reporting an Enabled status, the following output is displayed:
The Bucket_Name_Goes_Here S3 bucket has object versioning enabled.
- If the S3 bucket reports any other status than Enabled, object versioning is enabled and the following output is displayed:
The Bucket_Name_Goes_Here S3 bucket does not have object versioning enabled. Enabling object versioning on the Bucket_Name_Goes_Here S3 bucket.
The script is available below. It is also available on GitHub via the following link:
https://github.com/rtrouton/aws_scripts/tree/master/enable_s3_versioning_for_AWS_S3_buckets