首页 > 解决方案 > 用于创建资源的 AWS cloudformation 条件

问题描述

如何为 AWS 子资源类型使用条件

条件 - 创建规则为真 --- 创建规则 1 和规则 2

条件 - 创建规则为假 --- 创建规则 1 并应忽略创建规则 2 并退出


无论你的条件是什么,它都应该创建规则 1,该条件应该只适用于规则 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
                

            

标签: amazon-web-servicesif-statementconditional-statementsamazon-cloudformationaws-backup

解决方案


您应该能够通过使用这样的内在Fn:If条件函数来实现所需的结果:

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

推荐阅读