根據 AWS CloudFormation Guard 規則驗證輸入資料 - AWS CloudFormation Guard

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

根據 AWS CloudFormation Guard 規則驗證輸入資料

您可以使用 AWS CloudFormation Guard validate命令來驗證 Guard 規則的資料。如需 validate命令的詳細資訊,包括其參數和選項,請參閱驗證

先決條件

  • 寫入 Guard 規則以驗證您的輸入資料。如需詳細資訊,請參閱撰寫 Guard 規則

  • 測試您的規則,以確保它們如預期般運作。如需詳細資訊,請參閱測試 Guard 規則

使用 validate命令

若要根據 Guard 規則驗證輸入資料,例如 AWS CloudFormation 範本,請執行 Guard validate命令。針對 --rules 參數,指定規則檔案的名稱。針對 --data 參數,指定輸入資料檔案的名稱。

cfn-guard validate --rules rules.guard --data template.json

如果 Guard 成功驗證範本,validate命令會傳回結束狀態為 0($?在 bash 中為 )。如果 Guard 識別規則違規,validate命令會傳回失敗規則的狀態報告。使用摘要旗標 (-s all) 來查看詳細評估樹狀結構,其中顯示 Guard 如何評估每個規則。

template.json Status = FAIL SKIP rules rules.guard/aws_apigateway_deployment_checks SKIP rules.guard/aws_apigateway_stage_checks SKIP rules.guard/aws_dynamodb_table_checks SKIP PASS rules rules.guard/aws_events_rule_checks PASS rules.guard/aws_iam_role_checks PASS FAILED rules rules.guard/aws_ec2_volume_checks FAIL rules.guard/mixed_types_checks FAIL --- Evaluation of rules rules.guard against data template.json -- Property [/Resources/vol2/Properties/Encrypted] in data [template.json] is not compliant with [rules.guard/aws_ec2_volume_checks] because provided value [false] did not match expected value [true]. Error Message [] Property traversed until [/Resources/vol2/Properties] in data [template.json] is not compliant with [rules.guard/aws_ec2_volume_checks] due to retrieval error. Error Message [Attempting to retrieve array index or key from map at path = /Resources/vol2/Properties , Type was not an array/object map, Remaining Query = Size] Property [/Resources/vol2/Properties/Encrypted] in data [template.json] is not compliant with [rules.guard/mixed_types_checks] because provided value [false] did not match expected value [true]. Error Message [] -- Rule [rules.guard/aws_iam_role_checks] is compliant for data [template.json] Rule [rules.guard/aws_events_rule_checks] is compliant for data [template.json] -- Rule [rules.guard/aws_apigateway_deployment_checks] is not applicable for data [template.json] Rule [rules.guard/aws_apigateway_stage_checks] is not applicable for data [template.json] Rule [rules.guard/aws_dynamodb_table_checks] is not applicable for data [template.json]

針對多個資料檔案驗證多個規則

為了協助維護規則,您可以將規則寫入多個檔案,並根據需要組織規則。然後,您可以針對資料檔案或多個資料檔案驗證多個規則檔案。validate 命令可以取得 --data--rules選項的檔案目錄。例如,您可以執行下列命令,其中 /path/to/dataDirectory包含一或多個資料檔案,以及/path/to/ruleDirectory包含一或多個規則檔案。

cfn-guard validate --data /path/to/dataDirectory --rules /path/to/ruleDirectory

您可以撰寫規則來檢查多個 CloudFormation 範本中定義的各種資源是否具有適當的屬性指派,以確保靜態加密。為了方便搜尋和維護,您可以在具有路徑 的目錄中,使用稱為 s3_bucket_encryption.guardec2_volume_encryption.guard和 的個別檔案中,在每個資源rds_dbinstance_encrytion.guard中檢查靜態加密的規則~/GuardRules/encryption_at_rest。您需要驗證的 CloudFormation 範本位於路徑為 的目錄中~/CloudFormation/templates。在此情況下,請執行 validate命令,如下所示。

cfn-guard validate --data ~/CloudFormation/templates --rules ~/GuardRules/encryption_at_rest