CloudFormation Conditions

Does serverless have a way to use CloudFormation Conditions so that I use command line parameters or environment variables to conditionally create resources such as dynamodb tables?

I could imagine a solution using Serverless Variables to do this (but have not actually done it myself).

With this command:

sls deploy --stage prod

And this serverless.yml:

...
resources:  
  Conditions:
    CreateTable:
      Fn::Equals:
        - ${opt:stage}
        - dev
  Resources:
    DynamoDbTable:
      Type: AWS::DynamoDB::Table
      Condition: CreateTable
      Properties:
        TableName: my-table
        ...

In this contrived example, the DDB table would not get created, because ${opt:stage} is “prod”. As mentioned in the docs you can use environment variables in Serverless as well.

2 Likes

Thanks. That worked great by any chance do you know how to get the streamarn of an existing dynamodb table? If I create the table it is easy but I cannot figure out how to get it if the table and stream are already created. Here is the resource section from my serverless.yml file with the table and trigger. I want to get rid of the hardcoded text arn.

resources:
  Conditions:
    CreateResources: 
      Fn::Equals:
        - ${opt:create}
        - true
  Resources:
    LocationTable:
      Type: 'AWS::DynamoDB::Table'
      Condition: CreateResources
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: id
            AttributeType: S
        KeySchema:
          -
            AttributeName: id
            KeyType: HASH
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        StreamSpecification:
          StreamViewType: NEW_AND_OLD_IMAGES
        TableName: 'tablename'
    LocationStreamTrigger:
      Type: AWS::Lambda::EventSourceMapping
      # DependsOn: LocationTable
      Properties:
        BatchSize: 10
        EventSourceArn:
          Fn::If:
            - CreateResources
            - Fn::GetAtt:
              - LocationTable
              - StreamArn
            - 'arn:aws:dynamodb:us-east-1:9999999999999:table/tablename/stream/2016-09-20T21:37:18.880'
        FunctionName:
          Fn::GetAtt:
            - "SearchLambdaFunction"
            - "Arn"
        StartingPosition: "TRIM_HORIZON"
1 Like

I’m not familiar with DDB Streams - you might be able to get it using Fn::GetAtt?

Search for StreamArn on this page and refer to your table by its logical ID.

Let me know if that works/doesn’t work.

Facing a similar issue. I think it is not supported?

https://github.com/serverless/serverless/issues/2365