arjabbar
arjabbar

Reputation: 6404

Reference AWS API Gateway's hostname within the serverless.yml file for other CloudFormation resources?

I'm using the Serverless framework to create a image resizing service using S3, Lambda and API Gateway. This is similar to the concept here, but this will use Serverless to setup and configure the entire stack.

Right now I need to find a decent way to reference the generated API Gateway's hostname within the serverless.yml file. This is what I have under my resources. (Just a snippet)

imageBucket:
  Type: AWS::S3::Bucket
  Properties:
    BucketName: ${env:IMAGE_BUCKET}
    WebsiteConfiguration:
      RoutingRules:
        -
          RedirectRule:
            Hostname: ${HOSTNAME HERE}
            HttpRedirectCode: 302
          RoutingRuleCondition:
            HttpErrorCodeReturnedEquals: 404

Where it says ${HOSTNAME HERE} I need to be the hostname of the API Gateway API that the serverless framework generates.

Right now, the best way that I can think of is to create a CNAME alias somewhere and use that in front of my API. Then I'll pass that CNAME in as an environment variable and then reference it in this file. That's not ideal for me though. I would like someone have the ability to pull this project down and be able to run it with just a bucket name. Is there anyway to accomplish this?

Upvotes: 2

Views: 576

Answers (1)

jens walter
jens walter

Reputation: 14029

The hostname is no directly exposed by cloudformation, so you have to build it from the outputted values of the created resources. All resources of the serverless framework follow a certain naming convention: AWS - Resources

With this information, you can create your hostname through the following statement:

imageBucket:
  Type: AWS::S3::Bucket
  Properties:
    BucketName: ${env:IMAGE_BUCKET}
    WebsiteConfiguration:
      RoutingRules:
        -
          RedirectRule:
            Hostname: 
              Fn::Join:
                - ""
                - - Ref: ApiGatewayRestApi
                  - ".execute-api."
                  - Ref: AWS::Region
                  - ".amazonaws.com"
            HttpRedirectCode: 302
          RoutingRuleCondition:
            HttpErrorCodeReturnedEquals: 404

Upvotes: 5

Related Questions