How to Setup S3 Bucket CORS Configuration using CloudFormation

How to Setup S3 Bucket CORS Configuration using CloudFormation

How to Setup S3 Bucket CORS Configuration using CloudFormation

A 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.

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

Now, please don’t be angry with 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 its well deserved special attention ๐Ÿ˜€ ๐Ÿ˜€

Okay?

Let’s go ahead !!!

I will give a little bit of background regarding CORS and its significance in terms of the S3 bucket.

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

CORS and its 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 another domain. We will simplify it going further. Don’t worry ๐Ÿ™‚

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

What is a 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 an image qualifies to be a cross-origin request.

By default, request from the 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 resources 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 of CORS 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 a request from the origin is not allowed.

The Solution

As I already said, the 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 Example to Setup S3 Bucket CORS Configuration using CloudFormation in 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 Example to Setup S3 Bucket CORS Configuration using CloudFormation in 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 origins to be able to access the image.

AllowedOrigins:
  - '*'

But, for security reasons, it’s good to use a specific domain instead of ‘*’ to restrict 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 than one, you can list them 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 the 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 the configuration, keep everything as default and click on Next.
  • In the events tab of the stack, you can view the status.
  • Once the stack is successfully created, you can go to your bucket and verify CORS config

Note: You can also Deploy a CloudFormation Template using AWS CLI

How to verify CORS Configuration in an S3 Bucket?

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

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

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

You will see something like this below. Isn’t this the same setting which you set up in 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 domains in a secure manner
  • We can set up CORS on an S3 bucket to be 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 the S3 console.

Enjoyed the content?

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:

5 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 *