Websites using Swift and AWS Lambda — Part 2

Websites using Swift and AWS Lambda — Part 2

If you haven’t already, check out Part 1.

Summary

Want to see this kind of Swift website in action!? Check out the example website, and here is the source code!

This is the second part in a two part series of posts about making websites using the Swift programming language and Amazon Web Services (AWS). The first part focused more on the technical details of what this even means and how to set up a Swift project to generate a Swift website: both for local development and for making an executable ready for AWS Lambda. This post will pick up from there with a few notes about pricing before diving into the details on how to deploy & host this kind of website!

Even if you didn’t look at the first part (or skimmed it 🙃), I tried to provide enough details to make this a useful overview of AWS.

Yes, you will need an AWS account to do the following, and if you are worried about cost — me too! Check out the section on pricing below.


Hosting using Amazon Web Services (AWS)

As mentioned, this project makes use of AWS to provide the infrastructure to deliver a Swift generated website. To accomplish this from a high level, API Gateway provides us with a URL to put in a web browser that triggers an AWS Lambda function, which runs our generate website Swift code (that we made in Part 1), to make HTML/CSS that is then returned and rendered as a website 🎉.

Before we start, a couple things worth noting:

Pricing

You will need an AWS account for this post. Yes AWS is not free, but I wouldn’t get caught up thinking about cost too much unless you think you will have millions of requests coming in. Even at that point, you won’t be paying much for the services used in this post. Let’s take a look!

Personal experience

Part 1 of this post ended up getting a decent amount of exposure having been picked up by some weekly newsletters (iOS Dev Weekly issue 394 and Swift Weekly issue 150), and in turn so did the example website. With that flood of traffic, my AWS bill was at one point showing a ~5000% increase in my monthly cost, totaling a whole $0 😂. Here is a screenshot prior to hitting that ~5k% mark.
aws_cost_explorer

Some math

Not fully convinced? Let’s do some back of the envelope calculations to further prove the point:

Fair to say, running your website like this is effectively free! Costs of course may vary from the time of this writing, but the end conclusion will be likely similar.

Additional things to note

Make a Swift runtime for AWS Lambda

How does Swift code run in an AWS Lambda function without being one of the out of the box supported languages (e.g., python, javascript)!? We will need to make an environment that will allow our Swift code to run in AWS Lambda.

To accomplish this, we’ll use a newer addition to AWS called AWS Layers to create a Swift runtime for our AWS Lambda function to run Swift code. AWS Layers can do more than make runtimes for different languages and is worth checking out to see how powerful AWS Lambda is with this addition!

To make the runtime, clone this project and follow the readme to get a Swift runtime uploaded to AWS. The above project is also the same project that we use to let our Swift code communicate with Lambda function in the first part of these posts!

After creating the Layer, copy the ARN! We will use it in the next section to reference this Layer from Lambda.

Note: ARN stands for Amazon Resource Name, and is a string that uniquely identifies different AWS resources like the Layer you created here. If you want to learn more, read up on ARNs.


As I noted above, I used this project to create the Swift runtime for AWS Lambda. There are other similar projects that are worth checking out too. The below references come from this Swift forum’s post.

The AWS Lambda function

