

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

# 使用 AWS CloudFormation 範本有條件地啟用 Amazon GuardDuty
<a name="enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates"></a>

*Ram Kandaswamy，Amazon Web Services*

## 總結
<a name="enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates-summary"></a>

[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)是基礎設施即程式碼 (IaC) 工具，可協助您透過以範本為基礎的部署來管理 AWS 資源。CloudFormation 通常用於管理 AWS 資源。使用它來啟用 AWS 服務，例如 [Amazon GuardDuty](https://docs.aws.amazon.com/guardduty/latest/ug/what-is-guardduty.html)，可能會帶來獨特的挑戰。GuardDuty 是一種威脅偵測服務，可持續監控您的 AWS 帳戶 是否有惡意活動和未經授權的行為。與可多次建立的典型資源不同，GuardDuty 是一種服務，每個帳戶和 都需要啟用一次 AWS 區域。傳統 CloudFormation 條件僅支援靜態值比較，因此很難檢查 GuardDuty 等服務的目前狀態。如果您嘗試在已啟用的帳戶中透過 CloudFormation 啟用 GuardDuty，堆疊部署會失敗。這可能會為管理多帳戶環境的 DevOps 團隊帶來營運挑戰。

此模式引入了此挑戰的解決方案。它使用由 [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)函數支援的 CloudFormation 自訂資源來執行動態狀態檢查。條件式邏輯只會在尚未啟用的情況下啟用 GuardDuty。它使用堆疊輸出來記錄 GuardDuty 狀態以供未來參考。

透過遵循此模式，您可以自動化整個 AWS 基礎設施的 GuardDuty 部署，同時保持乾淨、可預測的 CloudFormation 堆疊操作。這種方法對以下組織特別有用：
+  AWS 帳戶 透過 IaC 管理多個
+ 大規模實作安全服務
+ 需要等冪基礎設施部署
+ 自動化安全服務部署

## 先決條件和限制
<a name="enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 具有建立、更新和刪除 CloudFormation 堆疊許可的 AWS Identity and Access Management (IAM) 角色
+ AWS Command Line Interface (AWS CLI)，[已安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html#getting-started-install-instructions)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)

**限制**

如果 AWS 帳戶 或 的 GuardDuty 已手動停用 AWS 區域，則此模式不會為該目標帳戶或區域啟用 GuardDuty。

## Architecture
<a name="enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates-architecture"></a>

**目標技術堆疊**

模式使用 CloudFormation 做為基礎設施的程式碼 (IaC)。您可以使用由 Lambda 函數支援的 CloudFormation 自訂資源來實現動態服務啟用功能。

**目標架構**

下列高階架構圖顯示透過部署 CloudFormation 範本來啟用 GuardDuty 的程序：

![使用 CloudFormation 堆疊在 AWS 帳戶中啟用 GuardDuty。](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/3abd7cb7-0937-41fe-8eaa-79aedb182732/images/71624052-eebc-474a-9aa3-8606d87fc51d.png)


1. 您可以部署 CloudFormation 範本來建立 CloudFormation 堆疊。

1. 堆疊會建立 IAM 角色和 Lambda 函數。

1. Lambda 函數會擔任 IAM 角色。

1. 如果目標上尚未啟用 GuardDuty AWS 帳戶，Lambda 函數會啟用它。

**自動化和擴展**

您可以使用 AWS CloudFormation StackSet 功能將此解決方案擴展到多個 AWS 帳戶 和 AWS 區域。如需詳細資訊，請參閱 CloudFormation 文件中的[使用 AWS CloudFormation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html)。

## 工具
<a name="enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates-tools"></a>
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您 AWS 服務 透過命令列 shell 中的命令與 互動。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 區域的生命週期中管理資源。
+ [Amazon GuardDuty](https://docs.aws.amazon.com/guardduty/latest/ug/what-is-guardduty.html) 是一項持續的安全監控服務，可分析和處理日誌，以識別您 AWS 環境中非預期和可能未經授權的活動。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。

## 史詩
<a name="enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates-epics"></a>

### 建立 CloudFormation 範本並部署堆疊
<a name="create-the-cfnshort-template-and-deploy-the-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將程式碼儲存在 Amazon S3 中。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates.html) | AWS DevOps | 
| 建立 CloudFormation 範本。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates.html) | AWS DevOps | 
| 建立 CloudFormation 堆疊。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates.html) | AWS DevOps | 
| 驗證是否已為 啟用 GuardDuty AWS 帳戶。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates.html) | 雲端管理員、AWS 管理員 | 
| 設定其他帳戶或區域。 | 根據您的使用案例，使用 CloudFormation StackSet 功能將此解決方案擴展到多個 AWS 帳戶 和 AWS 區域。如需詳細資訊，請參閱 CloudFormation 文件中的[使用 AWS CloudFormation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html)。 | 雲端管理員、AWS 管理員 | 

