6

I'm having an AWS SAM template file with some resources hosted on github, a codepipeline has been setted up to detect changes in the repo then create/update and execute changes on cloudformation stack. Everything is working fine. But now I need to configure stage and prod environments in the same template. I'm finding it difficult how to do it properly.

Different approaches are welcomed as well.

kzrfaisal
  • 1,355
  • 5
  • 15
  • 26
  • 1
    Defining these in the same template doesn't seem like good practice - is there a reason why you feel the need to do this? (You'd usually add [parameters](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html) for the stage specific values and the deploy a stack per stage. – Maurice Mar 27 '20 at 16:05
  • I don't want to create different accounts for each environment and I want to use the same resources for production environment after proper testing in dev/stage environment. However apart from this what's your suggestion for best practice (except different accounts approach) – kzrfaisal Mar 27 '20 at 16:32

2 Answers2

4

Are PROD and STAGE in the same account, or different accounts? I will assume same

Transform: AWS::Serverless-2016-10-31

Parameters:
  Environment:
    Type: String
    AllowedValues:
      - STAGE
      - PROD

Resources:
  MyLambda:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lambda_function.lambda_handler
      FunctionName: !Sub ${Environment}_my_lambda
      CodeUri: my_lambda

This would give a unique name to your lambda, by environment

Then when you deploy your template, use --parameter-overrides=Environment=STAGE or --parameter-overrides=Environment=PROD

You can setup CloudWatch to listen to CodeCommit. If STAGE branch changes, call CodeBuild to use the STAGE branch, and call CloudFormation w the STAGE param. Same for PROD

Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152
  • I don't think this does what you think it does. When you publish with STAGE, it would point your API Gateway URL (the 'Prod' stage url) to the `STAGE_my_lambda` function. Then deploying with PROD would point it back to the `PROD_my_lambda` function and destroy the `STAGE_my_lambda` function. They would not exist side by side and you would not truly be staging while prod continues to run. – Ben Zuill-Smith Oct 28 '22 at 23:04
1

Parameters would be best

You could also use Mappings or Conditions. But either of those could get messy

Tim Bassett
  • 1,325
  • 1
  • 12
  • 23