With the Swift runtime Layer ready, we can now set up our Lambda function with our Swift code to generate HTML/CSS for our website!
Note: The below goes through the manual way to create and configure a Lambda function. There are other ways like using the AWS commandline interface (CLI).

  1. In the AWS search type in, and select, Lambda. aws_lambda_creating_the_lambda_1

  2. Next, click to create a new Lambda function
    aws_lambda_creating_the_lambda_2

  3. You will be presented with this:
    aws_lambda_creating_the_lambda_3
    • Give your Lambda a Name.
    • Choose to use a custom Runtime (we will be using the Swift runtime created in the previous section — more on this later).
    • The next two options are to define a Role, which is used to define permissions and security that you want to grant your Lambda function. I chose to go with an existing basic execution role. If you want to learn more about roles, check here.
    • Click to create your function!

  4. When your newly created Lambda function opens, there will be an intimidating amount of things to sort through (at least there was for me). Working form top-right to top-left, some notable things.
    aws_lambda_top_menu_bar
    • When you make changes to your Lambda function, you will need to press Save for the changes to take effect. Think of this like updating your current git commit, git amend, but these changes are live!
    • You can test your Lambda by pressing Test on the top right. This won’t do anything meaningful right now since we haven’t added any code to run/test yet.
    • The Actions dropdown includes the ability to version your Lambda function. Think of this like a combination of a git commit and deployment. This lets you lock in a version of your Lambda function, which you can use later to roll back to a previous version of your function if needed. I recommend you use this in case you need to go back to a previous working version of your Lambda function, or if someone overrides your Lambda function accidentally 😅.
    • The Qualifiers dropdown is where you manage your Lambda function versions.

  5. Next, we need to link the Swift runtime that we created above to this newly created Lambda function. Find and click on the Layers option.
    aws_lambda_how_to_add_a_layer_5
    aws_lambda_how_to_add_a_layer_5
    • Here you will be able to add the runtime Layer. You can either select one from a list or provide an ARN. I’ve had little luck with selecting from a list, so I usually default to providing the ARN. If you are using the ARN, simply use the ARN for the AWS Layer you created in the previous section and click Add.

  6. Now that we have the Swift runtime setup, our Swift executable will be able to run! We just need to upload the Swift executable that we created in Part 1. If you want to skip creating the executable, you can download an already compiled one from the Github repo for these posts: example Swift website generator executable (lambda.zip).
    aws_lambda_upload_executable_1
    • Make sure you have your Lambda function’s name selected, which is right above the Layers button that we previously selected to add the Swift AWS Layer runtime.
    • Scroll down to the Function code section and look for Code entry type.
    • Click the dropdown menu and select Upload a .zip file.
    • Below the dropdown menu is the upload button. Click this to upload the Swift executable.
    • Make sure the Runtime is set to use a custom runtime.
    • Update the Handler to be Swift-AWS-Lambda-Website.handler
      • This tells Lambda what Swift function to run when triggered. This just has to match the function name that we created in the first part of these posts.
    • Press Save, which should be at the top right of the screen.

  7. We are ready to test!! Click the Test button at the top right of the screen (next to the Save button).
    aws_lambda_test_it_1
    • The first time you press this button, you will be prompted to configure the test event. You can edit the payload that will be delivered to your Lambda function. In our case this doesn’t make much of a difference, but if your Swift website needs to take in some information like a customer id to pull some data out of a database, you would probably want to make a test that provides a test customer id. In this example, you may also want a test an invalid customer id to test some edge cases.
    • Since our use case is simple, choose whatever names you want to give the test, feel free to delete the json between the brackets, and press Save.
    • Press the Test button again and you should see a green box with the result of running the Swift generate website code — HTML/CSS 🎉! aws_lambda_test_it_2
      • If you wanted to, you could copy the generated HTML/CSS to an .html file to see the website in action that was created by running your newly created Lambda function!
    • If your test runs and a red error box appears, don’t panic! Read the error message and step through everything you did to troubleshoot. Also, feel free to reach out if you are really stuck :).

AWS API Gateway

