

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

# `PutConfigRule` 搭配 AWS SDK 或 CLI 使用
<a name="example_config-service_PutConfigRule_section"></a>

下列程式碼範例示範如何使用 `PutConfigRule`。

------
#### [ CLI ]

**AWS CLI**  
**新增 AWS 受管 Config 規則**  
下列命令提供 JSON 程式碼來新增 AWS 受管 Config 規則：  

```
aws configservice put-config-rule --config-rule file://RequiredTagsForEC2Instances.json
```
`RequiredTagsForEC2Instances.json` 是包含規則組態的 JSON 檔案：  

```
{
  "ConfigRuleName": "RequiredTagsForEC2Instances",
  "Description": "Checks whether the CostCenter and Owner tags are applied to EC2 instances.",
  "Scope": {
    "ComplianceResourceTypes": [
      "AWS::EC2::Instance"
    ]
  },
  "Source": {
    "Owner": "AWS",
    "SourceIdentifier": "REQUIRED_TAGS"
  },
  "InputParameters": "{\"tag1Key\":\"CostCenter\",\"tag2Key\":\"Owner\"}"
}
```
對於 `ComplianceResourceTypes` 屬性，此 JSON 程式碼會將範圍限制為 `AWS::EC2::Instance`類型的資源，因此 AWS Config 只會針對規則評估 EC2 執行個體。由於規則是受管規則，`Owner` 屬性會設為 `AWS`，而 `SourceIdentifier` 屬性則設為規則識別碼 `REQUIRED_TAGS`。針對 `InputParameters` 屬性，會指定規則需要的標籤索引鍵 `CostCenter` 和 `Owner`。  
如果命令成功， AWS Config 不會傳回任何輸出。若要驗證規則組態，請執行 describe-config-rules 命令，並指定規則名稱。  
**新增客戶管理的 Config 規則**  
下列命令提供 JSON 程式碼，以新增客戶管理的 Config 規則：  

```
aws configservice put-config-rule --config-rule file://InstanceTypesAreT2micro.json
```
`InstanceTypesAreT2micro.json` 是包含規則組態的 JSON 檔案：  

```
{
  "ConfigRuleName": "InstanceTypesAreT2micro",
  "Description": "Evaluates whether EC2 instances are the t2.micro type.",
  "Scope": {
    "ComplianceResourceTypes": [
      "AWS::EC2::Instance"
    ]
  },
  "Source": {
    "Owner": "CUSTOM_LAMBDA",
    "SourceIdentifier": "arn:aws:lambda:us-east-1:123456789012:function:InstanceTypeCheck",
    "SourceDetails": [
      {
        "EventSource": "aws.config",
        "MessageType": "ConfigurationItemChangeNotification"
      }
    ]
  },
  "InputParameters": "{\"desiredInstanceType\":\"t2.micro\"}"
}
```
對於 `ComplianceResourceTypes` 屬性，此 JSON 程式碼會將範圍限制為 `AWS::EC2::Instance`類型的資源，因此 AWS Config 只會針對規則評估 EC2 執行個體。由於此規則是客戶受管規則，`Owner`屬性設定為 `CUSTOM_LAMBDA`，而`SourceIdentifier`屬性設定為 AWS Lambda 函數的 ARN。`SourceDetails` 物件為必要項目。當 Config 調用屬性來根據規則評估資源時，為 `InputParameters` 屬性指定的參數會傳遞至 AWS Lambda AWS 函數。  
如果命令成功， AWS Config 不會傳回任何輸出。若要驗證規則組態，請執行 describe-config-rules 命令，並指定規則名稱。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [PutConfigRule](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configservice/put-config-rule.html)。

------
#### [ Python ]

**適用於 Python 的 SDK (Boto3)**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/config#code-examples)中設定和執行。

```
class ConfigWrapper:
    """
    Encapsulates AWS Config functions.
    """

    def __init__(self, config_client):
        """
        :param config_client: A Boto3 AWS Config client.
        """
        self.config_client = config_client


    def put_config_rule(self, rule_name):
        """
        Sets a configuration rule that prohibits making Amazon S3 buckets publicly
        readable.

        :param rule_name: The name to give the rule.
        """
        try:
            self.config_client.put_config_rule(
                ConfigRule={
                    "ConfigRuleName": rule_name,
                    "Description": "S3 Public Read Prohibited Bucket Rule",
                    "Scope": {
                        "ComplianceResourceTypes": [
                            "AWS::S3::Bucket",
                        ],
                    },
                    "Source": {
                        "Owner": "AWS",
                        "SourceIdentifier": "S3_BUCKET_PUBLIC_READ_PROHIBITED",
                    },
                    "InputParameters": "{}",
                    "ConfigRuleState": "ACTIVE",
                }
            )
            logger.info("Created configuration rule %s.", rule_name)
        except ClientError:
            logger.exception("Couldn't create configuration rule %s.", rule_name)
            raise
```
+  如需 API 詳細資訊，請參閱《*適用於 Python (Boto3) 的AWS 開發套件 API 參考*》中的 [PutConfigRule](https://docs.aws.amazon.com/goto/boto3/config-2014-11-12/PutConfigRule)。

------
#### [ SAP ABAP ]

**適用於 SAP ABAP 的開發套件**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/cfs#code-examples)中設定和執行。

```
    " Create a config rule for S3 bucket public read prohibition
    lo_cfs->putconfigrule(
      io_configrule = NEW /aws1/cl_cfsconfigrule(
        iv_configrulename = iv_rule_name
        iv_description = |S3 Public Read Prohibited Bucket Rule|
        io_scope = NEW /aws1/cl_cfsscope(
          it_complianceresourcetypes = VALUE /aws1/cl_cfscplncresrctypes_w=>tt_complianceresourcetypes(
            ( NEW /aws1/cl_cfscplncresrctypes_w( |AWS::S3::Bucket| ) )
          )
        )
        io_source = NEW /aws1/cl_cfssource(
          iv_owner = |AWS|
          iv_sourceidentifier = |S3_BUCKET_PUBLIC_READ_PROHIBITED|
        )
        iv_inputparameters = '{}'
        iv_configrulestate = |ACTIVE|
      )
    ).
    MESSAGE 'Created AWS Config rule.' TYPE 'I'.
```
+  如需 API 詳細資訊，請參閱《適用於 *AWS SAP ABAP 的 SDK API 參考*》中的 [PutConfigRule](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)。

------

如需 AWS SDK 開發人員指南和程式碼範例的完整清單，請參閱 [AWS Config搭配AWS SDK 使用](sdk-general-information-section.md)。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。