How to Setup S3 Bucket CORS Configuration using CloudFormation

How to Setup S3 Bucket CORS Configuration using CloudFormation
Sharing is Caring:

How to Setup S3 Bucket CORS Configuration using CloudFormation

Few days ago, I wrote a post about how to create an S3 bucket using CloudFormation. Apart from the basic bucket creation, I covered some of the features like-

  • Versioning
  • Encryption
  • Preventing an object from becoming public etc.

You can find post here : How to Create an S3 Bucket using CloudFormation.

I didn’t cover CORS configuration in that post!!!

Now, please don’t be angry on me for that 😀 😀

To be honest, I thought that CORS is a huge topic in itself and it deserves a separate post altogether.

Therefore, here I am giving CORS it’s well deserved special attention 😀 😀

Okay?

Let’s go ahead !!!

I will give little bit of background regarding CORS and it’s significance in terms of S3 bucket.

If you are looking for the template right away , please head straight to YAML or JSON template section.

CORS and it’s significance in terms of an S3 bucket.

CORS stands for Cross-origin resource sharing. As the name says, it allows you to request a cross origin resource.

In simple terms, it allows you to request a resource such as an image or css from other domain. We will simplify it going further. Don’t worry 🙂

Before we understand CORS, first let’s try to understand cross-origin request.

What is Cross-origin request?

Can I give an example scenario?

Well, yes !!!

I am hosting my website at https://cloudkatha.com and I am trying to load an image from https://xyz.com. In this case my request for image qualifies to be a cross origin request.

By default, request from same origin is always allowed but any other domain is blocked by default and must be explicitly set and it’s for security reasons.

What is CORS?

CORS or Cross-Origin Resource Sharing is a mechanism to allow a web page to access resource hosted on a different domain in a controlled way.

Clients will allow only requests from the specific origins to the servers as per instructed by the servers.

Significance in terms of S3

You are trying to read an image from an S3 bucket with your origin xyz.com. If you have just created a bucket and hosted your images in the bucket. By default, there won’t be any CORS config on your bucket.

Result?

Your request to read images from the bucket will error out by saying request from origin is not allowed.

The Solution

As I already said, server which is S3 in this case can specify origins that can request images from the bucket.

You can configure your bucket to explicitly enable cross-origin requests from your domain/origin xyz.com

Template to Setup S3 Bucket CORS Configuration using CloudFormation : YAML

AWSTemplateFormatVersion: 2010-09-09
Description: This template creates a bucket with CORS configuration
Parameters:
  BucketName:
    Description: Name of Bucket
    Type: String
    Default: cloud-katha-cors-demo
Resources:
  DemoBucket:
    Type: 'AWS::S3::Bucket'
    Properties:
      BucketName: !Ref BucketName
      CorsConfiguration:
        CorsRules:
          - AllowedHeaders:
              - '*'
            AllowedMethods:
              - GET
              - PUT
              - POST
            AllowedOrigins:
              - '*'
            MaxAge: '3600'
Outputs:
  BucketName:
    Description: Output value
    Value: !Ref DemoBucket

Template to Setup S3 Bucket CORS Configuration using CloudFormation : JSON

{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "This template creates a bucket with CORS configuration",
    "Parameters": {
        "BucketName": {
            "Description": "Name of Bucket",
            "Type": "String",
            "Default": "cloud-katha-cors-demo"
        }
    },
    "Resources": {
        "DemoBucket": {
            "Type": "AWS::S3::Bucket",
            "Properties": {
                "BucketName": {
                    "Ref": "BucketName"
                },
                "CorsConfiguration": {
                    "CorsRules": [
                        {
                            "AllowedHeaders": [
                                "*"
                            ],
                            "AllowedMethods": [
                                "GET",
                                "PUT",
                                "POST"
                            ],
                            "AllowedOrigins": [
                                "*"
                            ],
                            "MaxAge": "3600"
                        }
                    ]
                }
            }
        }
    },
    "Outputs": {
        "BucketName": {
            "Description": "Output value",
            "Value": {
                "Ref": "DemoBucket"
            }
        }
    }
}

Please note that, I have used ‘*’ as AllowedOrigins and it will allow all the origin to be able to access image.

AllowedOrigins:
  - '*'

But, for security reasons it’s good to use specific domain instead of ‘*’ to restrict the resource usage for example-

AllowedOrigins:
  - 'https://cloudkatha.com'

For all the other rules like on AllowedMethods and AllowedHeaders use the same concept of least privilege.

If you have more then one, you can list them like below.

AllowedMethods:
  - GET
  - PUT
  - POST

Now, we have the template so let’s go and create the stack using the above template.

Steps to setup CORS on an S3 bucket using CloudFormation

Grab the YAML or JSON template from above and change the parameter value for BucketName as per your requirement.

Note: Make sure to provide a unique name because S3 bucket name is unique globally.

Save the template with .yml or .json as per the choice of template and follow below steps.

  • Login to AWS Management Console, navigate to CloudFormation and click on Create stack
  • Click on “Upload a template file”, upload your saved .yml  or .json file and click Next
  • Enter the stack name and click on Next. In configuration, keep everything as default and click on Next.
  • In the events tab of stack, you can view the status.
  • Once stack is successfully created, you can go to your bucket and verifiy CORS config

How to verify CORS Configuration in an S3 Bucket?

Open S3 console and from the bucket list, click on your bucket name to open your bucket.

Once you are inside the bucket, click on Permissions tab. Scroll down to CORS section or straight to the bottom of page.

Because, as of now Cross-origin resource sharing (CORS) section is last one in permissions tab.

You will see something like below. Isn’t this same setting which you setup from your CloudFormation template.

How to Setup S3 Bucket CORS Configuration using CloudFormation

Conclusion

Finally, let’s summarize what we did in this post.

  • We learnt that CORS lets us use cross origin resources such as images or css from other domain in a secure manner
  • We can set up CORS on an S3 bucket to able to request an image hosted in a s3 bucket.
  • We learnt how to setup CORS configuration on a bucket using CloudFormation
  • Finally we learnt to verify the config in S3 console.

Enjoyed the content?

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Subscribe to our newsletter below to get awesome AWS learning materials delivered straight to your inbox.

Don’t forget to motivate me by-

Suggested Read:

Sharing is Caring:

2 thoughts on “How to Setup S3 Bucket CORS Configuration using CloudFormation

Leave a Reply

Your email address will not be published. Required fields are marked *