Now that we have a Lambda function that is ready to generate our HTML/CSS, we need a way to run it other than hitting the Test button 🙃. API Gateway allows us to map an incoming URL request to trigger our Lambda function; The result of which then gets sent back and we have a website!

  1. Search for and go to API Gateway from the AWS console.

  2. Create a new API by clicking Create API at the top.

  3. Most of the defaults are fine. Just give your new API a name (and a description if you want).
    new_api_gateway_screen_1

  4. With the API initially created, we need to configure it to return the generated HTML/CSS from our Lambda function. First step is to set up the method for your endpoint. In this case, we want a GET method.
    get_resource_1
    • With your API selected on the left, select the Actions dropdown.
    • Click on Create Method.
      get_resource_2
    • Click the dropdown to select the type of method. Click GET from the options.
    • Accept the GET method choice by clicking the little check button.

  5. Next you will be asked to choose the integration point, which is similar to saying what would you like to do when your URL gets called? If you don’t see the below screen, click on the GET request method that you just created to bring it up.
    configure_get_request_1
    • Choose Lambda Function at the top.
    • Give the name of your Lambda function at the bottom. When typing in this field, you should get auto complete to help you select your Lambda function.
    • Press save.
    • You will be asked to add permission to the Lambda function. Press ok.

  6. Now that we have an API with a GET method that is hooked up to call our Lambda function, we need to configure the GET method a bit. If you don’t have your GET method selected, click it now. configure_get_request_2
    • Aside: The right side details that this opens up can be a little intimidating. From a high level, this shows the flow for a request coming in and the response going out. The left most rectangle shows the client and gives you the option to test your endpoint (we will be using this later). The top two boxes allow you to configure authentication and then where the request gets routed to, which ultimately ends up at the right most rectangle — at our Lambda function! Following the bottom two boxes, the response from our Lambda function gets processed and sent out back to the client (client = the thing calling your endpoint).
    • Let’s start configuring the method by clicking on Method Response.
      configure_get_request_3
      • click on the dropdown under HTTP Status. Change the following settings:
        • Under Response Headers for 200 add header with name Content-Type
        • Delete what is under Response Body for 200
    • Return to Method Execution.
      • If you ever lose your place just reselect the GET method as you did before to see the flow block diagram.
    • Select Integration Response.
      configure_get_request_4
      • Now, click to show the dropdown for both Header Mappings and Mapping Templates.
      • First, we need to make sure that the respone that goes back has a content type of HTML. This tells the web browser to try and render the response as webpage.
      • Edit the Header Mappings as follows:
        • Response header -> Content-Type
        • Mapping value -> 'text/html'
      • Next, we need to edit the Mapping Templates to pull the HTML/CSS out form our Lambda function’s response and return that.
        • Under Mappings Templates delete application/json, if that is listed.
        • Click Add mapping template and add text/html
        • On the right, put this into the text box:
          • $input.path('$').html
          • Note: If you don’t see a text box to the right, you will need to click on the text/html that you just added in the previous step.
      • Press save at the bottom.

  7. With your endpoint fully set up, let’s test it!
    • Start by going back to the overview flow block diagram of your GET endpoint. The overview looks like this.
    • Click Test on the left side of the flow block diagram.
    • On this screen click Test.
    • You should see something like this (you may need to scroll down a bit):
      configure_get_request_5

  8. We are real close now 🤓! With the above API Gateway setup complete and tested, we just need to make this endpoint publicly available. Go back to your API and click the dropdown for Actions like you did before. deploy_api_1
    • Under API Actions select Deploy API. deploy_api_2
    • You will need to select a stage like production or development. Since we haven’t set up a stage yet, let’s make new one and call it prod for production and click Deploy.
    • When this completes, you will have a fully functional AND publicly available URL! deploy_api_3
    • The URL will not be pretty, but you can copy and paste it into a web browser to see you webpage in action 🎉😎🎉!

Custom URL

Even though we just made a publicly available URL, having a website with a custom URL is a nice professional and gratifying touch.

