Use CloudFront Proxy to access Lambda APIs

In case it would help anyone, I’ve managed to configure what I needed, with much help of this json from the awsm-cloudfront project:

At serverless.yml I’ve added
resources:
Resources: ${file(cloudformation-resources.json)}

and the json files consists the following:

{
    "CloudFrontDistribution": {
        "Type" : "AWS::CloudFront::Distribution",
        "Properties" : {
            "DistributionConfig" : {
            "DefaultRootObject" : "index.html",
            "Enabled" : true,
            "DefaultCacheBehavior" : {
                "AllowedMethods" : ["GET", "HEAD"],
                "CachedMethods" : ["HEAD", "GET"],
                "ForwardedValues" : {
                    "QueryString" : true
                },
                "MinTTL" : "0",
                "TargetOriginId" : "MY_SERVICE_serverlessdeploymentbucket-ID",
                "ViewerProtocolPolicy" : "allow-all"
            },
            "CacheBehaviors" : [
                {
                    "AllowedMethods" : ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"],
                    "CachedMethods" : ["HEAD", "GET"],
                    "ForwardedValues" : {
                    "QueryString" : true
                    },
                    "MinTTL" : "0",
                    "PathPattern" : "*",
                    "TargetOriginId" : "MY_FUNCTION-api-gateway",
                    "ViewerProtocolPolicy" : "allow-all"
                }
            ],
            "Origins" : [
                {
                "CustomOriginConfig" : {
                    "HTTPSPort" : "443",
                    "OriginProtocolPolicy" : "https-only"
                },
                "DomainName" : "SOMETHING.execute-api.REGION.amazonaws.com",
                "Id" : "MY_FUNCTION-api-gateway",
                "OriginPath" : ""
                },
                {
                "DomainName" : "MY_SERVICE_serverlessdeploymentbucket-ID.s3.amazonaws.com",
                "Id" : "MY_SERVICE_serverlessdeploymentbucket-ID",
                "OriginPath" : "",
                "S3OriginConfig" : {}
                }
            ],
            "PriceClass" : "PriceClass_100"
            }
        }
    }
}

The only bummer right now is that I have to specify the s3 bucket name and the api gateway endpoint, so it can be created only after these resources were deployed. If anyone has an idea of how to connect these to the resources I’m going to deploy in the new environment and do not exist yet, I’ll be happy to hear.

1 Like