Use of !If intrinsic function in a SAM template

Viewed 22

I thought you could do something like this for a state machine using SAM:

SM:
    Type: AWS::Serverless::StateMachine
    Properties:
      Name: !Sub "${StageName}-State-Machine"
      DefinitionUri: statemachine/dddd.asl.json
      Events:
        Schedule:
          !If
            - IsPrimaryRegion
            -
              Type: Schedule
              Properties:
                Description: Schedule to run the twilio number state machine
                Enabled: !Ref ScheduleEnabled
                Schedule: "rate(1 hour)"
            - 
              Type: Schedule
              Properties:
                Description: Schedule to run the twilio number state machine
                Enabled: !Ref ScheduleEnabled
                Schedule: "rate(1 hour)"

But SAM validation fails for this. It also fails if I use State instead of Enabled in properties. Ultimately I want to have a way to set Enabled dynamically, using a parameter or any other way. But validation with State fails.

Also tried this:

Enabled: !If [IsPrimaryRegion, true, false]
1 Answers

You need to define Conditions block, then you can use these conditions in your template like below:

Parameters:
  PrimaryRegion:
    Type: String
    Description: Primary region

Conditions:
  IsPrimaryRegion: !Equals [ !Ref PrimaryRegion, !Ref "AWS::Region" ]

Resources:
  SM:
    Type: AWS::Serverless::StateMachine
      Properties:
        Name: !Sub "${StageName}-State-Machine"
        DefinitionUri: statemachine/dddd.asl.json
        Events:
          Schedule:
            Type: Schedule
            Properties:
              Description: Schedule to run the twilio number state machine
              Enabled: !If [ IsPrimaryRegion, true, false ]
              Schedule: "rate(1 hour)"

Eventually:

Parameters:
  PrimaryRegion:
    Type: String
    Description: Primary region

Conditions:
  IsPrimaryRegion: !Equals [ !Ref PrimaryRegion, !Ref "AWS::Region" ]
  IsNotPrimaryRegion: !Not [ !Equals [ !Ref PrimaryRegion, !Ref "AWS::Region" ] ]

Resources:
  SMPrimary:
    Type: AWS::Serverless::StateMachine
      Condition: IsPrimaryRegion
      Properties:
        Name: !Sub "${StageName}-State-Machine"
        ...
              Enabled: true
  SM:
    Type: AWS::Serverless::StateMachine
      Condition: IsNotPrimaryRegion
      Properties:
        Name: !Sub "${StageName}-State-Machine"
        ...
              Enabled: false
Related