You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Serverless Framework中声明条件资源?(serverless.ts配置)

在Serverless.ts中通过CloudFormation条件实现资源的条件式部署

核心思路

借助Serverless框架的resources字段集成CloudFormation的条件逻辑,结合阶段标识或环境变量判断当前运行模式,以此控制资源是否被创建。

具体实现步骤

1. 定义CloudFormation条件

在resources下添加Conditions字段,判断当前是否为离线模式。可以通过部署阶段或IS_OFFLINE环境变量来识别:

import type { AWS } from '@serverless/typescript';

const serverlessConfiguration: AWS = {
  service: 'your-service-name',
  frameworkVersion: '3',
  // ...其他基础配置(如provider、functions等)
  resources: {
    Conditions: {
      // 方式一:通过部署阶段判断
      IsNotOffline: {
        'Fn::Not': [
          {
            'Fn::Equals': [
              { Ref: 'AWS::Stage' },
              'offline'
            ]
          }
        ]
      }
      // 方式二:通过环境变量判断(Serverless Offline会自动设置IS_OFFLINE=true)
      // IsNotOffline: {
      //   'Fn::Not': [
      //     { 'Fn::Equals': [{ Ref: 'IS_OFFLINE' }, 'true'] }
      //   ]
      // }
    },
    Resources: {
      // 给需要条件部署的资源绑定Condition
      UserPool: {
        Type: 'AWS::Cognito::UserPool',
        Condition: 'IsNotOffline',
        Properties: {
          UserPoolName: '${self:service}-user-pool-${sls:stage}',
          // ...其他Cognito用户池配置项
        }
      },
      UserPoolClient: {
        Type: 'AWS::Cognito::UserPoolClient',
        Condition: 'IsNotOffline',
        Properties: {
          UserPoolId: { Ref: 'UserPool' },
          ClientName: '${self:service}-client-${sls:stage}',
          // ...其他客户端配置项
        }
      }
    }
  }
};

module.exports = serverlessConfiguration;

2. 触发离线模式的正确姿势

  • 用阶段判断时:启动离线需指定阶段,命令为serverless offline --stage offline
  • 用环境变量判断时:直接运行serverless offline即可,插件会自动注入IS_OFFLINE=true环境变量

3. 验证效果

  • 执行serverless deploy --stage production时,IsNotOffline条件为true,Cognito资源会正常创建
  • 执行离线命令时,条件为false,Cognito资源会被排除在部署之外

额外注意事项

  • 所有依赖该条件资源的关联资源(比如API Gateway的Cognito授权器),也需要添加相同的Condition,避免部署报错
  • 确保Serverless Offline插件版本兼容,避免环境变量传递异常

内容的提问来源于stack exchange,提问作者suman j

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 11:06:20