Home > front end >  AWS cloudformation condition for creating a resource
AWS cloudformation condition for creating a resource

Time:10-27

How to use a condition for AWS Child resource type

  • I wanted to create an AWS backupplan with 2 backup rules with a condition (example, if I set create2backup rule as "true", it should create the second one, if the condition is false, it should ignore creating the second rule. I couldn't use the condition there, it thrown error.
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
            

CodePudding user response:

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

CodePudding user response:

Conditions is a top level section and can't be used inside Properties section. It is used to decide whether a resource will be created or not. You could have two different resources and create one of them based on the condition. This of course creates some duplication.

  • Related