Skip to content

Instantly share code, notes, and snippets.

@t04glovern
Created April 30, 2024 03:50
Show Gist options
  • Save t04glovern/7aff7e806c08324671e4f99bcb2ac3db to your computer and use it in GitHub Desktop.
Save t04glovern/7aff7e806c08324671e4f99bcb2ac3db to your computer and use it in GitHub Desktop.
Gist showing how to use S3 access points with S3 pre-signed URLs
provider "aws" {
region = "us-west-2"
}
resource "aws_s3_bucket" "my_bucket" {
bucket = "unique-bucket-name"
}
resource "aws_s3_access_point" "my_access_point" {
name = "myaccesspoint"
bucket = aws_s3_bucket.my_bucket.id
}
output "bucket_name" {
value = aws_s3_bucket.my_bucket.bucket
}
output "access_point_arn" {
value = aws_s3_access_point.my_access_point.arn
}
import boto3
from botocore.exceptions import NoCredentialsError
import requests
def create_presigned_url(access_point_arn, object_key, expiration=3600):
s3_client = boto3.client('s3')
try:
response = s3_client.generate_presigned_url('put_object',
Params={'Bucket': access_point_arn,
'Key': object_key},
ExpiresIn=expiration)
return response
except NoCredentialsError:
return "Credentials not available"
def upload_file_to_s3(presigned_url, file_path):
# Open the file in binary mode
with open(file_path, 'rb') as file:
files = {'file': file}
# Put the file using the presigned URL
response = requests.put(presigned_url, data=file)
# Check if the upload was successful
if response.status_code == 200:
print("File uploaded successfully.")
else:
print(f"Failed to upload file. Status code: {response.status_code} Response: {response.text}")
# Example usage
access_point_arn = 'arn:aws:s3:us-west-2:01234567890:accesspoint/myaccesspoint'
object_key = 'test-file.txt'
url = create_presigned_url(access_point_arn, object_key)
upload_file_to_s3(url, object_key)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment