Cloudfront CloudFormation - amazon-web-services

We have option to get the value of DomainName in cloudformation template while creating a CloudFront Distribution using Fn::GetAtt function. But I could not find anywhere that how we get Origin's Id and DefaultCacheBehaviour's TargetOriginId dynamically?
Can I just use Ref to my S3 and ELB?
This is my code, I have used some parameters also and changed the Cloudfront code as well. Please check it once whether it is correct or not.
And it is throwing me an error called "Property validation failure: [Encountered unsupported properties in {/DistributionConfig/Origins/1/S3OriginConfig}: [HTTPSPort, HTTPPort, OriginProtocolPolicy]]"
{
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters": {
"ClientName": {
"Type": "String",
"Description": "Name of the Client"
},
"EnvName": {
"Type": "String",
"Description": "Name of the Environment"
}
},
"Resources": {
"distd2v0l803ay8odocloudfrontnet": {
"Type": "AWS::CloudFront::Distribution",
"Properties": {
"DistributionConfig": {
"Enabled": true,
"DefaultRootObject": "index.html",
"PriceClass": "PriceClass_All",
"CacheBehaviors": [
{
"TargetOriginId": {
"Ref": "elbhtlbetaelb"
},
"PathPattern": "/app*",
"ViewerProtocolPolicy": "allow-all",
"MinTTL": 0,
"AllowedMethods": [
"HEAD",
"DELETE",
"POST",
"GET",
"OPTIONS",
"PUT",
"PATCH"
],
"CachedMethods": [
"HEAD",
"GET"
],
"ForwardedValues": {
"QueryString": true,
"Cookies": {
"Forward": "all"
}
}
},
{
"TargetOriginId": {
"Ref": "elbhtlbetaelb"
},
"PathPattern": "/api*",
"ViewerProtocolPolicy": "allow-all",
"MinTTL": 0,
"AllowedMethods": [
"HEAD",
"DELETE",
"POST",
"GET",
"OPTIONS",
"PUT",
"PATCH"
],
"CachedMethods": [
"HEAD",
"GET"
],
"ForwardedValues": {
"QueryString": true,
"Cookies": {
"Forward": "all"
}
}
}
],
"DefaultCacheBehavior": {
"TargetOriginId": {
"Ref": "s3htlbeta"
},
"ViewerProtocolPolicy": "allow-all",
"MinTTL": 0,
"AllowedMethods": [
"HEAD",
"DELETE",
"POST",
"GET",
"OPTIONS",
"PUT",
"PATCH"
],
"CachedMethods": [
"HEAD",
"GET"
],
"ForwardedValues": {
"Cookies": {
"Forward": "none"
}
}
},
"Origins": [
{
"DomainName": {
"Fn::GetAtt": [
"s3htlbeta",
"DomainName"
]
},
"Id": {
"Ref": "s3htlbeta"
},
"S3OriginConfig": {
"OriginAccessIdentity": "origin-access-identity/cloudfront/EYD1QGO9CUDA2"
}
},
{
"DomainName": {
"Fn::GetAtt": [
"elbhtlbetaelb",
"DNSName"
]
},
"Id": {
"Ref": "elbhtlbetaelb"
},
"S3OriginConfig": {
"HTTPPort": "80",
"HTTPSPort": "443",
"OriginProtocolPolicy": "http-only"
}
}
],
"Restrictions": {
"GeoRestriction": {
"RestrictionType": "none",
"Locations": []
}
},
"ViewerCertificate": {
"CloudFrontDefaultCertificate": "true",
"MinimumProtocolVersion": "TLSv1"
}
}
}
},
"s3htlbeta": {
"Type": "AWS::S3::Bucket",
"Properties": {
"AccessControl": "Private",
"VersioningConfiguration": {
"Status": "Suspended"
}
}
}
},
"Description": "xxx-beta cloudformation template"
}

The DistributionConfig/Origins/ID field should just be a text name, it doesn't need to reference anything.
ie. Set DistributionConfig/Origins/ID to a string e.g. 'MyOriginBucket'
Then your CacheBehaviour TargetOriginId is also a string set to 'MyOriginBucket'
The only Ref required to your new bucket is in Origins/DomainName.
The purpose of the TargetOriginId is to point to the origin ID that you specified in the list of Origins, not point to the bucket name.

Related

HTTP API Gateway trailing slash

I have an HTTP API Gateway which has a custom domain with mappings like https://api.example.com/myapi and one route POST / which triggers Lambda.
Problem is that https://api.example.com/myapi throws {"message": "Not Found"} and it working only with trailing slash https://api.example.com/myapi/.
How can I make it so it works with and without slash or in the worst case just without slash?
Here is CloudFormation for reference:
{
"Resources": {
"Webhoook6917ABA8": {
"Type": "AWS::Lambda::Function",
"Properties": {...}
},
"DomainNameEC95A6E9": {
"Type": "AWS::ApiGatewayV2::DomainName",
"Properties": {
"DomainName": "api.example.com",
"DomainNameConfigurations": [
{
"CertificateArn": "arn:***",
"EndpointType": "REGIONAL"
}
]
}
},
"ApiA2E3A7D3": {
"Type": "AWS::ApiGatewayV2::Api",
"Properties": {
"Name": "Api",
"ProtocolType": "HTTP"
}
},
"ApiDefaultStageE05BC5D1": {
"Type": "AWS::ApiGatewayV2::Stage",
"Properties": {
"ApiId": {
"Ref": "ApiA2E3A7D3"
},
"StageName": "$default",
"AutoDeploy": true
},
"DependsOn": [
"DomainNameEC95A6E9"
]
},
"ApiDefaultStageDomainName710CA621": {
"Type": "AWS::ApiGatewayV2::ApiMapping",
"Properties": {
"ApiId": {
"Ref": "ApiA2E3A7D3"
},
"DomainName": {
"Ref": "DomainNameEC95A6E9"
},
"Stage": "$default",
"ApiMappingKey": "myapi"
},
"DependsOn": [
"DomainNameEC95A6E9",
"ApiDefaultStageE05BC5D1"
]
},
"ApiPOSTHttpIntegrationcc27d9637eb8fbf5d8b41e5d3f4f4743D2E9B97B": {
"Type": "AWS::ApiGatewayV2::Integration",
"Properties": {
"ApiId": {
"Ref": "ApiA2E3A7D3"
},
"IntegrationType": "AWS_PROXY",
"IntegrationUri": {
"Fn::GetAtt": [
"Webhoook6917ABA8",
"Arn"
]
},
"PayloadFormatVersion": "2.0"
}
},
"ApiPOSTE756F840": {
"Type": "AWS::ApiGatewayV2::Route",
"Properties": {
"ApiId": {
"Ref": "ApiA2E3A7D3"
},
"RouteKey": "POST /",
"AuthorizationType": "NONE",
"Target": {
"Fn::Join": [
"",
[
"integrations/",
{
"Ref": "ApiPOSTHttpIntegrationcc27d9637eb8fbf5d8b41e5d3f4f4743D2E9B97B"
}
]
]
}
}
}
}
}

How to enable CORS configuration in WSO2 for a specific API by using REST API?

I am creating and publishing APIs using WSO2 REST APIs and not from its UI because i have hundreds of WSO2 APIs to manage. I use swagger file(in json format) to configure all the details about my API and then publish this swagger file using curl command. I want to enable CORS configuration for my WSO2 APIs.
The documentation provided for WSO2 APIs provides information only about enabling CORS config via UI. Here is the link.
I could not find any info as to how i can enable it by any means other than directly from its UI. I have tried adding the following field in the API's swagger file but this change is not reflected in the published API.
"CORSConfiguration": {
"Enabled": "true",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
"Access-Control-Allow-Headers": "authorization,Access-Control-Allow-Origin,Content-Type,SOAPAction",
"Access-Control-Allow-Credentials": "false"
}
Any help to enable the CORS configuration for a particular API will be appreciated. Thanks :)
CORS information should go in the API create/update payload like this.
"corsConfiguration": {
"accessControlAllowOrigins": ["*"],
"accessControlAllowHeaders": [
"authorization",
"Access-Control-Allow-Origin",
"Content-Type",
"SOAPAction"
],
"accessControlAllowMethods": [
"GET",
"PUT",
"POST",
"DELETE",
"PATCH",
"OPTIONS"
],
"accessControlAllowCredentials": false,
"corsConfigurationEnabled": false
}
See the sample payload in [1].
[1] https://docs.wso2.com/display/AM260/apidocs/publisher/#!/operations#APIIndividual#apisPost
#Bee, here is what i tried to do.
{
"swagger": "2.0",
"info": {
"description": "Registration Type Master",
"version": "1.0",
"title": "Test_Entity_Master_API",
"termsOfService": "urn:tos",
"contact": {"name":"RD"},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0"
}
},
"host": "http://sampleurl.com/",
"basePath": "/samplemethod",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/regtype/createregtype": {
"post": {
"summary": "Create reg type entry",
"tags": [
"Registration Type Master"
],
"deprecated": false,
"produces": [
"application/json"
],
"parameters": [
{
"name": "Body",
"in": "body",
"required": true,
"description": "",
"schema": {
"type": "object",
"properties": {
"key": {
"type": "string"
},
"value": {
"type": "string"
}
}
}
}
],
"responses": {
"200": {
"description": "",
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"error": {
"type": "boolean",
"default": false
},
"message": {
"type": "string"
},
"data": {
"type": "object"
}
}
}
},
"500": {
"description": "",
"schema": {
"type": "object",
"properties": {
"success": {
"type": "boolean",
"default": false
},
"error": {
"type": "boolean"
},
"message": {
"type": "string"
},
"data": {
"type": "object"
}
}
}
}
}
}
}
},
"tags": [
{
"name": "entity-master-controller",
"description": "Entity Master Controller"
}
],
"corsConfiguration": {
"accessControlAllowOrigins": ["https://dtdevsso.ril.com"],
"accessControlAllowHeaders":[
"authorization",
"Access-Control-Allow-Origin",
"Content-Type",
"SOAPAction"
],
"accessControlAllowMethods":[
"GET",
"PUT",
"POST",
"DELETE",
"PATCH",
"OPTIONS"
],
"accessControlAllowCredentials": "true",
"corsConfigurationEnabled": "true"
}
}
In this swagger file, inspite of adding the CORS payload, it is not reflected after publishing the API through the swagger file.
To setup CORS support you must first define an OPTIONS method in your resource that returns the required headers.
All paths in swagger need a cors option chunk. this is the chunk.
"/users":
{
"options": {
"summary": "CORS support",
"description": "Enable CORS by returning correct headers\n",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"CORS"
],
"x-amazon-apigateway-integration": {
"type": "mock",
"requestTemplates": {
"application/json": "{\n \"statusCode\" : 200\n}\n"
},
"responses": {
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'",
"method.response.header.Access-Control-Allow-Methods": "'*'",
"method.response.header.Access-Control-Allow-Origin": "'*'"
},
"responseTemplates": {
"application/json": "{}\n"
}
}
}
},
"responses": {
"200": {
"description": "Default response for CORS method",
"headers": {
"Access-Control-Allow-Headers": {
"type": "string"
},
"Access-Control-Allow-Methods": {
"type": "string"
},
"Access-Control-Allow-Origin": {
"type": "string"
}
}
}
}
}
}
For more details you can visit this link
I used the following payload for creating/updating an API in WSO2.
It is working perfectly. Sorry for the delayed update on this.
{
"name": "%apiName%",
"description": "%apiDescription%",
"context": "/%apiName%",
"version": "%apiVersion%",
"provider": "%apiProvider%",
"apiDefinition": "%swaggger_extended.json% // Input swagger file",
"wsdlUri": null,
"status": "CREATED",
"responseCaching": "Disabled",
"cacheTimeout": 300,
"destinationStatsEnabled": false,
"isDefaultVersion": false,
"type": "HTTP",
"transport": [
"http",
"https"
],
"tags": ["%apiTags%"],
"tiers": ["%apiTiersCollection%"],
"visibility": "%apiVisibility%",
"visibleRoles": [],
"endpointConfig": "%endPointConfig%",
"gatewayEnvironments": "Production and Sandbox",
"subscriptionAvailability": null,
"subscriptionAvailableTenants": [],
"businessInformation": {
"businessOwnerEmail": "%BizOwnerName#ril.com%",
"technicalOwnerEmail": "%TechOwnerName#ril.com%",
"technicalOwner": "%TechOwnerName%",
"businessOwner": "%BizOwnerName%"
},
"corsConfiguration": {
"accessControlAllowOrigins": ["originURL"],
"accessControlAllowHeaders": [
"authorization",
"Access-Control-Allow-Origin",
"Content-Type",
"SOAPAction"
],
"accessControlAllowMethods": [
"GET",
"PUT",
"POST",
"DELETE",
"PATCH",
"OPTIONS"
],
"accessControlAllowCredentials": false,
"corsConfigurationEnabled": true
}
}

AWS APIGateway CloudFormation specify Api Key required for method?

I have the below CloudFormation template which creates my API Gateway (backed by Lambda). I want to enable API Keys as a requirement for one or more of these methods. I have successfully created API Keys, Usage Plans and the association between the two, but can't figure out how to actually enable the 'requires API Key' property for some of the methods. The documentation from AWS specifies an 'ApiKeyRequired' property as a part of the AWS::ApiGateway::Method component, but my CF template doesn't have or use this component? I'm unsure how to use it considering I've never required it before?
My template is below:
"ServerlessRestApi": {
"Type": "AWS::ApiGateway::RestApi",
"Properties": {
"Description":"This is a placeholder for the description of this web api",
"ApiKeySourceType":"HEADER",
"Body": {
"info": {
"version": "1.0",
"title": {
"Ref": "AWS::StackName"
}
},
"paths": {
"/list/tables": {
"get": {
"x-amazon-apigateway-integration": {
"httpMethod": "POST",
"type": "aws_proxy",
"uri": {
"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetTableList.Arn}/invocations"
}
},
"security": [
{
"api_key": []
}
],
"responses": {}
}
},
"/list/columns/{tableid}": {
"get": {
"x-amazon-apigateway-integration": {
"httpMethod": "POST",
"type": "aws_proxy",
"uri": {
"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetColumnList.Arn}/invocations"
}
},
"responses": {}
}
},
"datagw/general/table/get/{tableid}": {
"get": {
"x-amazon-apigateway-integration": {
"httpMethod": "POST",
"type": "aws_proxy",
"uri": {
"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetTableResponse.Arn}/invocations"
}
},
"responses": {}
}
},
"/": {
"get": {
"x-amazon-apigateway-integration": {
"httpMethod": "POST",
"type": "aws_proxy",
"uri": {
"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Get.Arn}/invocations"
}
},
"responses": {}
}
},
"/tables/{tableid}/{columnid}": {
"get": {
"x-amazon-apigateway-integration": {
"httpMethod": "POST",
"type": "aws_proxy",
"uri": {
"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${GetTableBasic.Arn}/invocations"
}
},
"responses": {}
}
},
"securityDefinitions": {
"type": "api_key",
"name": "x-api-key",
"in": "header"
}
},
"swagger": "2.0"
}
}
},
I think adding security under each path and then securityDefinitions under paths would work.
"paths": {
"/list/tables": {
"get": {
"x-amazon-apigateway-integration": {
"httpMethod": "POST",
"type": "aws_proxy",
"uri": {
"Fn::Sub": "arn:aws:apigateway:${AWS::Region}:lambda:path/2015-
03-31/functions/${GetTableList.Arn}/invocations"
}
},
"security": [
{
"api_key": []
}
]
}
}
},
"securityDefinitions": {
"type": "api_key",
"name": "x-api-key",
"in": "header"
}
I ran into the same issue and resolved it by abandoning the use of the Body property in the AWS::ApiGateway::RestApi using:
"ServerlessRestApi": {
"Type": "AWS::ApiGateway::RestApi",
"DependsOn": "AspNetCoreFunction",
"Properties": {
"Description":"My Api Gateway",
"ApiKeySourceType" : "HEADER",
"EndpointConfiguration" : { "Types" : [ "REGIONAL" ]}
}
},
Then, I created a proxy resource. In your case, you would create a resource for each of your paths. Where I have, "{proxy+}", you would have "/list/tables."
"ProxyResource": {
"Type": "AWS::ApiGateway::Resource",
"Properties": {
"RestApiId": {
"Ref": "ServerlessRestApi"
},
"ParentId": {
"Fn::GetAtt": [
"ServerlessRestApi",
"RootResourceId"
]
},
"PathPart": "{proxy+}"
}
},
Finally, I was able to define an AWS::ApiGateway::Method then enforce usage an API key:
"CoreApiPostMethod":
{
"Type": "AWS::ApiGateway::Method",
"DependsOn" : ["AspNetCoreFunction", "ServerlessRestApi"],
"Properties":
{
"AuthorizationType" :"NONE",
"OperationName" : "My API Post Request",
"ApiKeyRequired" : true,
"ResourceId": { "Ref": "ProxyResource" },
"RestApiId": {
"Ref": "ServerlessRestApi"
},
"HttpMethod" : "POST",
"Integration" : {
"ConnectionType" : "INTERNET",
"IntegrationHttpMethod" : "POST",
"Type" : "AWS_PROXY",
"Uri" : {
"Fn::Sub":"arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${AspNetCoreFunction.Arn}/invocations"
}
}
}
},
And then follow the same pattern for the other HTTP methods. It's more verbose than the original configuration, but it does give you more control over the method configuration.
Late to the party.
"x-amazon-apigateway-api-key-source" : "HEADER",
And
"securityDefinitions": {
"<SOME_NAME>": {
"type": "apiKey",
"name": "x-api-key",
"in": "header"
}
}
And
"security" : [{
"<SOME_NAME>" : []
}]
So a possible working solution could be
"Body": {
"swagger": "2.0",
"info": {
"version": "2017-01-27T21:44:58Z",
"title": {"Ref": "AWS::StackName"}
},
"basePath": "/bbd",
"x-amazon-apigateway-api-key-source" : "HEADER",
"schemes": [
"https"
],
"paths": {
"/{proxy+}": {
"x-amazon-apigateway-any-method": {
"produces": [
"application/json"
],
"parameters": [
{
"name": "proxy",
"in": "path",
"required": true,
"type": "string"
}
],
"security" : [{
"bbd" : []
}],
"responses": {},
"x-amazon-apigateway-integration": {
"responses": {
"default": {
"statusCode": "200"
}
},
"uri": "<URL>",
"passthroughBehavior": "when_no_match",
"httpMethod": "POST",
"cacheNamespace": "xh7gp9",
"cacheKeyParameters": [
"method.request.path.proxy"
],
"contentHandling": "CONVERT_TO_TEXT",
"type": "aws_proxy"
}
}
}
},
"securityDefinitions": {
"bbd": {
"type": "apiKey",
"name": "x-api-key",
"in": "header"
}
}
}
Complete guide here. This guide provides a basic setup for enabling API keys for any API Gateway methods.
Use AWS::Serverless::Api for defining your API. It supports an Auth attribute which has an attribute named ApiKeyRequired. Set this to true.
Following code snippet from the above guide should do.
AuthApiGateway:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
ApiKeyRequired: 'true' # This makes passing ApiKey mandatory
DefinitionBody:
swagger: '2.0'
info: ...
"security" : [{
"myKey" : []
}],
"myKey": {
"type": "apiKey",
"name": "x-api-key",
"in": "header"
},
Adding security element in body and myKey element in securityDefinitions worked for me.

