kaise white
kaise white

Reputation: 87

How to configure CorsRule for CDK using python

I am trying to figure out the proper syntax for setting up cors on an s3 bucket using CDK (python). The class aws_s3.CorsRule requires 3 params (allowed_methods, allowed_origins, max_age=None). I am trying to specify the allowed_methods which takes in a list of methods but the bases is enum.Enum. So how do I create a list of these methods. This is what I have tried but it doesn't pass validation.

s3.Bucket(self, "StaticSiteBucket",
        bucket_name="replaceMeWithBucketName",
        versioned=True,
        removal_policy=core.RemovalPolicy.DESTROY,
        website_index_document="index.html",
        cors=s3.CorsRule(allowed_methods=[s3.HttpMethods.DELETE],allowed_origins=["*"],max_age=3000)
        )

The only thing Im focused on is the cors line:

cors=s3.CorsRule(allowed_methods=[s3.HttpMethods.DELETE],allowed_origins=["*"],max_age=3000)

Trying to read the documentation is like peeling an onion.

https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_s3/HttpMethods.html#aws_cdk.aws_s3.HttpMethods

I tried calling each one individually as you can see using s3.HttpMethods.DELETE but that fails when it tries to synthesize.

Upvotes: 1

Views: 1231

Answers (1)

alex9311
alex9311

Reputation: 1410

looks like you at least forgot to wrap the param you pass to cors as a list. I agree that the docs are a bit of a rabbit hole, but you can see the Bucket docs specifies the cors param as (Optional[List[CorsRule]])

This is mine:

from aws_cdk import core
from aws_cdk import aws_s3
from aws_cdk import aws_apigateway

aws_s3.Bucket(self,
    'my_bucket',
    bucket_name='my_bucket',
    removal_policy=core.RemovalPolicy.DESTROY,
    cors=[aws_s3.CorsRule(
        allowed_headers=["*"],
        allowed_methods=[aws_s3.HttpMethods.PUT],
        allowed_origins=["*"])
    ])

So yours should be:

cors=[s3.CorsRule(
    allowed_methods=[s3.HttpMethods.DELETE],
    allowed_origins=["*"],
    max_age=3000)]

Upvotes: 2

Related Questions