The following custom URL steps use GoDaddy because that is where I started buying domains, but where you buy them is not really that important. As noted in the previous part of these posts, if I was going to buy a new domain(s) I would consider going with Amazon Route 53 to have everything under the AWS umbrella.

  1. To start, we need to make a certificate to both verify that we own the domain and to give us a secure website (i.e., https). After the certificate is created, we will use this in API Gateway to create a custom domain name that maps to the API we created in the last section.
    • In the AWS console, search for and go to Certificate Manager.
    • Click on Request a certificate.
      making_a_certificate_1
      • Select Request a public certificate and click Request a certificate at the bottom.
    • Next, you will be asked to put in the domain name that you want. making_a_certificate_2
      • I choose to go with a subdomain because I already use jasonzurita.com for this site — the subdomain used for the acompanying example website is the swift-aws-website before the main domain name. You should choose the domain, or subdomain, that is right for you.
    • Click Next.
    • Here you will need to select a validation method. Choose DNS validation and click on Review. making_a_certificate_3
    • Make sure everything you put in looks correct and click on Confirm and request at the bottom.
    • On the main Certificate manager dashboard, you will see that your certificate is created and Pending validation.
      making_a_certificate_5
      • We need to validate the certificate to prove that we own the domain.

  2. In order to validate your certificate, we need to add the CNAME that AWS generated to your DNS configuration, GoDaddy in my situation.
    • Note: CNAME record (Canonical Name record) is using in DNS to map one domain name to another. In our case, a map from our custom domain to the API gateway domain we made.
    • To see the CNAME click on the certificate you just created and click on the dropdown in the Domain section.
    • You should now see Name, Type, and Value, where Type is CNAME.
    • Keeping the above information available, go to your DNS provider’s website (GoDaddy in my case) and log in.
    • Navigate to your custom domain’s DNS management section and add a CNAME entry using the Name and Value above.
      custom_domain_dns_setup_1 custom_domain_dns_setup_2
      • Name goes into the Host field and value goes into the Value field.
        • Note: For GoDaddy, when you enter the Host, make sure to leave off the root domain when doing so. I am not sure if other DNS providers do this, but GoDaddy implicitly assumes the root domain at the end of what you enter. Continuing on this tangent, if you ever want to enter the root domain, GoDaddy let’s you put in a @ to represent that. This was a subtle got ya that caused me some pain.
    • Press Continue.
    • After you do this, go back to AWS Certificate Manager and { refresh ? }, and you should see your certificate turn to say Issued!
      custom_domain_certificate_issued
      • If certificate validation doesn’t happen right away, you may need to give the newly added CNAME some time to propagate.

  3. Now we are ready to use our newly created certificate. { this whole section needs to be verified }
    • Search for and go to API Gateway.
    • Select Custom Domains from the left side bar.
    • Click on Create Custom Domain Name. custom_domain_api_gateway_1
      • Put in your domain name.
      • You can select either Edge Optimized or Regional. Select Regional so that your custom domain gets deployed quickly.
        • Edge Optimized will produce a custom domain that is faster to access for your end users. It is good practice to select this if you are deploying a production website.
      • Select your newly made certificate.
      • Click Save.
        • Your custom domain setup may take some time to process.
    • Once your custom domain has been set up, we need to add a mapping to trigger the right API path. This is simple in our case since we only have one path, but you can imagine that there could be other paths for our API like a customer screen (e.g., <domain_name>/products). custom_domain_api_gateway_2
      • Set Path to “/”.
      • Set Destination to our previously created API.
      • And, set the last field to Prod.
    • Click Save. Your custom domain should look like this after being setup: custom_domain_api_gateway_3

  4. The final thing we need to do is add one final CNAME to our DNS to map the custom domain we want to the custom domain name that we just set up!

    Note: After setting this up, when a user types in your custom domain into the browser, they will get mapped to the custom domain in the previous step. When API Gateway receives the request, AWS will cross check against the legitimacy of the custom domain name using the certificate we created. Then API Gateway will know where to route the request — our Lambda function!

    • Using the following, complete the same steps to add a CNAME to your DNS as before. { check this link }
      • For the Host field, enter the custom domain name you want. In my case it was swift-aws-lambda-website. If you want to use your root domain (e.g., jasonzurita.com), GoDaddy uses @ to represent the root domain.
      • For the Value field, enter the API Gateway Custom Domain Name’s Target Domain Name as seen in the previous section’s last screenshot.
    • Once the CNAME has been added and processed, when you type in your custom domain into the browser you will see your website that is generated from Swift 🎊 🎉 🍾!!

Some parting thoughts

The current state of this implementation is a great first step! Some additional thoughts come to mind:


Feel free to reach out on Twitter — cheers!

rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora quora