AWS Cloud Formation template fails with Invalid mapping expression parameter specified

I am working on an AWS Cloud Formation template for an endpoint with a path like /user/{uid}/cart. I need to create an integration with an HTTP host. I've been attempting to map {uid} into the Integration Request URL Path Parameters like so:
"x-amazon-apigateway-integration": {
"uri": "http://${stageVariables.httpHost}/user/{uid}/cart",
"contentHandling": "CONVERT_TO_TEXT",
"timeoutInMillis": 29000,
"connectionType": "INTERNET",
"httpMethod": "PUT",
"passthroughBehavior": "WHEN_NO_MATCH",
"type": "HTTP_PROXY",
"requestParameters": {
"integration.request.path.uid" : "method.request.path.uid"
}...
I keep getting this error and I'm not sure what I'm doing wrong.
Errors found during import: Unable to put integration on 'PUT' for resource at path '/user/{uid}/cart': Invalid mapping expression specified: Validation Result: warnings : [], errors : [Invalid mapping expression parameter specified: method.request.path.uid]
Here's the full template
{
"Parameters": {
"AccessControlAllowOrigin": {
"Type": "String",
"Default": "*"
}
},
"Resources": {
"ConfigApi": {
"Type": "AWS::ApiGateway::RestApi",
"Properties": {
"Body": {
"swagger": "2.0",
"tags": [
{
"name": "users",
"description": "secure user calls"
}
],
"schemes": [
"https"
],
"paths": {
"/user/{uid}/cart": {
"parameters": [
{
"name": "uid",
"in": "path",
"description": "user id",
"required": true,
"type": "string",
"format": "uuid"
}
],
"put": {
"tags": [
"users",
"cart"
],
"summary": "When called, this endpoint completes the user cart and puts their cart into their library",
"operationId": "completeusercart",
"description": "Completes the user cart\n",
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "the user identifier",
"headers": {
"Access-Control-Allow-Origin": {
"type": "string"
},
"Access-Control-Allow-Headers": {
"type": "string"
}
},
"schema": {
"type": "string"
}
}
},
"x-amazon-apigateway-integration": {
"uri": "http://${stageVariables.httpHost}/user/{uid}/cart",
"contentHandling": "CONVERT_TO_TEXT",
"timeoutInMillis": 29000,
"connectionType": "INTERNET",
"httpMethod": "PUT",
"passthroughBehavior": "WHEN_NO_MATCH",
"type": "HTTP_PROXY",
"requestParameters": {
"integration.request.path.uid" : "method.request.path.uid"
},
"responses": {
"default": {
"responseModels": {
"application/json": "Empty"
},
"responseParameters": {
"method.response.header.Access-Control-Allow-Origin": {
"Fn::Sub": "'${AccessControlAllowOrigin}'"
},
"method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
},
"statusCode": "200"
}
}
}
},
"options": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"responses": {
"200": {
"description": "200 response",
"schema": {
"$ref": "#/definitions/Empty"
},
"headers": {
"Access-Control-Allow-Origin": {
"type": "string"
},
"Access-Control-Allow-Methods": {
"type": "string"
},
"Access-Control-Allow-Headers": {
"type": "string"
}
}
}
},
"x-amazon-apigateway-integration": {
"httpMethod": "OPTIONS",
"passthroughBehavior": "WHEN_NO_MATCH",
"requestTemplates": {
"application/json": "{\"statusCode\": 200}"
},
"type": "MOCK",
"timeoutInMillis": 29000,
"responses": {
"2\\d{2}": {
"responseParameters": {
"method.response.header.Access-Control-Allow-Origin": {
"Fn::Sub": "'${AccessControlAllowOrigin}'"
},
"method.response.header.Access-Control-Allow-Methods": "'PUT,OPTIONS'",
"method.response.header.Access-Control-Allow-Headers": "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
},
"statusCode": "200"
},
"4\\d{2}": {
"statusCode": "403"
},
"5\\d{2}": {
"statusCode": "403"
}
}
}
}
}
},
"definitions": {
"Empty": {
"type": "object",
"title": "Empty Schema"
}
}
}
}
},
"ConfigApiStage": {
"Type": "AWS::ApiGateway::Stage",
"Properties": {
"DeploymentId": {
"Ref": "ApiDeployment"
},
"MethodSettings": [
{
"DataTraceEnabled": true,
"HttpMethod": "*",
"LoggingLevel": "INFO",
"ResourcePath": "/*"
}
],
"RestApiId": {
"Ref": "ConfigApi"
},
"Variables": {
"httpHost": "0.0.0.0"
},
"StageName": "LATEST"
}
},
"ApiDeployment": {
"Type": "AWS::ApiGateway::Deployment",
"Properties": {
"RestApiId": {
"Ref": "ConfigApi"
},
"StageName": "DummyStage"
}
}
}
}
Thanks for your help!
The issue was the placement of the parameters. These need to be under the PUT rather than under the path.
"paths": {
"/user/{uid}/cart": {
"put": {
"tags": [
"users",
"cart"
],
"parameters": [
{
"name": "uid",
"in": "path",
"description": "user id",
"required": true,
"type": "string",
"format": "uuid"
}
],...

Connecting a SSL cert to a CloudFront CDN in CloudFormation

So far I have this to create the resources.
"staticFileBucketPolicy": {
"Type": "AWS::S3::BucketPolicy",
"DependsOn": "staticFileBucket",
"Properties": {
"Bucket": { "Ref": "staticFileBucket" },
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Sid": "AddPerm",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": { "Fn::Join" : ["", ["arn:aws:s3:::", { "Ref" : "staticFileBucket" } , "/*" ]]}
}]
}
}
},
"certificate": {
"Type": "AWS::CertificateManager::Certificate",
"Properties": {
"DomainName": { "Ref": "Domain" },
"SubjectAlternativeNames": [
{ "Fn::Join": ["", [ "*.", { "Ref": "Domain" } ]] }
],
"DomainValidationOptions" : [{
"DomainName": { "Ref": "Domain" },
"ValidationDomain" : { "Ref": "Domain" }
}],
"Tags": [{
"Key": "CloudFormationStack",
"Value": { "Ref": "AWS::StackName" }
}]
}
},
"staticCDN": {
"Type": "AWS::CloudFront::Distribution",
"DependsOn": "staticFileBucket",
"Properties": {
"DistributionConfig": {
"Comment": "CDN for Sagely static files.",
"Enabled": true,
"DefaultRootObject": "index.html",
"DefaultCacheBehavior": {
"AllowedMethods": [ "HEAD", "GET", "OPTIONS" ],
"TargetOriginId": { "Fn::Join": ["", [ { "Ref": "SubDomain" }, "-static.", { "Ref": "Domain" } ]] },
"ForwardedValues": {
"QueryString": false,
"Headers": [ "Access-Control-Request-Headers", "Access-Control-Request-Method", "Origin" ]
},
"ViewerProtocolPolicy": "redirect-to-https"
},
"Origins": [{
"DomainName": { "Fn::Join": ["", [ { "Ref": "SubDomain" }, "-static.", { "Ref": "Domain" }, ".s3.amazonaws.com" ]] },
"Id": { "Fn::Join": ["", [ { "Ref": "SubDomain" }, "-static.", { "Ref": "Domain" } ]] },
"S3OriginConfig": { }
}]
}
}
},
The CDN works through my custom domain. But how to I connect the SSL certificate to the CDN?
You want to have a ViewerCertificate property on your DistributionConfig. It should be something like:
"ViewerCertificate": {
"AcmCertificateArn": { "Ref": "certificate" },
"SslSupportMethod": "sni-only"
}
Based on your code, probably want to update your staticCDN to something like:
"staticCDN": {
"Type": "AWS::CloudFront::Distribution",
"DependsOn": "staticFileBucket",
"Properties": {
"DistributionConfig": {
"Comment": "CDN for Sagely static files.",
"Enabled": true,
"DefaultRootObject": "index.html",
"DefaultCacheBehavior": {
"AllowedMethods": [ "HEAD", "GET", "OPTIONS" ],
"TargetOriginId": { "Fn::Join": ["", [ { "Ref": "SubDomain" }, "-static.", { "Ref": "Domain" } ]] },
"ForwardedValues": {
"QueryString": false,
"Headers": [ "Access-Control-Request-Headers", "Access-Control-Request-Method", "Origin" ]
},
"ViewerProtocolPolicy": "redirect-to-https"
},
"Origins": [{
"DomainName": { "Fn::Join": ["", [ { "Ref": "SubDomain" }, "-static.", { "Ref": "Domain" }, ".s3.amazonaws.com" ]] },
"Id": { "Fn::Join": ["", [ { "Ref": "SubDomain" }, "-static.", { "Ref": "Domain" } ]] },
"S3OriginConfig": { }
}],
"ViewerCertificate": {
"AcmCertificateArn": { "Ref": "certificate" },
"SslSupportMethod": "sni-only"
}
}
}
},
You are missing the ViewerCertificate property.
This should be a Ref to the certificate, since ref returns the ARN of the certificate.