#!/usr/bin/env bash set -euo pipefail usage() { cat >&2 < [layer-version] Updates or adds a Lambda layer while preserving existing layers. Arguments: function-name Name of the Lambda function layer-name Name of the layer to add/update layer-version Layer version, defaults to latest EOF exit 1 } if [ $# -lt 2 ] || [ $# -gt 3 ]; then usage fi function_name="$1" layer_name="$2" version="${3:-}" region=$(aws configure get region) account_id="$AWS_ACCOUNT_ID" # Get latest version if not specified if [ -z "$version" ]; then version=$(aws lambda list-layer-versions \ --layer-name "$layer_name" \ --query 'max_by(LayerVersions, &Version).Version' \ --output text) fi new_layer_arn="arn:aws:lambda:${region}:${account_id}:layer:${layer_name}:${version}" # Get current layers and process them layer_arns=() while IFS= read -r layer_arn; do # Skip if it's the same layer (but different version) if [[ "$layer_arn" =~ ^(.+):([0-9]+)$ ]]; then base_arn="${BASH_REMATCH[1]}" if [[ "$new_layer_arn" =~ ^"$base_arn": ]]; then continue fi fi # Skip the update if the layer is already the right version if [ "$layer_arn" = "$new_layer_arn" ]; then echo "Layer $layer_name@$version is already attached to $function_name" exit 0 fi layer_arns+=("$layer_arn") done < <(aws lambda get-function --function-name "$function_name" --query 'Configuration.Layers[*].Arn' | jq -r '.[]') # Add the new layer layer_arns+=("$new_layer_arn") # Update the function configuration confirm aws lambda update-function-configuration --function-name "$function_name" --layers "${layer_arns[@]}" aws lambda wait function-active --function-name "$function_name"