How to use conditions for properties in Cloudformation

Viewed 114

I am trying to create a lambda function, version and alias using CloudFormation template and it is working as expected. But In my case I want to configure the RoutingConfig based on some input parameters.

Example : If endures provided the TrafficShitVersion as a inputparam, then only I want to add RoutingConfig to the alias.

Can any one help me how to achieve this use case

--- 
Description: "Lambda Example"
Parameters:
 TrafficShitVersion :
    Default: 0
    Type: String
    Description: TrafficShitVersion 
    
Conditions:
  CreateRouting: !Not 
    - !Equals 
      - !Ref TrafficShitVersion 
      - 0
Resources: 
  MyLambdaFunction: 
    Properties: 
      Code: 
        ZipFile: |
            exports.handler = function(event){
                console.log(JSON.stringify(event, null, 4))
                const response = {
                    statusCode: 200,
                    body: JSON.stringify('Hello from LambdaV5!')
                }
                return response
            };
      FunctionName: bhanuFunction
      Handler: index.handler
      Role: "RoleARN"
      Runtime: nodejs12.x
      Tags: 
        - 
          Key: "lambda:createdBy"
          Value: SAM
    Type: "AWS::Lambda::Function"
  myfunctionVersion3: 
    DeletionPolicy: Retain
    Properties: 
      FunctionName: 
        Ref: MyLambdaFunction
    Type: "AWS::Lambda::Version"
  myfunctionVersionAlias: 
    Properties: 
      FunctionName: 
        Ref: MyLambdaFunction
      FunctionVersion: 
       Fn::GetAtt : 
          - myfunctionVersion3
          - Version
      Name: MyTestAliash
      //Need to add the condition only if TrafficShitVersion is provided then only add ***RoutingConfig***
      RoutingConfig:
        AdditionalVersionWeights:
          - FunctionVersion: !Ref TrafficShitVersion 
            FunctionWeight: 0.5
    Type: "AWS::Lambda::Alias"
1 Answers

As per AWS docs, we can use Fn::If and AWS::NoValue to set properties accordingly.

The template will look like:

MyLambdaFunctionAlias: 

Properties: 
  FunctionName: 
    Ref: MyLambdaFunction
  FunctionVersion: 
   Fn::GetAtt : 
      - MyFunctionVersion3
      - Version
  Name: MyTestAlias
  RoutingConfig:
   !If
   - "CreateRouting"
   -
     AdditionalVersionWeights:
       - FunctionVersion: !Ref TrafficShitVersion 
         FunctionWeight: 0
   - !Ref "AWS::NoValue"
Type: "AWS::Lambda::Alias"
Related