Skip to content

Instantly share code, notes, and snippets.

@katesclau
Created August 20, 2021 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katesclau/a7b7464ebb3e61e17f17e390952b02a9 to your computer and use it in GitHub Desktop.
Save katesclau/a7b7464ebb3e61e17f17e390952b02a9 to your computer and use it in GitHub Desktop.
buildLayers.sh - Script to build NodeJS Lambda Layers for Serverless projects
###
# Script to build the Lambda Layers based on libs used by functions.
# Assumptions...
# - your functions are all inside ./functions
# - you don't need specific versions of the dependecies
###
#!/bin/bash
echo "======================================="
echo "Creating Lambda Layers..."
node_version=`cat .nvmrc | sed "s/v//"`
echo "Building layer: NodeJS:$node_version"
echo "Fetching required libraries:"
requires=`find ./functions/* | xargs grep "require(" | awk '{{
str = $NF
sub(/require\(./, "", str)
sub(/\/[a-zA-Z0-9-]+.\);?/, "", str)
sub(/.\)[;\.]?.+/, "", str)
print str
}}' | sort | uniq`
echo "======================================="
echo "=> Used libraries: " $requires
BASE_DIR=`pwd`
ZIP_FILE=`grep "layers/nodejs" serverless.yml | awk '{{
str = $NF
sub(/^(layers\/)/, "", str)
print str
}}'`
echo "======================================="
echo "Building ${BASE_DIR}/layers/${ZIP_FILE}"
declare -a libraries
for req in $requires
do
echo "Searching for $req..."
lib=`grep "$req" package.json | awk '{ print $1 }' | sed "s/[\":]//g"`
echo "=> found $lib"
if [[ -z "$lib" ]]; then
echo "=> settled $req"
libraries+=("$req")
else
echo "=> found $lib"
libraries+=("$lib")
fi
done
echo "======================================="
echo "Resolved libraries ${libraries[*]}"
cd layers
echo "Fetching dependecies..."
mkdir _build
cp package.template.json _build/package.json
cd _build
yarn add ${libraries[*]}
echo "=> Dependecies fetched!"
# Remove unused stuff
echo "======================================="
rm package.json
rm yarn.lock
# Add files from staging area to zip
zip -q -r "${BASE_DIR}/layers/${ZIP_FILE}" .
echo "Zipped layer size: $(ls -s --block-size=1048576 ${BASE_DIR}/layers/${ZIP_FILE} | cut -d' ' -f1)M"
# Package layers folder into .zip
# Remove unused stuff
echo "======================================="
# Cleanup build dir
cd $CURRENT_DIR
rm -rf layers/_build &
echo "All done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment