@flagsmith/serverless-plugin-canary-deployments

中文文档
2.0.1发布于 2026/09/29ISCCommonJS构建来源已验证近 30 天下载 2250

A Serverless plugin to implement canary deployment of Lambda functions

原始使用文档
文档目录23 节
  1. Contents
  2. Installation
  3. IAM Permissions
  4. CloudFormation
  5. CodeDeploy
  6. Lambda
  7. IAM
  8. CloudWatch (for alarms)
  9. Service-specific permissions
  10. CodeDeploy Service Role
  11. Lambda Execution Role
  12. Usage
  13. Configuration
  14. Default configurations
  15. Canary Alarms
  16. Configuration
  17. Preset: errors
  18. Alarm Properties
  19. Generated Resources
  20. Using with Standard Alarms
  21. How it works
  22. Limitations
  23. License

npm version

Serverless Plugin Canary Deployments

A Serverless plugin to implement canary deployments of Lambda functions, making use of the traffic shifting feature in combination with AWS CodeDeploy

Contents

Installation

npm i --save-dev @flagsmith/serverless-plugin-canary-deployments

IAM Permissions

This plugin creates and manages several AWS resources. The IAM user or role deploying your Serverless service needs the following permissions:

CloudFormation

cloudformation:CreateStack
cloudformation:UpdateStack
cloudformation:DeleteStack
cloudformation:DescribeStacks
cloudformation:DescribeStackEvents
cloudformation:DescribeStackResource
cloudformation:GetTemplate
cloudformation:ValidateTemplate

CodeDeploy

codedeploy:CreateApplication
codedeploy:DeleteApplication
codedeploy:GetApplication
codedeploy:CreateDeploymentGroup
codedeploy:DeleteDeploymentGroup
codedeploy:UpdateDeploymentGroup
codedeploy:GetDeploymentGroup
codedeploy:CreateDeployment
codedeploy:GetDeployment
codedeploy:StopDeployment

Lambda

lambda:CreateAlias
lambda:DeleteAlias
lambda:UpdateAlias
lambda:GetAlias
lambda:GetFunction
lambda:GetFunctionConfiguration
lambda:PublishVersion
lambda:ListVersionsByFunction
lambda:UpdateFunctionCode
lambda:UpdateFunctionConfiguration
lambda:AddPermission
lambda:RemovePermission

IAM

iam:CreateRole
iam:DeleteRole
iam:GetRole
iam:PassRole
iam:AttachRolePolicy
iam:DetachRolePolicy
iam:PutRolePolicy
iam:DeleteRolePolicy

CloudWatch (for alarms)

cloudwatch:PutMetricAlarm
cloudwatch:DeleteAlarms
cloudwatch:DescribeAlarms
cloudwatch:PutCompositeAlarm

Service-specific permissions

Depending on which event sources trigger your Lambda functions, you may also need:

Event SourcePermissions
API Gatewayapigateway:* on your API resources
SNSsns:Subscribe, sns:Unsubscribe
S3s3:PutBucketNotification
CloudWatch Eventsevents:PutRule, events:PutTargets, events:RemoveTargets, events:DeleteRule
CloudWatch Logslogs:PutSubscriptionFilter, logs:DeleteSubscriptionFilter
IoTiot:CreateTopicRule, iot:ReplaceTopicRule, iot:DeleteTopicRule
AppSyncappsync:UpdateDataSource
ALB/NLBelasticloadbalancing:RegisterTargets, elasticloadbalancing:DeregisterTargets

CodeDeploy Service Role

The plugin creates a CodeDeploy service role with the following managed policies attached:

  • arn:aws:iam::aws:policy/service-role/AWSCodeDeployRoleForLambdaLimited
  • arn:aws:iam::aws:policy/AWSLambda_FullAccess

If you provide your own codeDeployRole, ensure it has equivalent permissions. See example-code-deploy-policy.json for reference.

Lambda Execution Role

For pre/post traffic hooks to report deployment status, the plugin adds this permission to your Lambda execution role:

codedeploy:PutLifecycleEventHookExecutionStatus

Usage

To enable gradual deployments for Lambda functions, your serverless.yml should look like this:

service: canary-deployments
provider:
  name: aws
  runtime: nodejs6.10
  iamRoleStatements:
    - Effect: Allow
      Action:
        - codedeploy:*
      Resource:
        - "*"

plugins:
  - serverless-plugin-canary-deployments

functions:
  hello:
    handler: handler.hello
    events:
      - http: GET hello
    deploymentSettings:
      type: Linear10PercentEvery1Minute
      alias: Live
      preTrafficHook: preHook
      postTrafficHook: postHook
      alarms:
        - FooAlarm          # When a string is provided, it expects the alarm Logical ID
        - name: BarAlarm    # When an object is provided, it expects the alarm name in the name property

  preHook:
    handler: hooks.pre
  postHook:
    handler: hooks.post

You can see a working example in the example folder.

Configuration

  • type: (required) defines how the traffic will be shifted between Lambda function versions. It must be one of the following:
    • Canary10Percent5Minutes: shifts 10 percent of traffic in the first increment. The remaining 90 percent is deployed five minutes later.
    • Canary10Percent10Minutes: shifts 10 percent of traffic in the first increment. The remaining 90 percent is deployed 10 minutes later.
    • Canary10Percent15Minutes: shifts 10 percent of traffic in the first increment. The remaining 90 percent is deployed 15 minutes later.
    • Canary10Percent30Minutes: shifts 10 percent of traffic in the first increment. The remaining 90 percent is deployed 30 minutes later.
    • Linear10PercentEvery1Minute: shifts 10 percent of traffic every minute until all traffic is shifted.
    • Linear10PercentEvery2Minutes: shifts 10 percent of traffic every two minutes until all traffic is shifted.
    • Linear10PercentEvery3Minutes: shifts 10 percent of traffic every three minutes until all traffic is shifted.
    • Linear10PercentEvery10Minutes: shifts 10 percent of traffic every 10 minutes until all traffic is shifted.
    • AllAtOnce: shifts all the traffic to the new version, useful when you only need to execute the validation hooks.
  • alias: (required) name that will be used to create the Lambda function alias.
  • preTrafficHook: (optional) validation Lambda function that runs before traffic shifting. It must use the CodeDeploy SDK to notify about this step's success or failure (more info here).
  • postTrafficHook: (optional) validation Lambda function that runs after traffic shifting. It must use the CodeDeploy SDK to notify about this step's success or failure (more info here)
  • alarms: (optional) list of CloudWatch alarms. If any of them is triggered during the deployment, the associated Lambda function will automatically roll back to the previous version.
  • triggerConfigurations: (optional) list of CodeDeploy Triggers. See more details in the CodeDeploy TriggerConfiguration Documentation, or this CodeDeploy notifications guide for example uses

Default configurations

You can set default values for all functions in a top-level custom deploymentSettings section. E.g.:

custom:
  deploymentSettings:
    codeDeployRole: some_arn_value
    codeDeployRolePermissionsBoundary: some_arn_value
    stages:
      - dev
      - prod

functions:
  ...

Some values are only available as top-level configurations. They are:

  • codeDeployRole: (optional) an ARN specifying an existing IAM role for CodeDeploy. If absent, one will be created for you. See the codeDeploy policy for an example of what is needed.
  • codeDeployRolePermissionsBoundary: (optional) an ARN specifying an existing IAM permissions boundary, this permission boundary is set on the code deploy that is being created when codeDeployRole is not defined.
  • stages: (optional) list of stages where you want to deploy your functions gradually. If not present, it assumes that are all of them.

Canary Alarms

Canary alarms are version-specific CloudWatch alarms that monitor only the new Lambda version during deployment. This solves the "pre-existing alarm" problem where a deployment fails because the previous version's errors keep an alarm in ALARM state.

canaryAlarms creates CloudWatch alarms with the ExecutedVersion dimension, which only monitors metrics from the specific Lambda version being deployed.

functions:
  hello:
    handler: handler.hello
    deploymentSettings:
      type: Canary10Percent5Minutes
      alias: Live
      canaryAlarms:
        - preset: errors    # Use preset configuration

Configuration

  • canaryAlarms: (optional) list of version-specific CloudWatch alarms to create. Each alarm can be:

Using a preset:

canaryAlarms:
  - preset: errors            # Use 'errors' preset
  - preset: errors            # Override preset values
    threshold: 5

Using custom configuration:

canaryAlarms:
  - metric: Duration
    threshold: 5000
    comparisonOperator: GreaterThanThreshold
    statistic: Average

Preset: errors

The errors preset creates an alarm with these defaults:

PropertyValue
metricErrors
namespaceAWS/Lambda
statisticSum
period60
evaluationPeriods1
datapointsToAlarm1
threshold1000
comparisonOperatorGreaterThanThreshold
treatMissingDatanotBreaching

Alarm Properties

Each alarm in canaryAlarms must use either a preset or a custom metric configuration:

Preset-based alarm (requires preset):

PropertyTypeRequiredDescription
presetstringyesPreset name (errors)

Any other property below can be specified to override the preset defaults.

Custom metric alarm (requires metric and threshold):

PropertyTypeRequiredDefaultDescription
metricstringyes-CloudWatch metric name
thresholdnumberyes-Alarm threshold value
namespacestringnoAWS/LambdaCloudWatch namespace
comparisonOperatorstringnoGreaterThanThresholdComparison operator
statisticstringnoSumMetric statistic
periodnumberno60Period in seconds
evaluationPeriodsnumberno1Number of periods to evaluate
datapointsToAlarmnumberno1Datapoints to trigger alarm
treatMissingDatastringnonotBreachingHow to treat missing data

Metric math alarm (requires metrics, expression, and threshold):

Use CloudWatch Metric Math to combine multiple metrics in a single alarm — for example, to alarm on error rate rather than absolute error count:

canaryAlarms:
  - name: errorrate
    metrics:
      - id: errors
        metric: Errors
        statistic: Sum
      - id: invocations
        metric: Invocations
        statistic: Sum
    expression: "errors / invocations"
    threshold: 0.05
    comparisonOperator: GreaterThanThreshold
PropertyTypeRequiredDefaultDescription
namestringno-Logical name (used in CloudFormation logical ID)
metricsarrayyes-List of metrics to use in the expression
expressionstringyes-Metric math expression referencing metric IDs
thresholdnumberyes-Alarm threshold value (can be a float)
namespacestringnoAWS/LambdaCloudWatch namespace for all metrics
comparisonOperatorstringnoGreaterThanThresholdComparison operator
periodnumberno60Period in seconds for all metrics
evaluationPeriodsnumberno1Number of periods to evaluate
datapointsToAlarmnumberno1Datapoints to trigger alarm
treatMissingDatastringnonotBreachingHow to treat missing data

Each entry in metrics has:

PropertyTypeRequiredDescription
idstringyesUnique ID referenced in the expression
metricstringyesCloudWatch metric name
statisticstringyesMetric statistic (Sum, Average, etc.)

Generated Resources

When you configure canaryAlarms, the plugin generates:

  1. Per-function canary alarms with the ExecutedVersion dimension
  2. A stack composite alarm that fires if ANY function's canary alarm fires

The composite alarm uses a predictable name: ${service}-${stage}-canary-composite

Using with Standard Alarms

You can use both alarms and canaryAlarms together:

functions:
  hello:
    deploymentSettings:
      type: Canary10Percent5Minutes
      alias: Live
      alarms:
        - name: my-existing-alarm
      canaryAlarms:
        - preset: errors                      # Version-specific alarm

How it works

The plugin relies on the AWS Lambda traffic shifting feature to balance traffic between versions and AWS CodeDeploy to automatically update its weight. It modifies the CloudFormation template generated by Serverless, so that:

  1. It creates a Lambda function Alias for each function with deployment settings.
  • For functions that already have a target alias due to provisioned concurrency or SnapStart configuration, the CodeDeploy-related settings are applied to it.
  1. It creates a CodeDeploy Application and adds a CodeDeploy DeploymentGroup per Lambda function, according to the specified settings.
  2. It modifies events that trigger Lambda functions, so that they invoke the newly created alias.

Limitations

For now, the plugin only works with Lambda functions invoked by

  • API Gateway
  • Stream based (such as the triggered by Kinesis, DynamoDB Streams or SQS)
  • SNS based events
  • S3 events
  • CloudWatch Scheduled events
  • CloudWatch Logs
  • IoT rules
  • AppSync DataSources
  • ElasticLoadBalancingV2 TargetGroups

More events will be added soon.

License

ISC © David García

版本与发布记录

@flagsmith/serverless-plugin-canary-deployments 共发布 6 个版本,首次发布于 2024/01/09;过去 12 个月发布了 4 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.0.1latest2026/09/291 个月前
2.0.02026/08/292 个月前
1.1.02026/05/086 个月前
1.0.02026/02/059 个月前
0.9.12024/10/102 年前
0.9.02024/01/092 年前

关于 @flagsmith/serverless-plugin-canary-deployments 的常见问题

@flagsmith/serverless-plugin-canary-deployments 是什么?

A Serverless plugin to implement canary deployment of Lambda functions

如何安装 @flagsmith/serverless-plugin-canary-deployments?

在项目目录运行 npm install @flagsmith/serverless-plugin-canary-deployments,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:serverless(>= 1.26.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@flagsmith/serverless-plugin-canary-deployments 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/flagsmith__serverless-plugin-canary-deployments 是否存在。

@flagsmith/serverless-plugin-canary-deployments 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@flagsmith/serverless-plugin-canary-deployments 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@flagsmith/serverless-plugin-canary-deployments 可以商用吗?

@flagsmith/serverless-plugin-canary-deployments 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@flagsmith/serverless-plugin-canary-deployments 的下载量有多少?

根据 npm 官方下载统计,@flagsmith/serverless-plugin-canary-deployments 在 2026/10/15 – 2026/11/13 这 30 天内被下载 2,250 次,日均约 75 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@flagsmith/serverless-plugin-canary-deployments 还在维护吗?

最新版本 2.0.1 发布于 2026/09/29(1 个月前);至今共发布 6 个版本,其中过去 12 个月发布了 4 个;首次发布于 2024/01/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。