AWS Lambda is a great service for running code without worrying about server management. While it traditionally supports languages like Python, Node.js, and Java, AWS now allows you to run code in any language using custom runtimes. In this blog post, I’ll walk you through setting up a C++ Lambda function that calculates the Fibonacci series. We’ll leverage the performance and efficiency of C++ to build a function that runs smoothly and showcases the versatility of AWS Lambda’s custom runtime.
The aim of this blog is to guide you through creating and deploying a C++ Lambda function using AWS custom runtime. We’ll:
-
Set up an EC2 instance for our development environment.
-
Compile and package our C++ Lambda function.
-
Deploy and test the function on AWS Lambda.
Implementation Steps
Prerequisites
Before we dive in, make sure you have:
- An AWS account
- AWS CLI configured on your local machine.
- Linux-based environment for compiling the C++ code (Amazon Linux is recommended).
Setting up the EC2 Instance
1. Launch an EC2 Instance:
- Open the AWS Management Console.
- Navigate to the EC2 dashboard and click “Launch Instance.”
- Choose the Amazon Linux 2 AMI.
- Select an instance type (t2.micro should be sufficient for this tutorial).
- Configure the instance, add storage as needed, and review and launch the instance.
- Configure security groups to allow SSH access.
- Go to Security Groups under Network & Security
-
Edit Inbound Rules:
Add a new rule to allow SSH access:
Type: SSH
Protocol: TCP
Port Range: 22
Source: Specify your IP address (e.g., 0.0.0.0/0 for all IP addresses or a specific IP range).
- Go to Security Groups under Network & Security
- Connect to the instance using SSH.
- Use the following command to connect to your instance via SSH:
ssh -i /path/to/your/key.pem ec2-user@your-instance-public-ip
- Use the following command to connect to your instance via SSH:
2. Install Required Packages:
Connect to your EC2 instance and run the following commands to install the necessary packages:
- A C++11 compiler, either GCC 5.x or later or Clang 3.3 or later. On Amazon Linux, run the following commands:
$ yum install gcc64-c++ libcurl-devel $ export CC=gcc64 $ export CXX=g++64
-
CMake v.3.5 or later. On Amazon Linux, run the following command:
$ yum install cmake3
Download and Compile the Custom Lambda Runtime
1. Clone the AWS Lambda C++ Runtime Repository:
$ cd ~ $ git clone https://github.com/awslabs/aws-lambda-cpp.git $ cd aws-lambda-cpp $ mkdir build $ cd build $ cmake3 .. -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF \ -DCMAKE_INSTALL_PREFIX=~/out $ make && make install
Create Your Custom C++ Lambda Function
1.Create a New Project Directory:
$ mkdir fibonacci-cpp-lambda $ cd fibonacci-cpp-lambda
2. Write the C++ Code for Fibonacci Series:
- Create a file named main.cpp with the following content:
// main.cpp #include <aws/lambda-runtime/runtime.h> #include <iostream> using namespace aws::lambda_runtime; int fibonacci(int n){ if (n <= 1) return n; return fibonacci(n - 1) + fibonacci(n - 2); } invocation_response my_handler(invocation_request const& request){ int n = std::stoi(request.payload); int result = fibonacci(n); return invocation_response::success(std::to_string(result), "application/json"); } int main() { run_handler(my_handler); return 0; }
3. Create the CMakeLists.txt:
cmake_minimum_required(VERSION 3.5) set(CMAKE_CXX_STANDARD 11) project(fibonacci LANGUAGES CXX) find_package(aws-lambda-runtime REQUIRED) add_executable(${PROJECT_NAME} "main.cpp") target_link_libraries(${PROJECT_NAME} PUBLIC AWS::aws-lambda-runtime) aws_lambda_package_target(${PROJECT_NAME})
4. Compile the Function:
$ mkdir build $ cd build $ cmake3 .. -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=~/out $ make
5. Package the Executable:
-
To package this executable along with all its dependencies, run the following command:
$ make aws-lambda-package-fibonacci
Create the AWS Lambda Function
1. Create an IAM Role:
- Go to the IAM dashboard in the AWS Management Console.
- Click on “Roles” in the left sidebar, then click the “Create role” button.
- Select “Lambda” from the trusted entity type and click “Next: Permissions.”
- Skip attaching policies for now by clicking “Next: Tags” and then “Next: Review.”
- Name the role lambda-cpp-demo and click “Create role.”
2. Attach the Trust Policy:
-
Create a file named trust-policy.json with the following content:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "Service": ["lambda.amazonaws.com"] }, "Action": "sts:AssumeRole" } ] }
- Use the AWS CLI to attach the policy:
$ aws iam create role \ --role-name lambda-cpp-demo \ --assume-role-policy-document file://trust-policy.json
This should output JSON that contains the newly created IAM role information. Make sure to note down the “Arn” value from that JSON. You need it later. The Arn looks like the following: (paraphrase)
“Arn”: “arn:aws:iam::<account_id>:role/lambda-cpp-demo”
3. Create the Lambda Function:
- Open the AWS Management Console and go to the Lambda dashboard.
- Click “Create function.”
- Select “Author from scratch.”
- Enter fibonacci-cpp as the function name.
- Select “Custom runtime” from the Runtime dropdown.
- Under Execution role, choose “Use an existing role” and select the
lambda-cpp-demo
role. - Click “Create function.”
4. Upload the Deployment Package:
- Scroll down to the “Function code” section.
- Select “Upload a .zip file” and click “Upload.”
$ aws lambda create-function \ --function-name fibonacci-cpp \ --role <specify the role arn from the previous step> \ --runtime provided \ --timeout 15 \ --memory-size 128 \ --handler fibonacci\ --zip-file fileb://fibonacci.zip
-
Choose the fibonacci.zip file generated in the previous steps and click “Save.”
Test the Lambda Function
1. Invoke the Lambda Function:
- Use the AWS CLI to invoke the function and pass the payload:
$ aws lambda invoke --function-name fibonacci-cpp --payload '5' output.txt cat output.txt
Conclusion
Running C++ code in AWS Lambda using a custom runtime gives developers a way to use the performance benefits of C++ in a serverless setup. This guide covered setting up a development environment, writing and packaging a C++ Lambda function, and deploying it on AWS Lambda. These steps enable you to build efficient applications with C++ in the cloud. This approach is practical for tasks requiring high performance and for reusing existing C++ code.
AWS, Azure, and GCP Certifications are consistently among the top-paying IT certifications in the world, considering that most companies have now shifted to the cloud. Earn over $150,000 per year with an AWS, Azure, or GCP certification!
Follow us on LinkedIn, YouTube, Facebook, or join our Slack study group. More importantly, answer as many practice exams as you can to help increase your chances of passing your certification exams on your first try!
View Our AWS, Azure, and GCP Exam Reviewers Check out our FREE courses