Introduction to Serverless With AWS Lambda and Bitrise API: Part 1

In the early days of software development, anyone seeking to develop a web, mobile, or backend application had to own the hardware required to run a server, which is an expensive process.

Then, when cloud computing came, it became possible to lease server space or a number of servers remotely. The developers and companies who rent these fixed units of server space generally overbuy to ensure that a spike in traffic or activity won't exceed their monthly limits and break their applications. Because of this, a lot of the server space that gets paid for can be wasted.

As a result of this, serverless computing allows developers to purchase backend services on a pay-per-use basis, which means that only what they use must be paid for.

What Is Serverless?

In a serverless environment, a cloud provider (AWS, Azure, or Google Cloud) dynamically allocates resources to run code. The cost is only incurred when the code is actually executed. The code that is usually executed is called stateless containers, which can be triggered by a variety of events, for instance: database events, call API endpoint, and cron jobs.

Serverless computing refers to the ability to run these functions without maintaining your own servers. 

The term "serverless" doesn't refer to the absence of servers, but rather to the fact that the servers, operating systems, network layer, and rest of the infrastructure have already been configured so you can focus on writing the application code.

What Is AWS Lambda?

AWS Lambda is a compute service that lets you run code without provisioning or managing servers. Lambda runs your code on a high-availability compute infrastructure and performs all of the administration of the compute resources, including server and operating system maintenance, capacity provisioning and automatic scaling, code monitoring and logging.  — AWS Lambda Documentation.

You don't have to worry about any infrastructure with AWS Lambda since it's a fully managed service.

For instance, You can develop backends using AWS Lambda and Amazon API Gateway to authenticate and process API requests.

The Lambda functions can perform a variety of tasks, from serving web pages to processing streams of data to calling APIs and integrating with other AWS services such as CloudWatch, API Gateway, S3, SNS, and more. 

How Does AWS Lambda work?

When a function is created, Lambda packages it into a new container and then executes that container on a multi-tenant cluster of machines managed by AWS. Before the functions start running, each function’s container is allocated its necessary RAM and CPU capacity. Once the functions finish running, the RAM allocated at the beginning is multiplied by the amount of time the function spent running. The customers then get charged based on the allocated memory and the amount of run time the function took to complete.

Supported Languages and Runtimes

AWS Lambda supports a number of the most popular languages and runtimes such as Nodejs, Python, Ruby, Java, Go, and C# This is the full list of what’s supported.

AWS Lambda Pricing

With AWS Free Tier, you can run 1 million requests for free. Also if you’d like to estimate your AWS Lambda architecture cost you can use the AWS Pricing Calculator. More info about Lambda pricing can be found in the pricing section. 

Getting Started With AWS Lambda

You can create, invoke, and manage the Lambda functions using any of the following interfaces:

In this tutorial, I will use the AWS Management Console to create our Lambda function using NodeJS. 

Before we get started you should have the following prerequisites: 

Now let’s start with our first Lambda function:

Congratulations: you just created your first Lambda function and you have the Function overview and the code source with an online editor.

Now you can do everything you want with your function such as change the code, test the function, monitor the traffic using CloudWatch, configure the Environment Variables and deploy the function. 

In the Function Overview, you will find two options: 

Let’s now learn how to test our function. 

And the execution results will be displayed in a new tab in the online editor. 

After you’ve explored the Lambda function, and know how to trigger and test it, it’s time to know how to implement our function to trigger Bitrise builds. 

The next step in this tutorial requires that you have a Bitrise account and an API Key to access it.

AWS Lambda and Bitrise API

To implement a NodeJS function to trigger a Bitrise build we need to install different node modules because we will create the project locally and then upload it to Lambda to include the node_modules folder as a part of our service. 

Let’s get started!

Shell
 
mkdir LambdaBitrise
cd LambdaBitrise


Shell
 
npm init


The package.json file that will be generated

Now we need to implement a function that triggers a new build endpoint from the Bitrise API, to do that: 

Shell
 
npm install request 


And add the following code:

JavaScript
 
var request = require('request');
var options = {
  'method': 'POST',
  'url': 'https://api.bitrise.io/v0.1/apps/{YOUR_APP_SLUG}/builds',
  'headers': {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'YOUR_API_KEY'
  },
  body: JSON.stringify({
    "build_params": {
      "branch": "chapter-3",
      "workflow_id": "primary"
    },
    "hook_info": {
      "type": "bitrise"
    }
  })

};

exports.handler =  async function(event, response) {
  console.log(response.body);
  return "done..."
}

request(options, function (error,response) {
  if (error) throw new Error(error);
  console.log(response.body);
});


You can test the function by running the following command: 

Shell
 
node index.js


And if it is successful run, you will find the output like the following: 

Shell
 
zip -r LambdaBitrise.zip index.js node_modules


Now it’s time to upload the zipped folder to Lambda by the following steps: 

The folder will be uploaded and extracted successfully and displayed in the online editor you will notice the node_modules folder as well. 

Now you can replace the app_slug and API_Key with the Lambda Environment variables:

JavaScript
 
var request = require('request');

let app_slug = process.env.APP_SLUG
let api_key = process.env.API_KEY

var options = {
  'method': 'POST',
  'url': 'https://api.bitrise.io/v0.1/apps/'+app_slug+'/builds',
  'headers': {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': api_key
  },
  body: JSON.stringify({
   'build_params': {
      'branch': 'chapter-3',
      'workflow_id': 'primary'
    },
    'hook_info': {
      'type': 'bitrise'
    }
  })

};

exports.handler =  async function(event, response) {
  console.log(response.body);
  return "done..."
}

request(options, function (error,response) {
  if (error) throw new Error(error);
  console.log(response.body);
});


Click the Deploy button to save the changes and run Test to make sure that everything is working properly. 

Now to be able to test our Lambda function we need to add a trigger, which will be discussed in Part 2 to invoke the function from your terminal you can use the following command but remembers you need to have the AWS CLI: 

Shell
 
aws lambda invoke --function-name HelloBitrise  --cli-binary-format raw-in-base64-out  output.txt


And the output should be like the following: 

JSON
 
{
    "StatusCode": 200,
    "ExecutedVersion": "$LATEST"
}


Now you can check your Bitrise dashboard to make sure that a new build is already triggered, then you can abort it to save your credits.

Congratulations, you did it! You created your first serverless function using AWS Lambda to trigger a new Bitrise build using Bitrise API.

Thank you and happy building

 

 

 

 

Top