user9488542
user9488542

Reputation: 35

AWS cloudformation condition for creating a resource

How to use a condition for AWS Child resource type

Condition - create rule is true --- Creates Rule 1 and Rule 2

Condition - create rule is false --- Creates Rule1 and should ignore creating rule 2 and exit


whatever thee condition is it should create the Rule 1, the condition should only apply to Rule 2.

Try1 :
BackupPlan:
    Type: AWS::Backup::BackupPlan
    Properties:
      BackupPlan: 
        BackupPlanName: backupplan
        BackupPlanRule:
          -  
            RuleName: !Ref RuleName   
          - <Some condition>
            RuleName: !Ref RuleName2



Try2:
StorageBackupPlan:
    Type: AWS::Backup::BackupPlan
   # DependsOn: StorageBackupVault
    Properties:
      BackupPlan: 
        BackupPlanName: !Ref BackupPlanName
        BackupPlanRule:
          !If
            - Createbackuprule2
            - 
              RuleName: !Ref RuleName
              
            - 
              RuleName: !Ref RuleName2
              

Error for try 2 - Properties validation failed for resource StorageBackupPlan with message: #/BackupPlan/BackupPlanRule: expected type: JSONArray, found: JSONObject

Try 3 : worked but not as I expected, if condition is true it creates rule 1 if the condition is false it creates rule 2 - got this from below answer

StorageBackupPlan:
    Type: AWS::Backup::BackupPlan
   # DependsOn: StorageBackupVault
    Properties:
      BackupPlan: 
        BackupPlanName: !Ref BackupPlanName
        BackupPlanRule:
          !If
            - Createbackuprule2 
            -
              - RuleName: !Ref RuleName1
            -
              - RuleName: !Ref RuleName2
                

            

Upvotes: 0

Views: 1520

Answers (1)

Dunedan
Dunedan

Reputation: 8435

You should be able to achieve the desired result by using the intrinsic Fn:If condition function like that:

Parameters:
  CreateNewRole:
    Type: String
    AllowedValues:
      - yes
      - no
  RuleName:
    Type: String
  RuleName2:
    Type: String

Conditions:
  CreateNewRoleCondition:
    !Equals
      - !Ref CreateNewRole
      - yes

Resources:
  MyBackupPlan:
    Type: AWS::Backup::BackupPlan
    Properties:
      BackupPlan:
        BackupPlanName: backupplan
        BackupPlanRule:
          !If
            - CreateNewRoleCondition
            -
              - RuleName: !Ref RuleName
              - RuleName: !Ref RuleName2
            -
              - RuleName: !Ref RuleName

Upvotes: 1

Related Questions