diff --git a/lambda-web-weighted-rollout/nodejs/sam/.gitignore b/lambda-web-weighted-rollout/nodejs/sam/.gitignore new file mode 100644 index 0000000000..2302d388cf --- /dev/null +++ b/lambda-web-weighted-rollout/nodejs/sam/.gitignore @@ -0,0 +1,10 @@ +.aws-sam/ +samconfig.toml +*.zip +*.pkg +node_modules/ +npm-debug.log* +.claude/ +.vscode/ +.idea/ +.DS_Store diff --git a/lambda-web-weighted-rollout/nodejs/sam/README.md b/lambda-web-weighted-rollout/nodejs/sam/README.md new file mode 100644 index 0000000000..8d4a385484 --- /dev/null +++ b/lambda-web-weighted-rollout/nodejs/sam/README.md @@ -0,0 +1,169 @@ +# Weighted revision rollouts for an AWS Lambda Web Function behind Amazon CloudFront + +This pattern shows how to release new code to an **AWS Lambda Web Function** gradually: send a small share of traffic to the new release (a canary), increase it, then promote or roll back. Two fixed revision slots, **blue** and **green**, share one endpoint. Stack parameters set each slot's code version and traffic weight, so the template always matches what's serving traffic. Amazon CloudFront with Origin Access Control (OAC) sits in front, so you can watch the traffic split in a browser. + +The Lambda documentation recommends turning off automatic deployment and setting revision weights yourself for production workloads, and using automatic deployment to the latest revision for development and staging ([Deployment patterns](https://docs.aws.amazon.com/lambda/latest/dg/web-functions-deployment.html)). This pattern implements the production approach as infrastructure as code. + +**Important:** this application uses various AWS services and there are costs associated with these services after the Free Tier usage. See the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. + +## Requirements + +* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +* [Git installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) CLI installed +* `zip` on your PATH +* A Region where Lambda Web Functions is available. See the [Lambda Web Functions documentation](https://docs.aws.amazon.com/lambda/latest/dg/web-functions.html) for the current list. + +## Deployment Instructions + +1. Clone the repository and change to the pattern directory: + + git clone https://github.com/aws-samples/serverless-patterns + cd serverless-patterns/lambda-web-weighted-rollout/nodejs/sam + +2. Deploy. The script creates a versioning-enabled code bucket, uploads `src/`, and creates the stack with the same code in both slots and 100% of traffic on blue: + + ./deploy.sh + + The script uses the first Region it finds: the `--region` flag, then `AWS_REGION`, then `AWS_DEFAULT_REGION`, then your AWS CLI profile's default Region. If none is set, it stops with an error. To deploy somewhere else, run `./deploy.sh --region REGION`. + + The first deploy takes about 5 minutes, mostly waiting for the CloudFront distribution. When it finishes, the script prints a **Rollout status** section with the CloudFront URL, each slot's weight and role, and the next command to run. + +Every command accepts `--stack-name NAME` and `--region REGION`. Use the same stack name on every command. The first deploy also accepts `--bucket BUCKET` and `--key KEY`; later commands read both from the stack. Run `./deploy.sh --help` for the full list. + +## How it works + +![Architecture: CloudFront with OAC in front of a Lambda Web Function endpoint that splits traffic between blue and green revision slots, plus the release flow from first deploy through canary, shift, promote, and rollback](docs/architecture.png) + +``` +Viewer ──HTTPS──▶ CloudFront ──SigV4 (OAC)──▶ Web Function endpoint (IamAuth) + ├── blue revision (weight from BlueWeight) + └── green revision (weight from GreenWeight) +``` + +`template.yaml` declares: + +- **Two revision slots,** `BlueRevision` and `GreenRevision` (`AWS::Lambda::WebFunctionRevision`). Each is pinned to its own S3 object version of the same key, and passes `REVISION_SLOT`, `CODE_VERSION_ID`, and `DEPLOYED_AT` to the app. +- **One endpoint** (`AWS::Lambda::WebFunctionEndpoint`, `IamAuth`, `HomeRegion`) whose `RevisionWeights` comes from the `BlueWeight` and `GreenWeight` parameters. A slot with weight 0 is left out of the list, because each weight must be from 1 to 100 and the weights must add up to 100. +- **CloudFront with OAC** (origin type `lambda`, signing behavior `always-amz-auth`) and an `AWS::Lambda::ResourcePolicy` that allows only this distribution to invoke the endpoint. Direct requests to the endpoint's own domain get 403. +- **A code bucket policy** that lets `lambda.amazonaws.com` read the code, scoped to this account and to this stack's Web Function revisions. +- **Both log groups** (`/aws/lambda/web/-web-function` and its `.local` companion) with 30-day retention, and throttling and scaling caps on the endpoint. + +### Why two fixed slots + +Revisions are immutable, so new code always means a new revision. If the template declared one revision, every code change would replace the revision that's serving traffic. With two slots, new code only ever goes into the slot that has 0% of traffic. The other slot keeps serving, and it stays available as the rollback target until the next release. + +The endpoint references both slots with `!GetAtt`, so you never copy revision IDs into the template. The SAM `AWS::Serverless::WebFunction` resource also supports `RevisionWeights`, but its keys are literal revision IDs and it generates one revision per deployment, so a canary would need template edits between deployments. + +### Release flow + +| Command | Stack updates | Result | +|---|---|---| +| `./deploy.sh` | 1 | First deploy: same code in both slots, blue 100% | +| `./deploy.sh canary PCT` | 2 | Uploads `src/` into the idle slot (no traffic yet), then sends it PCT% (1–99) | +| `./deploy.sh shift PCT` | 1 | Changes the running canary's share (1–99). No new code | +| `./deploy.sh promote` | 1 | Canary gets 100% and becomes the live slot | +| `./deploy.sh rollback` | 1 | During a canary: 100% back to the live slot. After a promote: back to the previous release | +| `./deploy.sh status` | 0 | Prints slots, weights, deploy times, and the next step | + +`canary` runs two stack updates because the endpoint can route only to revisions that are already `Active`: the first update creates the new revision with no traffic, and the second gives it its share. + +The script guards against unsafe steps. `canary` refuses to run while a canary is in progress, because both slots would be serving traffic. Change the share with `shift`, or run `rollback` first to release different code. Running plain `./deploy.sh` on an existing stack re-applies the template with the current slots and weights; it never ships new code. + +The page and status show only facts fixed when a revision is created: its slot, release, and deploy time. A revision can't know its current weight, because weights change without creating a new revision. + +## Testing + +The commands below use `AWS_REGION`. Set it to the Region you deployed to. This line uses your environment's Region, or else your AWS CLI profile's default: + + export AWS_REGION="${AWS_REGION:-$(aws configure get region)}" + +1. Get the CloudFront URL and confirm the first release: + + URL=$(aws cloudformation describe-stacks --stack-name lambda-web-weighted-rollout --region "${AWS_REGION}" \ + --query "Stacks[0].Outputs[?OutputKey=='CloudFrontUrl'].OutputValue" --output text) + curl -s "${URL}/version" + + Expect `"slot":"blue"` and `"release":"v1"`. Open the URL in a browser to see the page, which has a blue header. + +2. Confirm the endpoint can't be called directly: + + ENDPOINT=$(aws cloudformation describe-stacks --stack-name lambda-web-weighted-rollout --region "${AWS_REGION}" \ + --query "Stacks[0].Outputs[?OutputKey=='WebFunctionEndpointDomain'].OutputValue" --output text) + curl -s -o /dev/null -w "%{http_code}\n" "https://${ENDPOINT}/" + + Expect `403`. + +3. Make a release. In `src/index.js`, change `RELEASE` to `'v2'` and `ACCENT` to another color, then start a canary: + + ./deploy.sh canary 20 + +4. Watch the split. In the browser, choose **Sample 20 requests**, or run: + + for i in $(seq 50); do curl -s "${URL}/version?n=${i}" | grep -o '"release":"v[0-9]*"'; done | sort | uniq -c + + Expect roughly 40 `v1` and 10 `v2`. Small samples vary. + +5. Increase the share, then promote or roll back: + + ./deploy.sh shift 50 + ./deploy.sh promote # all traffic to v2 + ./deploy.sh rollback # back to v1, which is still in the other slot + + Run `./deploy.sh status` at any time to see the current weights. + +### Monitoring a canary + +Web Function metrics have no revision dimension, so they can't separate the canary's errors from the live slot's. The app writes one JSON log line per request with its slot, release, path, and status. In CloudWatch Logs Insights, query the log group `/aws/lambda/web/lambda-web-weighted-rollout-web-function`: + + filter ispresent(slot) + | stats count(*) as requests by slot, release, status + +Decide your error and latency thresholds before you start the canary, then `shift` or `promote` only if the canary meets them. + +## Limitations + +- **Manual promotion.** Lambda Web Functions don't shift traffic or roll back on alarms by themselves. Each step in this pattern is a decision you make. To automate it, run the same commands from a pipeline with your own checks. +- **Two revisions at most.** An endpoint routes to at most two revisions at a time, so there's one canary at a time. +- **Change weights only through the stack.** If you change the endpoint's weights in the console or with the `aws lambda-web` CLI, the stack parameters no longer match what's serving traffic, and the next `deploy.sh` command overwrites your change. +- **Identical releases.** Running `canary` without changing `src/` still creates a new revision with a new code version. The page shows the same release in both slots. + +## Production considerations + +This pattern keeps the baseline small so the rollout mechanics stay clear. Before you use it for production traffic, add what your workload needs: + +- **AWS WAF.** Attach a web ACL to the distribution to filter malicious requests and rate-limit clients. WAF has its own charges. +- **Access logging.** Turn on CloudFront standard logging or real-time logs so you can audit requests and investigate incidents. +- **Custom domain and TLS.** With the default `*.cloudfront.net` certificate, CloudFront doesn't enforce a minimum viewer TLS version. The template sets `MinimumProtocolVersion: TLSv1.2_2021`, which takes effect when you add a custom domain with an AWS Certificate Manager certificate. +- **Log encryption with your own key.** CloudWatch Logs encrypts log data at rest by default. If compliance requires a customer managed key, set `KmsKeyId` on both log groups and allow CloudWatch Logs in the key policy. +- **Cost guardrails.** Set an [AWS Budgets](https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html) alert, and tune the endpoint's `ThrottleConfig` and `ScalingConfig` caps for your expected load. +- **Automated promotion.** Run `deploy.sh` from a pipeline that checks your canary's error rate and latency before each `shift` or `promote`. + +## Cleanup + + export AWS_REGION="${AWS_REGION:-$(aws configure get region)}" # the Region you deployed to + export STACK_NAME=lambda-web-weighted-rollout # deploy.sh default + export CODE_KEY=web-function/app.zip # deploy.sh default + export CODE_BUCKET="${STACK_NAME}-code-$(aws sts get-caller-identity --query Account --output text)-${AWS_REGION}" # deploy.sh default; set your own if you passed --bucket + + sam delete --stack-name "${STACK_NAME}" --region "${AWS_REGION}" + +Deleting the stack removes the Web Function, both revisions, the endpoint, the CloudFront distribution, and the log groups. It does **not** remove the code bucket, which lives outside the stack and also holds the packaged templates under `sam-artifacts/`. The bucket is versioned, so `aws s3 rm` would only add a delete marker and every earlier version would stay and keep billing ([Deleting object versions](https://docs.aws.amazon.com/AmazonS3/latest/userguide/DeletingObjectVersions.html)). + +If the bucket is dedicated to this pattern (for example, the one `./deploy.sh` created), remove every object version and delete marker, then delete the bucket: + + aws s3api list-object-versions --bucket "${CODE_BUCKET}" --region "${AWS_REGION}" \ + --query '[Versions,DeleteMarkers][][].[Key,VersionId]' --output text \ + | while read -r key version; do + aws s3api delete-object --bucket "${CODE_BUCKET}" --region "${AWS_REGION}" \ + --key "$key" --version-id "$version" + done + aws s3 rb "s3://${CODE_BUCKET}" --region "${AWS_REGION}" + +If you brought a shared bucket, don't delete it. Remove only the `${CODE_KEY}` and `sam-artifacts/` versions instead. + +---- +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/lambda-web-weighted-rollout/nodejs/sam/deploy.sh b/lambda-web-weighted-rollout/nodejs/sam/deploy.sh new file mode 100755 index 0000000000..066932e3aa --- /dev/null +++ b/lambda-web-weighted-rollout/nodejs/sam/deploy.sh @@ -0,0 +1,282 @@ +#!/usr/bin/env bash +# +# deploy.sh: deploy lambda-web-weighted-rollout and roll out new releases. +# +# Usage: +# ./deploy.sh [deploy] First deploy (current src/ in both slots, 100% blue), or +# re-apply the template with the current slots and weights +# ./deploy.sh canary PCT Upload src/ into the idle slot, then send it PCT% (1-99) +# ./deploy.sh shift PCT Change the share of the canary in progress (1-99) +# ./deploy.sh promote Send 100% to the canary; it becomes the live slot +# ./deploy.sh rollback Abort the canary in progress (100% back to the live slot), +# or, after a promote, switch back to the previous release +# ./deploy.sh status Show slots, code versions, weights, and the URL +# +# Options: --stack-name NAME --bucket BUCKET --key KEY --region REGION +# stack name : lambda-web-weighted-rollout +# bucket : -code-- (created on first deploy) +# region : --region, then $AWS_REGION, $AWS_DEFAULT_REGION, aws configure +# +set -euo pipefail + +STACK_NAME="lambda-web-weighted-rollout" +CODE_KEY="web-function/app.zip" +CODE_BUCKET="" +REGION_FLAG="" +CMD="" +PCT="" + +die() { echo "ERROR: $*" >&2; exit 1; } + +while [[ $# -gt 0 ]]; do + case "$1" in + --stack-name) STACK_NAME="$2"; shift 2;; + --bucket) CODE_BUCKET="$2"; shift 2;; + --key) CODE_KEY="$2"; shift 2;; + --region) REGION_FLAG="$2"; shift 2;; + -h|--help) sed -n '3,/^set -euo/p' "$0" | sed '$d' | sed 's/^# \{0,1\}//'; exit 0;; + deploy|canary|shift|promote|rollback|status) + if [[ -n "${CMD}" ]]; then die "run one command at a time"; fi + CMD="$1"; shift + if [[ "${CMD}" == "canary" || "${CMD}" == "shift" ]]; then + PCT="${1:-}" + if [[ $# -gt 0 ]]; then shift; fi + fi;; + *) die "unknown argument: $1 (try --help)";; + esac +done +CMD="${CMD:-deploy}" + +if [[ "${CMD}" == "canary" || "${CMD}" == "shift" ]]; then + if ! [[ "${PCT}" =~ ^[0-9]+$ ]] || (( PCT < 1 || PCT > 99 )); then + die "${CMD} needs a percentage from 1 to 99, for example: ./deploy.sh ${CMD} 10" + fi +fi + +REGION="${REGION_FLAG:-${AWS_REGION:-${AWS_DEFAULT_REGION:-$(aws configure get region 2>/dev/null || true)}}}" +[[ -n "${REGION}" ]] || die "no AWS Region. Pass --region, set AWS_REGION, or run 'aws configure'." +case "${REGION}" in + us-east-1|us-east-2|us-west-2|ap-northeast-1|eu-west-1) ;; + *) echo "WARNING: ${REGION} may not support Lambda Web Functions. Check the Lambda documentation." >&2;; +esac + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +stack_exists() { + aws cloudformation describe-stacks --stack-name "${STACK_NAME}" --region "${REGION}" >/dev/null 2>&1 +} +param() { + aws cloudformation describe-stacks --stack-name "${STACK_NAME}" --region "${REGION}" \ + --query "Stacks[0].Parameters[?ParameterKey=='$1'].ParameterValue | [0]" --output text +} +output() { + aws cloudformation describe-stacks --stack-name "${STACK_NAME}" --region "${REGION}" \ + --query "Stacks[0].Outputs[?OutputKey=='$1'].OutputValue | [0]" --output text +} +other() { if [[ "$1" == "blue" ]]; then echo green; else echo blue; fi; } +weight_of() { if [[ "$1" == "blue" ]]; then echo "${BLUE_WEIGHT}"; else echo "${GREEN_WEIGHT}"; fi; } +set_weight() { if [[ "$1" == "blue" ]]; then BLUE_WEIGHT="$2"; else GREEN_WEIGHT="$2"; fi; } +set_version() { if [[ "$1" == "blue" ]]; then BLUE_VERSION="$2"; else GREEN_VERSION="$2"; fi; } +set_deployed() { if [[ "$1" == "blue" ]]; then BLUE_DEPLOYED="$2"; else GREEN_DEPLOYED="$2"; fi; } +now_utc() { date -u +%Y-%m-%dT%H:%M:%SZ; } + +load_state() { + stack_exists || die "stack ${STACK_NAME} not found in ${REGION}. Run ./deploy.sh first." + CODE_BUCKET="$(param CodeBucket)" + CODE_KEY="$(param CodeKey)" + BLUE_VERSION="$(param BlueCodeVersionId)" + GREEN_VERSION="$(param GreenCodeVersionId)" + BLUE_DEPLOYED="$(param BlueDeployedAt)" + GREEN_DEPLOYED="$(param GreenDeployedAt)" + [[ "${BLUE_DEPLOYED}" == "None" ]] && BLUE_DEPLOYED="unknown" + [[ "${GREEN_DEPLOYED}" == "None" ]] && GREEN_DEPLOYED="unknown" + BLUE_WEIGHT="$(param BlueWeight)" + GREEN_WEIGHT="$(param GreenWeight)" + LIVE_SLOT="$(param LiveSlot)" + ROLLBACK_AVAILABLE="$(param RollbackAvailable)" + CANARY_SLOT="$(other "${LIVE_SLOT}")" +} + +ensure_bucket() { + if aws s3api head-bucket --bucket "${CODE_BUCKET}" --region "${REGION}" 2>/dev/null; then + echo "==> Bucket exists: ${CODE_BUCKET}" + local status + status="$(aws s3api get-bucket-versioning --bucket "${CODE_BUCKET}" --region "${REGION}" --query Status --output text)" + [[ "${status}" == "Enabled" ]] || die "bucket ${CODE_BUCKET} must have versioning enabled" + return + fi + echo "==> Creating bucket: ${CODE_BUCKET}" + if [[ "${REGION}" == "us-east-1" ]]; then + aws s3api create-bucket --bucket "${CODE_BUCKET}" --region "${REGION}" >/dev/null + else + aws s3api create-bucket --bucket "${CODE_BUCKET}" --region "${REGION}" \ + --create-bucket-configuration LocationConstraint="${REGION}" >/dev/null + fi + aws s3api put-bucket-versioning --bucket "${CODE_BUCKET}" --region "${REGION}" \ + --versioning-configuration Status=Enabled + aws s3api put-public-access-block --bucket "${CODE_BUCKET}" --region "${REGION}" \ + --public-access-block-configuration \ + BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true + aws s3api put-bucket-encryption --bucket "${CODE_BUCKET}" --region "${REGION}" \ + --server-side-encryption-configuration \ + '{"Rules":[{"ApplyServerSideEncryptionByDefault":{"SSEAlgorithm":"AES256"},"BucketKeyEnabled":true}]}' +} + +# Zips src/ and uploads it; sets NEW_VERSION to the new S3 object version. +upload() { + local zip_dir + zip_dir="$(mktemp -d)" + trap 'rm -rf "${zip_dir}"' RETURN + ( cd "${SCRIPT_DIR}/src" && zip -r -q "${zip_dir}/app.zip" . ) + echo "==> Uploading src/ to s3://${CODE_BUCKET}/${CODE_KEY}" + NEW_VERSION="$(aws s3api put-object --bucket "${CODE_BUCKET}" --key "${CODE_KEY}" \ + --body "${zip_dir}/app.zip" --region "${REGION}" --query VersionId --output text)" + [[ -n "${NEW_VERSION}" && "${NEW_VERSION}" != "None" ]] || die "upload returned no object version" + echo "==> New code version: ${NEW_VERSION}" +} + +apply() { + echo "==> Updating stack: blue ${BLUE_WEIGHT}%, green ${GREEN_WEIGHT}%, live slot ${LIVE_SLOT}" + (( BLUE_WEIGHT + GREEN_WEIGHT == 100 )) || die "weights must add up to 100" + sam deploy \ + --template-file "${SCRIPT_DIR}/template.yaml" \ + --stack-name "${STACK_NAME}" \ + --region "${REGION}" \ + --capabilities CAPABILITY_IAM \ + --s3-bucket "${CODE_BUCKET}" \ + --s3-prefix sam-artifacts \ + --no-confirm-changeset \ + --no-fail-on-empty-changeset \ + --tags pattern=lambda-web-weighted-rollout stack="${STACK_NAME}" \ + --parameter-overrides \ + CodeBucket="${CODE_BUCKET}" \ + CodeKey="${CODE_KEY}" \ + BlueCodeVersionId="${BLUE_VERSION}" \ + GreenCodeVersionId="${GREEN_VERSION}" \ + BlueDeployedAt="${BLUE_DEPLOYED}" \ + GreenDeployedAt="${GREEN_DEPLOYED}" \ + BlueWeight="${BLUE_WEIGHT}" \ + GreenWeight="${GREEN_WEIGHT}" \ + LiveSlot="${LIVE_SLOT}" \ + RollbackAvailable="${ROLLBACK_AVAILABLE}" +} + +# Colors only on a terminal, and never when NO_COLOR is set (https://no-color.org). +if [[ -t 1 && -z "${NO_COLOR:-}" ]]; then + C_BOLD=$'\033[1m'; C_DIM=$'\033[2m'; C_RESET=$'\033[0m' + C_BLUE=$'\033[1;34m'; C_GREEN=$'\033[1;32m'; C_YELLOW=$'\033[1;33m'; C_CYAN=$'\033[1;36m' +else + C_BOLD=""; C_DIM=""; C_RESET=""; C_BLUE=""; C_GREEN=""; C_YELLOW=""; C_CYAN="" +fi +RULE="======================================================================" + +show_status() { + load_state + local slot role color code deployed + echo + echo "${C_CYAN}${RULE}${C_RESET}" + echo "${C_BOLD} Rollout status${C_RESET}" + echo "${C_CYAN}${RULE}${C_RESET}" + echo " Stack: ${STACK_NAME} (${REGION})" + echo " URL: ${C_BOLD}$(output CloudFrontUrl)${C_RESET}" + echo + for slot in blue green; do + if [[ "${slot}" == "${LIVE_SLOT}" ]]; then role="live"; elif (( $(weight_of "${slot}") > 0 )); then role="canary"; else role="idle"; fi + if [[ "${slot}" == "blue" ]]; then color="${C_BLUE}"; code="${BLUE_VERSION}"; deployed="${BLUE_DEPLOYED}"; else color="${C_GREEN}"; code="${GREEN_VERSION}"; deployed="${GREEN_DEPLOYED}"; fi + printf " %s%-6s%s %3s%% %-7s deployed %-20s ${C_DIM}code %s${C_RESET}\n" "${color}" "${slot}" "${C_RESET}" "$(weight_of "${slot}")" "${role}" "${deployed}" "${code}" + done + echo + if (( $(weight_of "${CANARY_SLOT}") > 0 )); then + echo " ${C_YELLOW}Canary in progress on ${CANARY_SLOT}.${C_RESET}" + echo " ${C_YELLOW}Next: ./deploy.sh shift PCT (change canary %) | promote | rollback${C_RESET}" + elif [[ "${ROLLBACK_AVAILABLE}" == "yes" ]]; then + echo " ${C_YELLOW}The ${CANARY_SLOT} slot holds the previous release.${C_RESET}" + echo " ${C_YELLOW}Next: ./deploy.sh rollback switches back to it.${C_RESET}" + else + echo " ${C_YELLOW}Next: change src/, then ./deploy.sh canary 10${C_RESET}" + fi + echo "${C_CYAN}${RULE}${C_RESET}" + echo +} + +case "${CMD}" in + deploy) + if stack_exists; then + load_state + echo "==> Stack exists. Re-applying the template with the current slots and weights." + echo " To release new code, use: ./deploy.sh canary 10" + apply + else + ACCOUNT_ID="$(aws sts get-caller-identity --query Account --output text)" + CODE_BUCKET="${CODE_BUCKET:-${STACK_NAME}-code-${ACCOUNT_ID}-${REGION}}" + ensure_bucket + upload + BLUE_VERSION="${NEW_VERSION}"; GREEN_VERSION="${NEW_VERSION}" + BLUE_DEPLOYED="$(now_utc)"; GREEN_DEPLOYED="${BLUE_DEPLOYED}" + BLUE_WEIGHT=100; GREEN_WEIGHT=0; LIVE_SLOT=blue; ROLLBACK_AVAILABLE=no + apply + fi + show_status;; + + canary) + load_state + if (( $(weight_of "${CANARY_SLOT}") > 0 )); then + die "a canary is already in progress on ${CANARY_SLOT} ($(weight_of "${CANARY_SLOT}")%). Nothing was changed. + To change its share: ./deploy.sh shift ${PCT} + To finish it: ./deploy.sh promote + To release different code: ./deploy.sh rollback, then ./deploy.sh canary ${PCT}" + fi + upload + # Step 1: replace the idle slot's revision while it has no traffic. + set_version "${CANARY_SLOT}" "${NEW_VERSION}" + set_deployed "${CANARY_SLOT}" "$(now_utc)" + ROLLBACK_AVAILABLE=no + echo "==> Step 1 of 2: create the ${CANARY_SLOT} revision with the new code (no traffic yet)" + apply + # Step 2: route traffic to it now that it exists and is Active. + set_weight "${CANARY_SLOT}" "${PCT}" + set_weight "${LIVE_SLOT}" "$(( 100 - PCT ))" + echo "==> Step 2 of 2: send ${PCT}% of traffic to ${CANARY_SLOT}" + apply + show_status;; + + shift) + load_state + (( $(weight_of "${CANARY_SLOT}") > 0 )) || die "no canary in progress. Start one with: ./deploy.sh canary 10" + set_weight "${CANARY_SLOT}" "${PCT}" + set_weight "${LIVE_SLOT}" "$(( 100 - PCT ))" + apply + show_status;; + + promote) + load_state + (( $(weight_of "${CANARY_SLOT}") > 0 )) || die "no canary in progress to promote" + set_weight "${CANARY_SLOT}" 100 + set_weight "${LIVE_SLOT}" 0 + LIVE_SLOT="${CANARY_SLOT}" + ROLLBACK_AVAILABLE=yes + apply + show_status;; + + rollback) + load_state + if (( $(weight_of "${CANARY_SLOT}") > 0 )); then + echo "==> Aborting the canary: 100% back to ${LIVE_SLOT}" + set_weight "${LIVE_SLOT}" 100 + set_weight "${CANARY_SLOT}" 0 + ROLLBACK_AVAILABLE=no + elif [[ "${ROLLBACK_AVAILABLE}" == "yes" ]]; then + echo "==> Switching back to the previous release in the ${CANARY_SLOT} slot" + set_weight "${CANARY_SLOT}" 100 + set_weight "${LIVE_SLOT}" 0 + LIVE_SLOT="${CANARY_SLOT}" + ROLLBACK_AVAILABLE=no + else + die "nothing to roll back: no canary in progress and no previous release in the idle slot" + fi + apply + show_status;; + + status) + show_status;; +esac diff --git a/lambda-web-weighted-rollout/nodejs/sam/docs/architecture.png b/lambda-web-weighted-rollout/nodejs/sam/docs/architecture.png new file mode 100644 index 0000000000..327ccca11a Binary files /dev/null and b/lambda-web-weighted-rollout/nodejs/sam/docs/architecture.png differ diff --git a/lambda-web-weighted-rollout/nodejs/sam/example-pattern.json b/lambda-web-weighted-rollout/nodejs/sam/example-pattern.json new file mode 100644 index 0000000000..d599e0abc0 --- /dev/null +++ b/lambda-web-weighted-rollout/nodejs/sam/example-pattern.json @@ -0,0 +1,55 @@ +{ + "title": "Weighted revision rollouts for an AWS Lambda Web Function", + "description": "Canary, promote and rollback for a Lambda Web Function behind Amazon CloudFront, using two revision slots and stack-driven revision weights", + "language": "Node.js", + "level": "300", + "framework": "AWS SAM", + "introBox": { + "headline": "How it works", + "text": [ + "The SAM template declares two fixed Lambda Web Function revisions, blue and green, each pinned to its own S3 object version, and one IamAuth endpoint whose revision weights come from stack parameters. New code always goes into the slot that has no traffic, so the live revision is never replaced mid-rollout and the previous release stays available for rollback.", + "A deploy script drives the release: canary uploads new code into the idle slot and gives it a share of traffic, shift changes that share, promote moves all traffic to the canary, and rollback returns traffic to the previous release. Amazon CloudFront with Origin Access Control fronts the endpoint, and the sample page shows which slot served each request and can sample the live traffic split." + ] + }, + "gitHub": { + "template": { + "templateFile": "template.yaml" + } + }, + "resources": { + "bullets": [ + { + "text": "Lambda Web Functions deployment patterns", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/web-functions-deployment.html" + }, + { + "text": "AWS SAM RevisionWeights property for Web Functions", + "link": "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-webfunction-revisionweights.html" + } + ] + }, + "deploy": { + "text": [ + "./deploy.sh" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "See the GitHub repo for detailed cleanup instructions." + ] + }, + "authors": [ + { + "name": "Shekhar Shrinivasan", + "image": "https://avatars.githubusercontent.com/u/58206425?s=400&u=90899732423049a2e45523f631ab0379330aec62&v=4", + "bio": "Senior Technical Consultant (TAM)", + "linkedin": "shekhar-shrinivasan", + "twitter": "" + } + ] +} diff --git a/lambda-web-weighted-rollout/nodejs/sam/lambda-web-weighted-rollout.json b/lambda-web-weighted-rollout/nodejs/sam/lambda-web-weighted-rollout.json new file mode 100644 index 0000000000..a8855f411b --- /dev/null +++ b/lambda-web-weighted-rollout/nodejs/sam/lambda-web-weighted-rollout.json @@ -0,0 +1,74 @@ +{ + "title": "Weighted revision rollouts for an AWS Lambda Web Function", + "description": "Canary, promote and rollback for a Lambda Web Function behind Amazon CloudFront, using two revision slots and stack-driven revision weights", + "language": "Node.js", + "level": "300", + "framework": "AWS SAM", + "introBox": { + "headline": "How it works", + "text": [ + "The SAM template declares two fixed Lambda Web Function revisions, blue and green, each pinned to its own S3 object version, and one IamAuth endpoint whose revision weights come from stack parameters. New code always goes into the slot that has no traffic, so the live revision is never replaced mid-rollout and the previous release stays available for rollback.", + "A deploy script drives the release: canary uploads new code into the idle slot and gives it a share of traffic, shift changes that share, promote moves all traffic to the canary, and rollback returns traffic to the previous release. Amazon CloudFront with Origin Access Control fronts the endpoint, and the sample page shows which slot served each request and can sample the live traffic split." + ] + }, + "gitHub": { + "template": { + "templateFile": "template.yaml" + } + }, + "resources": { + "bullets": [ + { + "text": "Lambda Web Functions deployment patterns", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/web-functions-deployment.html" + }, + { + "text": "AWS SAM RevisionWeights property for Web Functions", + "link": "https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-property-webfunction-revisionweights.html" + } + ] + }, + "deploy": { + "text": [ + "./deploy.sh" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "See the GitHub repo for detailed cleanup instructions." + ] + }, + "authors": [ + { + "name": "Shekhar Shrinivasan", + "image": "https://avatars.githubusercontent.com/u/58206425?s=400&u=90899732423049a2e45523f631ab0379330aec62&v=4", + "bio": "Senior Technical Consultant (TAM)", + "linkedin": "shekhar-shrinivasan", + "twitter": "" + } + ], + "patternArch": { + "icon1": { + "x": 20, + "y": 50, + "service": "cloudfront", + "label": "Amazon CloudFront" + }, + "icon2": { + "x": 80, + "y": 50, + "service": "lambda-event-functions", + "label": "AWS Lambda\nWeb Function" + }, + "line1": { + "from": "icon1", + "to": "icon2", + "label": "Signed request (OAC)" + } + } +} diff --git a/lambda-web-weighted-rollout/nodejs/sam/src/index.js b/lambda-web-weighted-rollout/nodejs/sam/src/index.js new file mode 100644 index 0000000000..a262dbab23 --- /dev/null +++ b/lambda-web-weighted-rollout/nodejs/sam/src/index.js @@ -0,0 +1,116 @@ +// Lambda Web Function app for lambda-web-weighted-rollout. +// Change RELEASE (and ACCENT) before `./deploy.sh canary 10` to see the new release +// take a share of the traffic. +import http from 'node:http'; +import { createHash, randomUUID } from 'node:crypto'; + +const RELEASE = 'v1'; +const ACCENT = '#2563eb'; + +// The runtime sets AWS_LAMBDA_HTTP_ENDPOINT to host:port. Locally, fall back to 127.0.0.1:3000. +const endpoint = process.env.AWS_LAMBDA_HTTP_ENDPOINT || '127.0.0.1:3000'; +const sep = endpoint.lastIndexOf(':'); +const HOST = endpoint.slice(0, sep); +const PORT = Number(endpoint.slice(sep + 1)); + +// Set per revision in template.yaml. A revision can't know its current traffic weight +// (weights change without a new revision), so the page shows only what is fixed at +// creation: the slot, the release, and when this slot's code was deployed. +const SLOT = process.env.REVISION_SLOT || 'local'; +const CODE_VERSION = process.env.CODE_VERSION_ID || 'local'; +const DEPLOYED_AT = process.env.DEPLOYED_AT || 'unknown'; +const ENVIRONMENT_ID = randomUUID().slice(0, 8); +const SLOT_COLOR = { blue: '#1d4ed8', green: '#15803d' }[SLOT] || '#6b7280'; + +const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + +function deployedLabel() { + const d = new Date(DEPLOYED_AT); + if (Number.isNaN(d.getTime())) return 'unknown'; + return d.toISOString().replace('T', ' ').replace(/:\d\d\.\d+Z$|:\d\dZ$/, ' UTC'); +} + +// Samples /version from the browser so the page shows the real split right now. +// cache: 'no-store' and a unique query string make every call reach the endpoint. +const SAMPLE_SCRIPT = ` +const btn = document.getElementById('sample'); +const out = document.getElementById('result'); +btn.addEventListener('click', async () => { + btn.disabled = true; + const counts = { blue: 0, green: 0 }; + let failed = 0; + for (let i = 0; i < 20; i++) { + out.textContent = 'Sampling... ' + (i + 1) + ' of 20'; + try { + const r = await fetch('/version?n=' + Date.now() + '-' + i, { cache: 'no-store' }); + const v = await r.json(); + counts[v.slot] = (counts[v.slot] || 0) + 1; + } catch (e) { failed++; } + } + const bar = (n) => '\\u2588'.repeat(n); + out.innerHTML = 'blue ' + bar(counts.blue) + ' ' + counts.blue + '' + + 'green ' + bar(counts.green) + ' ' + counts.green + '' + + (failed ? '' + failed + ' failed' : ''); + btn.disabled = false; +});`; + +function page() { + return ` + +Weighted rollout: ${esc(SLOT)} ${esc(RELEASE)} + +
+

