

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

# 自動化刪除 AWS CloudFormation 堆疊和相關聯的資源
<a name="automate-deletion-cloudformation-stacks-associated-resources"></a>

*SANDEEP SINGH 和 Amazon Web Services 的 James Jacob*

## 總結
<a name="automate-deletion-cloudformation-stacks-associated-resources-summary"></a>

[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 是一項廣泛使用的服務，可用來管理雲端基礎設施即程式碼 (IaC)。當您使用 CloudFormation 時，請以稱為*堆疊*的單一單位來管理相關資源。意即您能夠建立、更新和刪除堆疊，藉此建立、更新並刪除資源集合。

有時候，您不再需要 CloudFormation 堆疊中的資源。根據資源及其組態，刪除堆疊及其相關聯的資源可能很複雜。在實際生產系統中，由於 CloudFormation 無法覆寫的條件或限制衝突，刪除有時會失敗或需要很長時間。它可能需要仔細的規劃和執行，以確保以高效且一致的方式正確刪除所有資源。此模式說明如何設定架構，以協助您管理刪除涉及下列複雜性的 CloudFormation 堆疊：
+ **具有刪除保護的資源** – 有些資源可能已啟用刪除保護。常見範例為 [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 資料表和 [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 儲存貯體。刪除保護可防止自動刪除，例如透過 CloudFormation 刪除。如果您想要刪除這些資源，您必須手動或以程式設計方式覆寫或暫時停用刪除保護。在繼續之前，您應該仔細考慮刪除這些資源的含意。
+ **具有保留政策的資源** – 某些資源，例如 AWS Key Management Service (AWS KMS) 金鑰和 Amazon S3 儲存貯體，可能具有指定在請求刪除後應保留多久的保留政策。您應該在清除策略中考慮這些政策，以保持符合組織政策和法規要求。
+ **延遲刪除連接到 VPC 的 Lambda 函數** – 刪除連接到虛擬私有雲端 (VPC) 的[AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)函數可能需要 5-40 分鐘，取決於程序中涉及的多個互連相依性。如果您在刪除堆疊之前從 VPC 分離函數，您可以將此延遲減少到 1 分鐘以下。
+ **非由 CloudFormation 直接建立的資源** – 在某些應用程式設計中，資源可能會在原始 CloudFormation 堆疊之外建立，無論是由應用程式本身或透過堆疊佈建的資源。以下是兩個範例：
  + CloudFormation 可能會佈建執行使用者資料指令碼的 [Amazon Elastic Compute Cloud (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 執行個體。然後，此指令碼可能會建立 [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 參數來存放應用程式相關資料。此參數不是透過 CloudFormation 管理。
  + CloudFormation 可能會佈建 Lambda 函數，以自動產生 [Amazon CloudWatch Logs ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)群組來儲存日誌。此日誌群組不是透過 CloudFormation 管理。

  即使這些資源不是由 CloudFormation 直接管理，但通常在刪除堆疊時需要清除這些資源。如果未受管，它們可能會變得孤立，並導致不必要的資源消耗。

雖然這些護欄可能會造成複雜性，但它們是有意且關鍵的。允許 CloudFormation 覆寫所有限制條件和無差別刪除資源，在許多情況下可能會導致不利和不可預見的後果。不過，身為負責管理環境的 DevOps 或雲端工程師，有時可能需要覆寫這些限制，特別是在開發、測試或預備環境中。

**目標業務成果**

透過實作此架構，您可以實現下列優點：
+ **成本管理** – 定期且有效率地清理暫時性環境，例如end-to-end或使用者接受度測試環境，有助於防止資源執行超過必要的時間。這可以大幅降低成本。
+ **安全** – 自動清除過時或未使用的資源可減少攻擊面，並有助於維護安全 AWS 的環境。
+ **營運效率** – 定期和自動清理可提供下列營運優勢：
  + 移除舊日誌群組或空 Amazon S3 儲存貯體的自動化指令碼可以透過保持環境乾淨且可管理來提高營運效率。
  + 快速刪除和重新建立堆疊支援設計和實作的快速反覆運算，這可能會導致更強大和彈性的架構。
  + 定期刪除和重建環境可協助您識別和修正潛在問題。這可協助您確保基礎設施可以承受真實世界的案例。

## 先決條件和限制
<a name="automate-deletion-cloudformation-stacks-associated-resources-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ Python 3.6 版或更新版本，[已安裝](https://www.python.org/downloads/)
+ AWS Command Line Interface (AWS CLI)，[已安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)

**限制**
+ 命名慣例用於識別應刪除的資源。此模式中的範例程式碼使用資源名稱的字首，但您可以定義自己的命名慣例。不會識別未使用此命名慣例的資源，也不會隨後刪除。

## Architecture
<a name="automate-deletion-cloudformation-stacks-associated-resources-architecture"></a>

下圖顯示此架構如何識別目標 CloudFormation 堆疊及其相關聯的其他資源。

![\[探索、處理和刪除 CloudFormation 堆疊及其相關聯資源的階段。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/ab7c3b56-3476-41a3-8ece-68915605a546/images/a7fceb1c-d624-47b3-957d-f910ef2f44d7.png)


該圖顯示以下工作流程：

1. **收集資源** – 自動化架構使用命名慣例來傳回所有相關 CloudFormation 堆疊、Amazon Elastic Container Registry (Amazon ECR) 儲存庫、DynamoDB 資料表和 Amazon S3 儲存貯體。
**注意**  
此階段的函數使用[分頁程式](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html)，這是 Boto3 中的一項功能，可抽象化經過截斷 API 結果集的反覆運算程序。這可確保處理所有資源。若要進一步最佳化效能，請考慮套用[伺服器端](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results)篩選，或考慮使用 JMESPath [來執行用戶端](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results-with-jmespath)篩選。

1. **預先處理** – 自動化架構可識別並解決必須覆寫的服務限制條件，以允許 CloudFormation 刪除資源。例如，它會將 DynamoDB 資料表`DeletionProtectionEnabled`的設定變更為 `False`。在命令列界面中，針對每個資源，您會收到提示，詢問您是否要覆寫限制條件。

1. **刪除堆疊** – 自動化架構會刪除 CloudFormation 堆疊。在命令列界面中，您會收到提示，詢問您是否要刪除堆疊。

1. **後置處理** – 自動化架構會刪除任何未直接透過 CloudFormation 佈建的相關資源，做為堆疊的一部分。這些資源類型的範例包括 Systems Manager 參數和 CloudWatch 日誌群組。個別函數會收集這些資源、預先處理它們，然後刪除它們。在命令列界面中，針對每個資源，您會收到提示，詢問您是否要刪除資源。
**注意**  
此階段的函數使用[分頁程式](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html)，這是 Boto3 中的一項功能，可抽象化經過截斷 API 結果集的反覆運算程序。這可確保處理所有資源。若要進一步最佳化效能，請考慮套用[伺服器端](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results)篩選，或考慮使用 JMESPath [來執行用戶端](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results-with-jmespath)篩選。

**自動化和擴展**

如果您的 CloudFormation 堆疊包含範例程式碼中未包含的其他資源，或者堆疊具有此模式中未解決的限制，則可以針對您的使用案例調整自動化架構。遵循相同的方法來收集資源、預先處理、刪除堆疊，然後進行後續處理。

## 工具
<a name="automate-deletion-cloudformation-stacks-associated-resources-tools"></a>

**AWS 服務**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。
+ [CloudFormation 命令列界面 (CFN-CLI)](https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/what-is-cloudformation-cli.html) 是一種開放原始碼工具，可協助您開發和測試 AWS 和第三方延伸模組，然後註冊它們以在 CloudFormation 中使用。
+ [適用於 Python (Boto3) 的 AWS SDK](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) 是一種軟體開發套件，可協助您整合 Python 應用程式、程式庫或指令碼 AWS 服務。

**其他工具**
+ [按一下](https://click.palletsprojects.com/en/stable/)是 Python 工具，可協助您建立命令列界面。
+ [Poetry](https://python-poetry.org/docs/) 是一種在 Python 中管理相依性和封裝的工具。
+ [Pyenv](https://github.com/pyenv/pyenv) 是一種工具，可協助您管理和切換 Python 版本。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [cloudformation-stack-cleanup](https://github.com/aws-samples/cloudformation-stack-cleanup/) 儲存庫中使用。

## 最佳實務
<a name="automate-deletion-cloudformation-stacks-associated-resources-best-practices"></a>
+ **標記資源以方便識別** – 實作[標記策略](https://aws.amazon.com/solutions/guidance/tagging-on-aws/)來識別為不同環境和目的建立的資源。標籤可協助您根據資源的標籤篩選資源，以簡化清除程序。
+ **設定資源生命週期** – 定義資源生命週期，以便在特定期間之後自動刪除資源。此實務可協助您確保暫時環境不會成為永久成本負債。

## 史詩
<a name="automate-deletion-cloudformation-stacks-associated-resources-epics"></a>

### 安裝工具
<a name="install-tools"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 工程師 | 
| 安裝 Poetry。 | 依照[指示](https://python-poetry.org/docs/) (Poetry 文件） 在目標虛擬環境中安裝 Poetry。 | DevOps 工程師 | 
| 安裝依存項目。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 工程師 | 
| （選用） 安裝 Pyenv。 | 依照[指示](https://github.com/pyenv/pyenv#installation) (GitHub) 安裝 Pyenv。 | DevOps 工程師 | 

### （選用） 自訂架構
<a name="optional-customize-the-framework"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立收集、預先處理和刪除目標資源的函數。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 工程師，Python | 

### 建立範例資源
<a name="create-sample-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 CloudFormation 堆疊。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | AWS DevOps | 
| 建立 Systems Manager 參數。 | 輸入下列命令以建立未透過 CloudFormation 佈建的 Systems Manager 參數：<pre>aws ssm put-parameter \<br />  --name "/sampleforcleanup/database/password" \<br />  --value "your_db_password" \<br />  --type "SecureString" \<br />  --description "Database password for my app" \<br />  --tier "Standard" \<br />  --region "us-east-1"</pre> | AWS DevOps | 
| 建立 Amazon S3 儲存貯體。 | 輸入下列命令來建立未透過 CloudFormation 佈建的 Amazon S3 儲存貯體：<pre>aws s3api create-bucket \<br />  --bucket samplesorcleanup-unmanagedbucket-<UniqueIdentifier> \<br />  --region us-east-1 \<br />  --create-bucket-configuration LocationConstraint=us-east-1</pre> | AWS DevOps | 

### 刪除範例資源
<a name="delete-the-sample-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除 CloudFormation 堆疊。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | AWS DevOps | 
| 驗證資源刪除。 | 在輸出中，確認已刪除所有範例資源。如需範例輸出，請參閱此模式[的其他資源](#automate-deletion-cloudformation-stacks-associated-resources-additional)區段。 | AWS DevOps | 

## 相關資源
<a name="automate-deletion-cloudformation-stacks-associated-resources-resources"></a>
+ [刪除堆疊 ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html)(CloudFormation 文件）
+ [故障診斷 CloudFormation ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)(CloudFormation 文件）
+ [讓 Lambda 函數存取 Amazon VPC 中的資源 ](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)(Lambda 文件）
+ [如何刪除卡在 DELETE\$1FAILED 狀態的 AWS CloudFormation 堆疊？](https://repost.aws/knowledge-center/cloudformation-stack-delete-failed) (AWS 知識中心）

## 其他資訊
<a name="automate-deletion-cloudformation-stacks-associated-resources-additional"></a>

以下是來自 `cfncli`命令的範例輸出：

```
cfncli --region aus-east-1  dev cleanup-env --prefix-list sampleforcleanup                                                                                                                              
https://sts.us-east-1.amazonaws.com
Cleaning up: ['sampleforcleanup'] in xxxxxxxxxx:us-east-1
Do you want to proceed? [Y/n]: Y
No S3 buckets
No ECR repositories
No Lambda functions in VPC
The following DynamoDB tables will have their deletion protection removed:
sampleforcleanup-MyDynamoDBTable
Do you want to proceed with removing deletion protection from these tables? [Y/n]: Y
Deletion protection disabled for DynamoDB table 'sampleforcleanup-MyDynamoDBTable'.
The following CloudFormation stacks will be deleted:
sampleforcleanup-Stack
Do you want to proceed with deleting these CloudFormation stacks? [Y/n]: Y
Initiated deletion of CloudFormation stack: `sampleforcleanup-Stack`
Waiting for stack `sampleforcleanup-Stack` to be deleted...
CloudFormation stack `sampleforcleanup-Stack` deleted successfully.
The following ssm_params will be deleted:
/sampleforcleanup/database/password
Do you want to proceed with deleting these ssm_params? [Y/n]: Y
Deleted SSM Parameter: /sampleforcleanup/database/password
Cleaned up: ['sampleforcleanup']
```