## 相關資源
<a name="enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates-resources"></a>

**參考**
+ [AWS CloudFormation 文件](https://docs.aws.amazon.com/cloudformation/index.html)
+ [AWS Lambda 資源類型參考](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/AWS_Lambda.html)
+ [CloudFormation 資源類型： AWS：IAM：：Role](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html)
+ [CloudFormation 資源類型： AWS：GuardDuty：：Detector](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-guardduty-detector.html)
+ [使用 擷取任何 AWS 服務屬性的四種方式 AWS CloudFormation](https://aws.amazon.com/blogs/mt/four-ways-to-retrieve-any-aws-service-property-using-aws-cloudformation-part-1/) （部落格文章）

**教學課程和影片**
+ [使用 簡化您的基礎設施管理 AWS CloudFormation](https://www.youtube.com/watch?v=1h-GPXQrLZw) （教學課程）
+ [使用 Amazon GuardDuty 和 AWS Security Hub CSPM 來保護多個帳戶 ](https://www.youtube.com/watch?v=Rg2ZzAAi1nY)(AWS re：Invent 2020)
+ [撰寫的最佳實務 AWS CloudFormation](https://www.youtube.com/watch?v=bJHHQM7GGro)(AWS re：Invent 2019)
+ [上的威脅偵測 AWS：Amazon GuardDuty 簡介 ](https://www.youtube.com/watch?v=czsuZXQvD8E)(AWS re：Inforce 2019)

## 其他資訊
<a name="enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates-additional"></a>

**Python 程式碼**

```
import boto3
import os
import json
from botocore.exceptions import ClientError
import cfnresponse
guardduty=boto3.client('guardduty')
cfn=boto3.client('cloudformation')
def lambda_handler(event, context):
    print('Event: ', event)
    if 'RequestType' in event:    
      if event['RequestType'] in ["Create","Update"]:
          enabled=False
          try:  
            response=guardduty.list_detectors()
            if "DetectorIds" in response and len(response["DetectorIds"])>0:
              enabled="AlreadyEnabled"
            elif "DetectorIds" in response and len(response["DetectorIds"])==0:
              cfn_response=cfn.create_stack(
                StackName='guardduty-cfn-stack',
                TemplateBody='{ "AWSTemplateFormatVersion": "2010-09-09",    "Description": "Guard duty creation template",    "Resources": { "IRWorkshopGuardDutyDetector": {  "Type": "AWS::GuardDuty::Detector",    "Properties": {   "Enable": true  }   } } }'
                )
              enabled="True"
          except Exception as e:
              print("Exception: ",e)
          responseData = {}
          responseData['status'] = enabled
          cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, "CustomResourcePhysicalID" )
      elif event['RequestType'] == "Delete":
          cfn_response=cfn.delete_stack(
                  StackName='guardduty-cfn-stack')
          cfnresponse.send(event, context, cfnresponse.SUCCESS, {})
```

