Building DevSecOps solutions using AWS, Terraform and Kubernetes

Deploy a Golang Lambda

  • 7th June 2022
Video walk-through showing how to deploy a Golang Lambda in AWS

The Problem

Quite often we just want a simple way to build and deploy a Golang Lambda in AWS without using SAM or Serverless.

We will look at using the CLI to deploy a simple Golang lambda. This example will give us the building blocks to integrate this into a CI/CD pipeline later.

Deploy a Golang Lambda

The Solution

1) Prerequisites
This article assumes you have these installed already:
  • Golang
  • AWS CLI
  • The jq package for parsing json
  • IAM permissions required to deploy the lambda
2) Create main.go file

Create a file called main.go in the root directory.

Here is a quick hello world script.

package main

import (
    "log"

    "context"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, request events.APIGatewayProxyRequest) error {
    log.Println("HelloWorld from Golang Lambda")

    return nil
}

func main() {
    lambda.Start(handler)
}    
3) Create Makefile

Create a file called Makefile in the root directory.

Please edit the parameters for function name and region

export GOOS=linux
export GOARCH=amd64
export CGO_ENABLED=0
.DEFAULT_GOAL := deploy

deploy:
	go build -o hello
	zip -r function.zip hello
	aws lambda update-function-code --function-name "BlogHelloWorldExample" --zip-file fileb://function.zip --region="eu-west-1" | jq .    

Note: If you receive the error "Makefile:6: *** missing separator. Stop.", make sure to replace the spaces with tabs.

4) Install Golang Dependencies

You only need to do this step once:

go mod init example.com/demo
go get github.com/aws/aws-lambda-go/events
go get github.com/aws/aws-lambda-go/lambda
5) Run Makefile

Run the following CLI command to build, zip and deploy our example Lambda

make deploy

You should now see output similar to:

{
  "FunctionName": "BlogHelloWorldExample",
  "FunctionArn": "arn:aws:lambda:eu-west-1:xyz:function:BlogHelloWorldExample",
  "Runtime": "go1.x",
  "Role": "arn:aws:iam::xyz:role/service-role/BlogHelloWorldExample-role-xyz",
  "Handler": "hello",
  "CodeSize": xyz,
  "Description": "",
  "Timeout": 15,
  "MemorySize": 512,
  "LastModified": "2022-06-07T11:09:28.000+0000",
  "CodeSha256": "xyz",
  "Version": "$LATEST",
  "TracingConfig": {
    "Mode": "PassThrough"
  },
  "RevisionId": "xyz",
  "State": "Active",
  "LastUpdateStatus": "InProgress",
  "LastUpdateStatusReason": "The function is being created.",
  "LastUpdateStatusReasonCode": "Creating"
}

Summary

That's it! Your lambda should now be deployed. Hopefully this gives you a quick starting point for building your pipeline.

Rhuaridh

Please get in touch through my socials if you would like to ask any questions - I am always happy to speak tech!