Amazon web services (AWS) is a powerful platform for almost every web service you can imagine. With AWS API Gateway and Lambda you are able to create REST API’s with ease! API gateway is used to create the API. Lambda lets you execute code when the API is invoked. This code can be in many programming languages like Python or NodeJs.
Unfortunately, it is unable to run Bash code out-of-the-box with Lambda. For me it was necessary to run bash code in order to execute AWS CLI. With AWS CLI you are able control your AWS web services with commands (CLI = command line interface). With AWS CLI you can do things like: create an API in API gateway or connect to a database from DynamoDB. An example command to create an API is:
aws apigateway create-rest-api --name "test-api"
But before we can use these AWS CLI commands lets checkout how to create a Lambda function with a bash runtime.
Setup the Lambda function to run Bash code
In order to create a lambda function with bash code you need to do the following:
Step 1: create an lambda function
Go to your AWS Console and open Lambda. Click on create function.
Step 2: Fill-out the name of your Lambda function. Select “Provide your own bootstrap” from the list of available runtimes. Finally, set the right security permissions.
Step 3: Once the Lambda function is created, click on “Layers”. Then click on “Add a layer.
Step 4: In the next screen you have to select the type of layer you want to use. In this case you need to select: “Provide a layer version ARN”. In the textbox paste the following line:
arn:aws:lambda:<region>:744348701589:layer:bash:8
Replace <region> with your AWS region. See the image below. Once you are done click on “Add”.
Step 5: Scroll down to the Function code. In the “Handler” section type “index.handler”. Then right-click on one of the files in the environment folder and select “Rename”. Rename this file to “index.sh”. You can delete the other 2 files.
Step 6: open the index.sh file. Delete all the contents and copy the following code into the editor:
$ cat index.sh
handler () {
set -e
echo 'hallo'
}
Concratualations! You made your first bash Lambda function.
Access event variables in bash
Let’s say your Lambda is connected to an API in API gateway. When you do a POST request you are able to sent data to the Lambda function. You are able to read the event data with the following line of code:
EVENT_DATA=$1
Subsequently you are able to read the body of the API request like in the image below.
Conclusion
As a data scientist & entrepreneur I started to learn about AWS when I created my first device detection API for The API Company. To my opinion AWS is a really user-friendly platform to create your own API’s. By using bash in your Lambda function a lot of new possibilities are created. Now all my services are managed with AWS Lambda, API gateway and AWS CLI. So go ahead and start making your own bash API!