1. Academy
  2. Object Store

How to set bucket CORS configuration

Learn how to set CORS configuration on containers and buckets in the Fuga Object Store

 
CORS according to boto3.amazonaws.com:

Cross Origin Resource Sharing (CORS) enables client web applications in one domain to access resources in another domain. An S3 bucket can be configured to enable cross-origin requests. The configuration defines rules that specify the allowed origins, HTTP methods (GET, PUT, etc.), and other elements.

Prerequisites:

  • Fuga Cloud EC2 credentials
  • Python 3.6+
  • boto3 python package (tested with boto3 1.9.244 and botocore 1.12.244)

Fuga Cloud account

Create a new Python file named add-cors-configuration.py with the following content:

#!/usr/bin/env python3

import os
import sys
import json
from argparse import ArgumentParser
from urllib.parse import urlencode, quote_plus

import boto3

with open('credentials.json', 'r') as fd:
credentials = json.loads(fd.read())

def main():

parser = ArgumentParser(description='set bucket CORS configuration')
parser.add_argument('--bucket-name',
dest='bucket_name',
action='store',
required=True,
help='name of the bucket')
parser.add_argument('--cors-config',
dest='cors_config_path',
action='store',
required=True,
help='path to CORS configuration')
args = parser.parse_args()

s3 = boto3.client('s3',
endpoint_url=credentials.get('endpoint_url'),
aws_access_key_id=credentials.get('access_key'),
aws_secret_access_key=credentials.get('secret_key'),
)

with open(args.cors_config_path, 'r') as fd:
cors_configuration = json.loads(fd.read())

response = s3.put_bucket_cors(Bucket=args.bucket_name,
CORSConfiguration=cors_configuration)

response = s3.get_bucket_cors(Bucket=args.bucket_name)
print(json.dumps(response['CORSRules'], indent=2))


if __name__ == '__main__':
main()

 

Create a new JSON file named cors.json with the following content, update the contents to match your setup:

{
"CORSRules": [
{
"AllowedHeaders": [
"Authorization"
],
"AllowedMethods": [
"GET",
"PUT"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"GET",
"PUT"
],
"MaxAgeSeconds": 3000
}
]
}

 

Create a new JSON file named credentials.json with the following content, update the contents to match your setup, you can find the endpoints in my.fuga dashboard.

{
"access_key": "<your ec2 credential access>",
"secret_key": "<your ec2 credential secret>",
"endpoint_url": "<api_endpoints>"
}

Install required Python packages and run the script to set CORS configuration:

% pip install --user boto3
% python3.7 ./add_cors_configuration.py --bucket-name my-first-bucket --cors-config ./cors.json
{
"CORSRules": [
{
"AllowedHeaders": [
"Authorization"
],
"AllowedMethods": [
"GET",
"PUT"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": [
"GET",
"PUT"
],
"MaxAgeSeconds": 3000
}
]
}

 

For information and examples see boto3.amazonaws.com.