knoebber / golamb

~/bin/golamb Commits Diff Raw
#!/usr/bin/env bash
# golamb: zip, upload, and update a golang lambda function.
# $1 should be both the name of the lambda function and the name of the go module.
#
# Example: Lambda function named "get-comments"
#          go module named "github.com/knoebber/personal-website/get-comments"
#          Use: golamb get-comments 
#          Or to test: golamb get-comments --test

# exit when any command fails
set -e

function=$1
bucket=nicolasknoebber-backend
start_path=$(pwd)

# Find go.mod files in or beneath the current directory.
function find_go_modules() {
    find . \
         -type d\
         \( -name node_modules -o -name .git \) -prune -false \
         -o -name 'go.mod'
}

# Finds a go package that should be zipped and uploaded.
# $1 should match part of the first line of a go.mod file.
function find_lambda_package() {
    for module in $(find_go_modules); do
        if head -1 "$module" | grep -w "$1" > /dev/null; then
            echo "$module"
            break
        fi
    done
}


module_path="$(find_lambda_package "$function")"
if [ -z "$module_path" ]; then
    echo "Failed to find module for $function"
    exit 1
fi

echo "Found lambda module at $module_path"
build_path=$(dirname "$module_path")
cd "$build_path"
pwd

if [ "$2" == "--test" ]; then
    go test ./...
    aws lambda get-function --function "$1"
    cd "$start_path"
    exit 0
fi



echo "Building Lambda function $function"
CGO_ENABLED=0 GOOS=linux go build

echo "Zipping Lambda function $function"
zip "$function.zip" "./$function"

s3_path="s3://$bucket/$function.zip"
echo "Uploading Lambda binary to $s3_path"

aws s3 cp "$function.zip" "$s3_path"

echo "Updating Lambda function"

aws lambda update-function-code\
    --function-name "$function"\
    --s3-bucket "$bucket"\
    --s3-key "$function.zip"\
    --publish

echo Cleaning up
rm "$function"
rm "$function.zip"
cd "$start_path"