如何在Serverless Framework中根据stage动态设置环境变量baseUrl
实现按stage动态匹配baseUrl的修改方案
第一步:新增baseUrl的阶段映射配置
在你现有serverless.yml的custom块下添加不同stage对应的baseUrl取值映射:
custom: profiles: dev: default prod: mad # 新增以下配置 baseUrls: dev: https://example.com prod: https://example2.com
第二步:配置环境变量
如果需要所有Lambda函数都能拿到该环境变量,直接在provider块下添加environment配置即可:
provider: name: aws profile: ${self:custom.profiles.${sls:stage}} runtime: nodejs12.x lambdaHashingVersion: 20201221 region: ap-southeast-1 # 新增全局环境变量配置 environment: baseUrl: ${self:custom.baseUrls.${sls:stage}}
如果只需要给指定函数配置,就把上述environment配置加到对应函数的配置块下即可,比如仅给operations函数新增该变量:
functions: operations: handler: serverless.handler environment: STAGE_NAME: ${opt:stage, 'dev'} # 新增baseUrl配置 baseUrl: ${self:custom.baseUrls.${sls:stage}}
完整修改后的serverless.yml示例
custom: profiles: dev: default prod: mad baseUrls: dev: https://example.com prod: https://example2.com provider: name: aws profile: ${self:custom.profiles.${sls:stage}} runtime: nodejs12.x lambdaHashingVersion: 20201221 region: ap-southeast-1 environment: baseUrl: ${self:custom.baseUrls.${sls:stage}} iam: role: statements: - Effect: Allow Action: - dynamodb:DescribeTable - dynamodb:Query - dynamodb:Scan - dynamodb:GetItem - dynamodb:PutItem - dynamodb:UpdateItem - dynamodb:DeleteItem Resource: arn:aws:dynamodb:ap-southeast-1:: resources: Resources: trimifyUrlsTable: Type: 'AWS::DynamoDB::Table' Properties: AttributeDefinitions: - AttributeName: pk AttributeType: S - AttributeName: originalUrl AttributeType: S KeySchema: - AttributeName: pk KeyType: HASH - AttributeName: originalUrl KeyType: RANGE ProvisionedThroughput: ReadCapacityUnits: 1 WriteCapacityUnits: 1 TableName: 'mad_dove_urls' functions: customAuthorizer: handler: authorizer/authorizer.auth environment: ACCOUNT_ID: ${aws:accountId} API_ENDPOINT: Ref: ApiGatewayRestApi STAGE_NAME: ${opt:stage, 'dev'} operations: handler: serverless.handler environment: STAGE_NAME: ${opt:stage, 'dev'} events: - http: path: / method: ANY cors: true - http: path: /{proxy+} method: ANY cors: true - http: path: /auth-ops method: ANY authorizer: customAuthorizer cors: true - http: path: /auth-ops/{proxy+} method: ANY authorizer: customAuthorizer cors: true
验证规则
- 执行
sls deploy --stage dev部署时,baseUrl取值为https://example.com - 执行
sls deploy --stage prod部署时,baseUrl取值为https://example2.com
内容的提问来源于stack exchange,提问作者Jatin Mehrotra
相关产品推荐
相关产品推荐

