Created
March 17, 2023 13:51
-
-
Save zimathon/41a81f661ccbbce31fab83851cc76db9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def is_object_encrypted(s3_client, bucket_name, key): | |
response = s3_client.head_object(Bucket=bucket_name, Key=key) | |
return 'ServerSideEncryption' in response | |
def encrypt_objects(bucket_name, prefix, encryption_type): | |
s3_client = boto3.client('s3') | |
# List all objects under the specified prefix | |
objects = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=prefix) | |
# Iterate over the objects and encrypt each one if not already encrypted | |
for obj in objects['Contents']: | |
key = obj['Key'] | |
# Check if the object is already encrypted | |
if not is_object_encrypted(s3_client, bucket_name, key): | |
# Copy the object with the specified encryption type | |
copy_source = {'Bucket': bucket_name, 'Key': key} | |
s3_client.copy_object( | |
Bucket=bucket_name, | |
CopySource=copy_source, | |
Key=key, | |
ServerSideEncryption=encryption_type | |
) | |
print(f'Encrypted object: {key}') | |
else: | |
print(f'Object already encrypted: {key}') | |
if __name__ == '__main__': | |
bucket_name = 'your-bucket-name' | |
directory_prefix = 'your/directory/prefix/' | |
# Choose the encryption type: 'AES256' for SSE-S3 or 'aws:kms' for SSE-KMS | |
encryption_type = 'AES256' | |
encrypt_objects(bucket_name, directory_prefix, encryption_type) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment