Search code examples
yamlserverless-frameworkserverless

How to add item to YML collection conditionally using Serverless framework?


Given I have the following defined in a YML file for a resource:

Type: AWS::Cognito::UserPoolClient
  CallbackURLs:
    - "my-first-url"

How can I add a second item when only certain conditions are met? Unfortuantely it is not possible to simply set it to an empty string or null as it fails deployment validation. E.G something like:

Type: AWS::Cognito::UserPoolClient
  CallbackURLs:
    - "my-first-url"
    - myCondition ? "" : undefined // Omit item 

Is this possible in any way at all? Happy to use Plugin solutions etc.


Solution

  • You can use a CloudFormation condition like Fn::If to conditionally create stack resources. The CloudFormation documentation about conditions has all the details but somehting like this should get you started:

    resources:
      Conditions:
        my_condition: !Equals [value_1, value_2]
      Resources:
        MyUserPool:
          Type: AWS::Cognito::UserPoolClient
            CallbackURLs:
              - "my-first-url"
              - !If [my_condition, "...", !Ref "AWS::NoValue"]
    

    Replace the content of my_condition with your condition. It is referenced later in the Fn::If (the example uses the shorthand for Fn::If).

    The AWS::NoValue is a pseudo parameter which can be used as a return value to remove the corresponding property. It should work here to remove the list item but I'm not sure about it, you'll need to test.