Served by: ${esc(SLOT)}

AWS Lambda Web Function behind Amazon CloudFront

+
+

${esc(RELEASE)}  deployed ${esc(deployedLabel())}

+

Refresh to see which revision serves each request. During a canary, requests are split between blue and green.

+

+
Shows how the endpoint is splitting traffic right now.
+

Current weights and next steps: ./deploy.sh status

+
+
+ +`; +} + +// The CSP allows only this page's own inline script, by hash. +const SCRIPT_HASH = createHash('sha256').update(SAMPLE_SCRIPT).digest('base64'); +const CSP = `default-src 'none'; style-src 'unsafe-inline'; script-src 'sha256-${SCRIPT_HASH}'; connect-src 'self'`; + +const server = http.createServer((req, res) => { + const path = (req.url || '/').split('?')[0]; + let status = 200; + const headers = { 'cache-control': 'no-store', 'x-revision-slot': SLOT, 'x-release': RELEASE, 'x-content-type-options': 'nosniff' }; + if (path === '/health') { + res.writeHead(200, { ...headers, 'content-type': 'text/plain' }).end('ok'); + } else if (path === '/version') { + res.writeHead(200, { ...headers, 'content-type': 'application/json' }) + .end(JSON.stringify({ slot: SLOT, release: RELEASE, deployedAt: DEPLOYED_AT, codeVersion: CODE_VERSION, environment: ENVIRONMENT_ID })); + } else if (path === '/') { + res.writeHead(200, { ...headers, 'content-type': 'text/html; charset=utf-8', 'content-security-policy': CSP }).end(page()); + } else { + status = 404; + res.writeHead(404, { ...headers, 'content-type': 'text/plain' }).end('not found'); + } + // One structured line per request, so you can compare the canary with the live slot in logs. + console.log(JSON.stringify({ slot: SLOT, release: RELEASE, codeVersion: CODE_VERSION, path, status })); +}); + +server.listen(PORT, HOST, () => console.log(`Listening on ${HOST}:${PORT} (slot ${SLOT}, release ${RELEASE})`)); +process.on('SIGTERM', () => server.close(() => process.exit(0))); diff --git a/lambda-web-weighted-rollout/nodejs/sam/src/package.json b/lambda-web-weighted-rollout/nodejs/sam/src/package.json new file mode 100644 index 0000000000..51480e2626 --- /dev/null +++ b/lambda-web-weighted-rollout/nodejs/sam/src/package.json @@ -0,0 +1,11 @@ +{ + "name": "lambda-web-weighted-rollout-app", + "version": "1.0.0", + "description": "Lambda Web Function app that reports which revision slot served each request.", + "type": "module", + "main": "index.js", + "private": true, + "scripts": { + "start": "node index.js" + } +} diff --git a/lambda-web-weighted-rollout/nodejs/sam/template.yaml b/lambda-web-weighted-rollout/nodejs/sam/template.yaml new file mode 100644 index 0000000000..5755c7ff2e --- /dev/null +++ b/lambda-web-weighted-rollout/nodejs/sam/template.yaml @@ -0,0 +1,277 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + Weighted revision rollouts (canary, promote, rollback) for an AWS Lambda Web Function + behind Amazon CloudFront with Origin Access Control. Two fixed revision slots (blue and + green) share one IamAuth endpoint; stack parameters set each slot's code version and + traffic weight. + +# How a release works (deploy.sh drives these parameters for you): +# 1. Live slot serves 100%. The idle slot has weight 0 and receives no traffic. +# 2. canary: the idle slot gets the new code version (its revision is replaced while it +# has no traffic), then a second update gives it a small weight. +# 3. promote: the canary slot gets 100% and becomes the live slot. +# 4. rollback: the live slot gets 100% again. The canary revision is kept but unused. +# A revision is only ever replaced while it has weight 0, so the endpoint never routes +# to a revision that is being replaced. + +Parameters: + CodeBucket: + Type: String + Description: > + Versioning-enabled S3 bucket that holds the deployment package. Use a bucket + dedicated to this stack: the stack replaces its bucket policy. + CodeKey: + Type: String + Default: web-function/app.zip + Description: S3 key of the deployment package. Both slots use this key, pinned to different object versions. + BlueCodeVersionId: + Type: String + MinLength: 1 + Description: S3 object version of the code in the blue slot. + GreenCodeVersionId: + Type: String + MinLength: 1 + Description: S3 object version of the code in the green slot. + BlueDeployedAt: + Type: String + Default: unknown + Description: UTC time the blue slot's code was uploaded. Set by deploy.sh; shown on the page. + GreenDeployedAt: + Type: String + Default: unknown + Description: UTC time the green slot's code was uploaded. Set by deploy.sh; shown on the page. + BlueWeight: + Type: Number + MinValue: 0 + MaxValue: 100 + Default: 100 + Description: Percentage of traffic for the blue slot. BlueWeight + GreenWeight must equal 100. + GreenWeight: + Type: Number + MinValue: 0 + MaxValue: 100 + Default: 0 + Description: Percentage of traffic for the green slot. BlueWeight + GreenWeight must equal 100. + LiveSlot: + Type: String + AllowedValues: [blue, green] + Default: blue + Description: The slot that holds the current release. The other slot is the canary or idle slot. + RollbackAvailable: + Type: String + AllowedValues: ['yes', 'no'] + Default: 'no' + Description: > + Set by deploy.sh. 'yes' means the idle slot still holds the previous release, so + deploy.sh rollback can switch back to it. + +Conditions: + # A revision with weight 0 must be left out of RevisionWeights (each weight is 1-100). + BlueOnly: !Equals [!Ref GreenWeight, 0] + GreenOnly: !Equals [!Ref BlueWeight, 0] + +Resources: + + # Lambda reads the code as the lambda.amazonaws.com service principal. Scoped to this + # account and to this stack's Web Function revisions (confused-deputy protection). Uses + # the computed function name, not !Ref, to avoid a dependency cycle. + CodeBucketPolicy: + Type: AWS::S3::BucketPolicy + Properties: + Bucket: !Ref CodeBucket + PolicyDocument: + Version: '2012-10-17' + Statement: + - Sid: AllowLambdaWebFunctionCodeAccess + Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: + - s3:GetObject + - s3:GetObjectVersion + Resource: !Sub "arn:${AWS::Partition}:s3:::${CodeBucket}/*" + Condition: + StringEquals: + aws:SourceAccount: !Ref AWS::AccountId + ArnLike: + aws:SourceArn: !Sub "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:web-function/${AWS::StackName}-web-function/revision/*" + + WebFunctionExecutionRole: + Type: AWS::IAM::Role + Properties: + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Principal: + Service: lambda.amazonaws.com + Action: sts:AssumeRole + ManagedPolicyArns: + - !Sub arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole + + # Lambda creates these log groups with no expiration if they don't exist first. + WebFunctionLogGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub /aws/lambda/web/${AWS::StackName}-web-function + RetentionInDays: 30 + WebFunctionLocalLogGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub /aws/lambda/web/${AWS::StackName}-web-function.local + RetentionInDays: 30 + + WebFunction: + Type: AWS::Lambda::WebFunction + Properties: + FunctionName: !Sub ${AWS::StackName}-web-function + Tags: + - Key: pattern + Value: lambda-web-weighted-rollout + + # Blue and green slots. Each is an immutable revision pinned to one S3 object version. + # Changing a slot's code version replaces its revision; deploy.sh only does that while + # the slot has weight 0. REVISION_SLOT and CODE_VERSION_ID let the app report which + # revision served each request, because Web Function metrics have no revision dimension. + BlueRevision: + Type: AWS::Lambda::WebFunctionRevision + DependsOn: [CodeBucketPolicy, WebFunctionLogGroup, WebFunctionLocalLogGroup] + Properties: + FunctionName: !Ref WebFunction + Description: Blue slot + BuildConfig: + CodeConfig: + S3Object: + Bucket: !Ref CodeBucket + Key: !Ref CodeKey + VersionId: !Ref BlueCodeVersionId + RuntimeConfig: + Runtime: nodejs24.x + ServiceConfig: + ExecutionRoleArn: !GetAtt WebFunctionExecutionRole.Arn + TimeoutSeconds: 30 + EnvironmentVariables: + REVISION_SLOT: blue + CODE_VERSION_ID: !Ref BlueCodeVersionId + DEPLOYED_AT: !Ref BlueDeployedAt + + GreenRevision: + Type: AWS::Lambda::WebFunctionRevision + DependsOn: [CodeBucketPolicy, WebFunctionLogGroup, WebFunctionLocalLogGroup] + Properties: + FunctionName: !Ref WebFunction + Description: Green slot + BuildConfig: + CodeConfig: + S3Object: + Bucket: !Ref CodeBucket + Key: !Ref CodeKey + VersionId: !Ref GreenCodeVersionId + RuntimeConfig: + Runtime: nodejs24.x + ServiceConfig: + ExecutionRoleArn: !GetAtt WebFunctionExecutionRole.Arn + TimeoutSeconds: 30 + EnvironmentVariables: + REVISION_SLOT: green + CODE_VERSION_ID: !Ref GreenCodeVersionId + DEPLOYED_AT: !Ref GreenDeployedAt + + # Disabled auto-deployment: Lambda never moves traffic on its own; RevisionWeights decides. + WebFunctionEndpoint: + Type: AWS::Lambda::WebFunctionEndpoint + Properties: + FunctionName: !Ref WebFunction + EndpointName: live + EndpointType: HomeRegion + AuthType: IamAuth + RevisionWeights: !If + - BlueOnly + - - RevisionId: !GetAtt BlueRevision.RevisionId + Weight: 100 + - !If + - GreenOnly + - - RevisionId: !GetAtt GreenRevision.RevisionId + Weight: 100 + - - RevisionId: !GetAtt BlueRevision.RevisionId + Weight: !Ref BlueWeight + - RevisionId: !GetAtt GreenRevision.RevisionId + Weight: !Ref GreenWeight + # Caps so a sample can't consume the account's regional capacity. Tune for your load. + ScalingConfig: + MaxEnvironments: 10 + ThrottleConfig: + RateLimit: 100 + + # For Web Function origins CloudFront requires origin type 'lambda' and 'always-amz-auth'. + OriginAccessControl: + Type: AWS::CloudFront::OriginAccessControl + Properties: + OriginAccessControlConfig: + Name: !Sub ${AWS::StackName}-oac + OriginAccessControlOriginType: lambda + SigningBehavior: always-amz-auth + SigningProtocol: sigv4 + + Distribution: + Type: AWS::CloudFront::Distribution + Properties: + DistributionConfig: + Comment: !Ref AWS::StackName + Enabled: true + HttpVersion: http2 + PriceClass: PriceClass_100 + Origins: + - Id: web-function + DomainName: !GetAtt WebFunctionEndpoint.DomainName + OriginAccessControlId: !GetAtt OriginAccessControl.Id + CustomOriginConfig: + OriginProtocolPolicy: https-only + OriginSSLProtocols: [TLSv1.2] + DefaultCacheBehavior: + TargetOriginId: web-function + ViewerProtocolPolicy: redirect-to-https + AllowedMethods: [GET, HEAD, OPTIONS] + # Managed CachingDisabled: every request reaches the endpoint, so you see the + # real traffic split. No origin request policy: no viewer headers, cookies or + # query strings are forwarded, and Host stays the endpoint domain. + CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad + # With the default *.cloudfront.net certificate, CloudFront doesn't enforce a + # minimum viewer TLS version. The setting takes effect when you add a custom + # domain with an ACM certificate (see Production considerations in the README). + ViewerCertificate: + CloudFrontDefaultCertificate: true + MinimumProtocolVersion: TLSv1.2_2021 + + # Web Functions don't support AWS::Lambda::Permission. Allow only this distribution. + EndpointResourcePolicy: + Type: AWS::Lambda::ResourcePolicy + Properties: + ResourceArn: !GetAtt WebFunction.FunctionArn + PolicyDocument: + Version: '2012-10-17' + Statement: + - Sid: AllowCloudFrontOAC + Effect: Allow + Principal: + Service: cloudfront.amazonaws.com + Action: lambda:InvokeWebFunctionEndpoint + Resource: !GetAtt WebFunctionEndpoint.EndpointArn + Condition: + StringEquals: + AWS:SourceArn: !Sub arn:${AWS::Partition}:cloudfront::${AWS::AccountId}:distribution/${Distribution} + +Outputs: + CloudFrontUrl: + Description: Public URL. Refresh it to watch the traffic split. + Value: !Sub https://${Distribution.DomainName} + WebFunctionEndpointDomain: + Description: The endpoint's own domain. Unsigned requests get 403. + Value: !GetAtt WebFunctionEndpoint.DomainName + BlueRevisionId: + Value: !GetAtt BlueRevision.RevisionId + GreenRevisionId: + Value: !GetAtt GreenRevision.RevisionId + LogGroupName: + Value: !Ref WebFunctionLogGroup