

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

# 建立 AWS Config 自訂政策規則
<a name="evaluate-config_develop-rules_cfn-guard"></a>

您可以從 AWS 管理主控台 AWS CLI或 AWS Config API 建立 AWS Config 自訂政策規則。

## 新增 AWS Config 自訂政策規則
<a name="config-custom-policy-rules-add"></a>

------
#### [ Using the console ]

1. 登入 AWS 管理主控台 並在 https：//[https://console.aws.amazon.com/config/home](https://console.aws.amazon.com/config/home) 開啟 AWS Config 主控台。

1. 在 AWS 管理主控台 選單中，確認區域選擇器已設定為支援 AWS Config 規則的區域 AWS 。如需支援區域的清單，請參閱《*Amazon Web Services 一般參考*》中的 [AWS Config 區域與端點](https://docs.aws.amazon.com/general/latest/gr/awsconfig.html)。

1. 在左側導覽中，選擇 **規則**。

1. 在 **Rules (規則)** 頁面，選擇 **Add rule (新增規則)**。

1. 在 **指定規則類型** 頁面上，請選擇 **使用 Guard 建立自訂規則**。

1. 在 **設定規則** 頁面上，請完成下列步驟以建立規則：

   1. 針對 **規則名稱**，請鍵入規則的唯一名稱。

   1. 針對 **描述**，請鍵入規則的描述。

   1. 針對 **Guard 執行時間版本**，選擇 AWS Config 自訂政策規則的執行時間系統。

   1. 針對 **規則內容**，您可以為規則填入 Guard 自訂政策。

   1. 在**評估模式中**，選擇您要在資源建立和管理程序中 AWS Config 評估資源的時間。根據規則， AWS Config 可以在佈建資源之前、在提供資源之後，或同時評估您的資源組態。

      1. 選擇 **開啟主動評估**，可讓您在部署資源之前，對資源的組態設定執行評估。

         開啟主動評估後，您可以使用 [StartResourceEvaluation](https://docs.aws.amazon.com/config/latest/APIReference/API_StartResourceEvaluation.html) API 和 [GetResourceEvaluationSummary](https://docs.aws.amazon.com/config/latest/APIReference/API_GetResourceEvaluationSummary.html) API 來檢查您在這些命令中指定的資源是否會被您區域中帳戶中的主動規則標記為「NON\$1COMPLIANT」。

          如需使用此命令的詳細資訊，請參閱[使用 AWS Config 規則評估您的 資源](https://docs.aws.amazon.com/config/latest/developerguide/evaluating-your-resources.html#evaluating-your-resources-proactive)。如需支援主動評估的受管規則清單，請參閱[依評估模式的 AWS Config 受管規則清單](https://docs.aws.amazon.com/config/latest/developerguide/managed-rules-by-evaluation-mode.html)。

      1. 選擇 **開啟偵測評估** 以評估現有資源的組態設定。

         對於偵測性評估， AWS Config 自訂政策規則由**組態變更**啟動。此選項將被預先選擇。
         +  **資源** – 建立、變更或刪除符合指定資源類型或加上識別符類型的資源時。
         +  **標籤** – 建立、變更或刪除含指定標籤的資源時。
         +  **所有變更** – AWS Config 建立、變更或刪除 記錄的資源時。

         AWS Config 會在偵測到符合規則範圍的資源變更時執行評估。您可以使用範圍來限制要進行評估的資源。否則，當佈建後的資源發生變更時，會啟動評估。

   1. 針對 **參數**，如果您的規則包含參數，則您可以自訂所提供金鑰的值。您的資源必須依循參數這項屬性，才會被視為符合規則。

1. 在**檢閱和建立**頁面上，檢閱所有選取項目，再將規則新增至您的 AWS 帳戶。

1. 檢閱完規則後，請選擇 **新增規則**。

------
#### [ Using the AWS CLI ]

使用 [https://docs.aws.amazon.com/cli/latest/reference/configservice/put-config-rule.html](https://docs.aws.amazon.com/cli/latest/reference/configservice/put-config-rule.html) 命令。

該 `Owner` 欄位應為 `CUSTOM_POLICY`。 AWS Config 自訂政策規則需要下列其他欄位：
+ `Runtime`： AWS Config 自訂政策規則的執行時間系統。
+ `PolicyText`：包含 AWS Config 自訂政策規則邏輯的政策定義。
+ `EnableDebugLogDelivery`：為 AWS Config 自訂政策規則啟用偵錯記錄的布林表達式。預設值為 `false`。

------
#### [ Using the API Reference ]

使用 [PutConfigRule](https://docs.aws.amazon.com/config/latest/APIReference/API_PutConfigRule.html) 動作。

該 `Owner` 欄位應為 `CUSTOM_POLICY`。 AWS Config 自訂政策規則需要下列其他欄位：
+ `Runtime`： AWS Config 自訂政策規則的執行時間系統。
+ `PolicyText`：包含 AWS Config 自訂政策規則邏輯的政策定義。
+ `EnableDebugLogDelivery`：為 AWS Config 自訂政策規則啟用偵錯記錄的布林表達式。預設值為 `false`。

------

## 撰寫 AWS Config 自訂政策規則的規則內容
<a name="config-custom-policy-rules"></a>

透過 AWS Config 自訂政策規則，您可以使用 AWS CloudFormation Guard 的網域特定語言 (DSL) 來評估資源組態。本主題提供撰寫自訂政策規則的模式和最佳實務。

如需如何使用 Guard 撰寫規則的詳細資訊，請參閱 [Guard 使用者指南中的撰寫](https://docs.aws.amazon.com/cfn-guard/latest/ug/writing-rules.html) AWS CloudFormation Guard 規則和 [AWS CloudFormation Guard GitHub 儲存庫中的 Guard 2.0 的操作模式](https://github.com/aws-cloudformation/cloudformation-guard/tree/main/guard)。 GitHub 

### 基本規則結構
<a name="config-custom-policy-rules-structure"></a>

使用下列基本格式來建立規則：

```
# Basic rule format
rule <rule_name> when
    resourceType == "<AWS::Service::Resource>" {
    # Evaluation clauses
}

# Example with filtering
let resources_of_type = Resources.*[ Type == 'AWS::Service::Resource' ]
rule check_resources when %resources_of_type !empty {
    %resources_of_type.configuration.property == expected_value
}
```

### 關鍵元件
<a name="config-custom-policy-rules-components"></a>

組態  
包含資源組態的內容。

supplementaryConfiguration  
包含資源組態的其他內容。 會 AWS Config 傳回特定資源類型的此欄位，以補充組態欄位傳回的資訊。

resourceType  
AWS 正在評估的資源類型。

resourceId  
資源的 ID （例如，`sg-xxxxxx`)。

accountId  
與資源相關聯的 12 位數 AWS 帳戶 ID。

### 常見模式
<a name="config-custom-policy-rules-patterns"></a>

------
#### [ Status checks ]

```
let allowed_status = ['ACTIVE', 'RUNNING']
rule check_resource_status when
    resourceType == "AWS::Service::Resource" {
    configuration.status IN %allowed_status
}
```

------
#### [ Required properties ]

```
rule check_required_properties when
    resourceType == "AWS::Service::Resource" {
    configuration.propertyName exists
    configuration.propertyName is_string  # or is_list, is_struct
}
```

------
#### [ Query blocks ]

```
configuration.Properties {
    property1 exists
    property2 is_string
    property3 IN [allowed_value1, allowed_value2]
}
```

------
#### [ Conditional evaluation ]

```
when configuration.feature_enabled == true {
    configuration.feature_settings exists
    configuration.feature_settings is_struct
}
```

------
#### [ Custom messages ]

```
rule check_compliance when
    resourceType == "AWS::Service::Resource" {
    configuration.property == expected_value <<Custom error message explaining the requirement>>
}}
```

------

### 進階功能
<a name="config-custom-policy-rules-advanced"></a>

------
#### [ Range checks ]

```
rule check_numeric_limits {
    # Inclusive range (lower_limit <= value <= upper_limit)
    configuration.value IN r[minimum_value, maximum_value]  

    # Exclusive range (lower_limit < value < upper_limit)
    configuration.value IN r(exclusive_min, exclusive_max)  

    # Left inclusive, right exclusive (lower_limit <= value < upper_limit)
    configuration.value IN r[minimum_value, exclusive_max)

    # Left exclusive, right inclusive (lower_limit < value <= upper_limit)
    configuration.value IN r(exclusive_min, maximum_value]
}
```

------
#### [ Combining conditions ]

```
# AND conditions (implicit through new lines)
condition_1
condition_2

# OR conditions (explicit)
condition_3 OR
condition_4
```

------
#### [ Chaining rules ]

```
rule check_prerequisites {
    configuration.required_setting exists
}

rule check_details when check_prerequisites {
    configuration.required_setting == expected_value
}
```

------

### 最佳實務
<a name="config-custom-policy-rules-best-practices"></a>
+ 使用變數搭配 `let`陳述式以提高可讀性。
+ 使用具名規則區塊對相關檢查進行分組。
+ 包含描述性註解。
+ 使用適當的運算子 (`exists`、`is_string`、`is_list`)。
+ 使用不區分大小寫比對的 regex 模式。

### 範例：dynamodb-pitr-enabled
<a name="config-custom-policy-rules-example"></a>

下列範例顯示 AWS Config 受管規則 的 AWS Config 自訂政策規則版本的政策定義[dynamodb-pitr-enabled](dynamodb-pitr-enabled.md)。此規則會檢查 DynamoDB 資料表是否已啟用Point-in-Time復原。

```
# Check if DynamoDB tables have Point-in-Time Recovery enabled
let status = ['ACTIVE']

rule tableisactive when
    resourceType == "AWS::DynamoDB::Table" {
    configuration.tableStatus == %status
}

rule checkcompliance when
    resourceType == "AWS::DynamoDB::Table"
    tableisactive {
    let pitr = supplementaryConfiguration.ContinuousBackupsDescription.pointInTimeRecoveryDescription.pointInTimeRecoveryStatus
    %pitr == "ENABLED" <<DynamoDB tables must have Point-in-Time Recovery enabled>>
}
```