As your serverless application evolves, you’ll often need to toggle resources, features, or settings based on the environment (e.g., dev, staging, production).

With AWS SAM, you can do this using CloudFormation-style conditionals, allowing you to dynamically include or exclude resources at deploy time.

In this post, we’ll cover:

  • Defining parameters and conditions
  • Using Conditions in your SAM template
  • Real-world examples like enabling the Powertools logger only in production

🧱 Step 1: Define Parameters

Start by adding environment-based parameters in your template.yml:

Parameters:
  Environment:
    Type: String
    Default: dev
    AllowedValues:
      - dev
      - staging
      - prod

⚙️ Step 2: Define Conditions

Now use those parameters to define conditional logic:

Conditions:
  IsProd: !Equals [ !Ref Environment, prod ]
  IsLowEnv: !Or 
    - !Equals [ !Ref Environment, dev ]
    - !Equals [ !Ref Environment, qa ]

You can now use these conditions to control resources, properties, or behaviors in your SAM app.

🔧 Step 3: Use Conditions in Resources

Here’s an example of conditionally including a Powertools Logger layer only in production:

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs22.x
      Environment:
        Variables:
          ENV: !Ref Environment
      Layers:
        - !If
          - IsProd
          - arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:24
          - !Ref "AWS::NoValue"

💡 AWS::NoValue tells CloudFormation to omit the property entirely when the condition is false.

✅ Optional: Enable/Disable Features

You can also toggle entire resources or outputs:

Resources:
  TestFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs22.x
    Condition: IsLowEnv

Conclusion

With AWS SAM Conditionals, you can:

  • Make templates more reusable across environments
  • Toggle resources, settings, and layers cleanly
  • Keep infrastructure lean and purposeful

Whether you're turning on debug logs in dev or enabling global tracing in prod, conditionals help you build smart, environment-aware serverless apps.