Simple Serverless Functions with Terraform and AWS
Serverless functions are a great way to run code without having to manage the underlying infrastructure. In this tutorial, we’ll create a simple serverless function with Terraform and AWS.
Prerequisites
Before you begin, you’ll need the following:
- An AWS account
- The AWS CLI installed and configured (i.e.
aws configure
) - Terraform installed
- Node.js installed
- An IDE, such as Visual Studio Code
Initial Function Deployment
First, clone the serverless functions template repository:
git clone https://github.com/russellsteadman/serverless-functions-template.git
cd serverless-functions-template
Open the serverless-functions-template
directory in your IDE. If you’re using Visual Studio Code, you can run code .
to open the directory in the VS Code.
Head to the functions
directory and run npm install
to install the function’s dependencies. Then, run npm run build
to build the function.
cd functions
npm install
npm run build
Now that the function is built, we can deploy it to AWS using Terraform. First, initialize the Terraform configuration:
cd ../terraform
terraform init
Next, run terraform apply
to deploy the function to AWS. You’ll be prompted to confirm the deployment. Enter yes
to proceed.
terraform apply
Once the deployment is complete, you’ll see the URL of the deployed function in the output. You can open this URL in your browser to see the function in action.
Making Changes
Now that we have a serverless function deployed, let’s make some changes to it. Open the functions/src/hello-world.ts
file in your IDE and make some changes to the function. For example, you could change the message that the function returns.
To add new functions, create a new file in the functions/src
directory and export a the execute
function from the file. Then, add the new function to the cloud/api.tf
file. The README.md
file contains more detailed instructions on how to work with new functions.
Once you’ve made your changes, run npm run build
to build the function again. Then, run terraform apply
to deploy the updated function to AWS.
npm run build
cd ../terraform
terraform apply
Conclusion
It is easy to create and deploy serverless functions with Terraform and AWS. You can use this approach to create a wide range of serverless applications, from simple APIs to complex event-driven systems. Check out the serverless functions template repository for more detailed instructions.