

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 [AWS SDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)。

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

# CloudFormation 使用 AWS SDKs程式碼範例
<a name="cloudformation_code_examples"></a>

下列程式碼範例示範如何使用 AWS CloudFormation 搭配 AWS 軟體開發套件 (SDK)。

*Actions* 是大型程式的程式碼摘錄，必須在內容中執行。雖然動作會告訴您如何呼叫個別服務函數，但您可以在其相關情境中查看內容中的動作。

*案例*是向您展示如何呼叫服務中的多個函數或與其他 AWS 服務組合來完成特定任務的程式碼範例。

**其他資源**
+  **[CloudFormation 使用者指南](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)** – 有關 的詳細資訊 CloudFormation。
+ **[CloudFormation API 參考](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/Welcome.html)** – 所有可用 CloudFormation 動作的詳細資訊。
+ **[AWS 開發人員中心](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23cloudformation)** – 您可以依類別或全文搜尋篩選的程式碼範例。
+ **[AWS SDK 範例](https://github.com/awsdocs/aws-doc-sdk-examples)** – GitHub 儲存庫使用慣用語言的完整程式碼。包含設定和執行程式碼的指示。

**Contents**
+ [基本概念](cloudformation_code_examples_basics.md)
  + [您好 CloudFormation](cloudformation_example_cloudformation_Hello_section.md)
  + [動作](cloudformation_code_examples_actions.md)
    + [`CancelUpdateStack`](cloudformation_example_cloudformation_CancelUpdateStack_section.md)
    + [`ContinueUpdateRollback`](cloudformation_example_cloudformation_ContinueUpdateRollback_section.md)
    + [`CreateStack`](cloudformation_example_cloudformation_CreateStack_section.md)
    + [`DeleteStack`](cloudformation_example_cloudformation_DeleteStack_section.md)
    + [`DescribeStackEvents`](cloudformation_example_cloudformation_DescribeStackEvents_section.md)
    + [`DescribeStackResource`](cloudformation_example_cloudformation_DescribeStackResource_section.md)
    + [`DescribeStackResources`](cloudformation_example_cloudformation_DescribeStackResources_section.md)
    + [`DescribeStacks`](cloudformation_example_cloudformation_DescribeStacks_section.md)
    + [`EstimateTemplateCost`](cloudformation_example_cloudformation_EstimateTemplateCost_section.md)
    + [`GetTemplate`](cloudformation_example_cloudformation_GetTemplate_section.md)
    + [`ListStackResources`](cloudformation_example_cloudformation_ListStackResources_section.md)
    + [`ListStacks`](cloudformation_example_cloudformation_ListStacks_section.md)
    + [`UpdateStack`](cloudformation_example_cloudformation_UpdateStack_section.md)
    + [`ValidateTemplate`](cloudformation_example_cloudformation_ValidateTemplate_section.md)
+ [案例](cloudformation_code_examples_scenarios.md)
  + [建立 REST API 以追蹤 COVID-19 資料](cloudformation_example_cross_ApiGatewayDataTracker_section.md)

# CloudFormation 使用 AWS SDKs的基本範例
<a name="cloudformation_code_examples_basics"></a>

下列程式碼範例示範如何 AWS CloudFormation 搭配 AWS SDKs 使用 的基本概念。

**Contents**
+ [您好 CloudFormation](cloudformation_example_cloudformation_Hello_section.md)
+ [動作](cloudformation_code_examples_actions.md)
  + [`CancelUpdateStack`](cloudformation_example_cloudformation_CancelUpdateStack_section.md)
  + [`ContinueUpdateRollback`](cloudformation_example_cloudformation_ContinueUpdateRollback_section.md)
  + [`CreateStack`](cloudformation_example_cloudformation_CreateStack_section.md)
  + [`DeleteStack`](cloudformation_example_cloudformation_DeleteStack_section.md)
  + [`DescribeStackEvents`](cloudformation_example_cloudformation_DescribeStackEvents_section.md)
  + [`DescribeStackResource`](cloudformation_example_cloudformation_DescribeStackResource_section.md)
  + [`DescribeStackResources`](cloudformation_example_cloudformation_DescribeStackResources_section.md)
  + [`DescribeStacks`](cloudformation_example_cloudformation_DescribeStacks_section.md)
  + [`EstimateTemplateCost`](cloudformation_example_cloudformation_EstimateTemplateCost_section.md)
  + [`GetTemplate`](cloudformation_example_cloudformation_GetTemplate_section.md)
  + [`ListStackResources`](cloudformation_example_cloudformation_ListStackResources_section.md)
  + [`ListStacks`](cloudformation_example_cloudformation_ListStacks_section.md)
  + [`UpdateStack`](cloudformation_example_cloudformation_UpdateStack_section.md)
  + [`ValidateTemplate`](cloudformation_example_cloudformation_ValidateTemplate_section.md)

# 您好 CloudFormation
<a name="cloudformation_example_cloudformation_Hello_section"></a>

下列程式碼範例示範如何開始使用 CloudFormation。

------
#### [ .NET ]

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

```
using Amazon.CloudFormation;
using Amazon.CloudFormation.Model;
using Amazon.Runtime;

namespace CloudFormationActions;

public static class HelloCloudFormation
{
    public static IAmazonCloudFormation _amazonCloudFormation = null!;

    static async Task Main(string[] args)
    {
        // Create the CloudFormation client
        _amazonCloudFormation = new AmazonCloudFormationClient();
        Console.WriteLine($"\nIn Region: {_amazonCloudFormation.Config.RegionEndpoint}");

        // List the resources for each stack
        await ListResources();
    }

    /// <summary>
    /// Method to list stack resources and other information.
    /// </summary>
    /// <returns>True if successful.</returns>
    public static async Task<bool> ListResources()
    {
        try
        {
            Console.WriteLine("Getting CloudFormation stack information...");

            // Get all stacks using the stack paginator.
            var paginatorForDescribeStacks =
                _amazonCloudFormation.Paginators.DescribeStacks(
                    new DescribeStacksRequest());
            if (paginatorForDescribeStacks.Stacks != null)
            {
                await foreach (Stack stack in paginatorForDescribeStacks.Stacks)
                {
                    // Basic information for each stack
                    Console.WriteLine(
                        "\n------------------------------------------------");
                    Console.WriteLine($"\nStack: {stack.StackName}");
                    Console.WriteLine($"  Status: {stack.StackStatus.Value}");
                    Console.WriteLine($"  Created: {stack.CreationTime}");

                    // The tags of each stack (etc.)
                    if (stack.Tags != null && stack.Tags.Count > 0)
                    {
                        Console.WriteLine("  Tags:");
                        foreach (Tag tag in stack.Tags)
                            Console.WriteLine($"    {tag.Key}, {tag.Value}");
                    }

                    // The resources of each stack
                    DescribeStackResourcesResponse responseDescribeResources =
                        await _amazonCloudFormation.DescribeStackResourcesAsync(
                            new DescribeStackResourcesRequest
                            {
                                StackName = stack.StackName
                            });
                    if (responseDescribeResources.StackResources != null && responseDescribeResources.StackResources.Count > 0)
                    {
                        Console.WriteLine("  Resources:");
                        foreach (StackResource resource in responseDescribeResources
                                     .StackResources)
                            Console.WriteLine(
                                $"    {resource.LogicalResourceId}: {resource.ResourceStatus}");
                    }
                }
            }

            Console.WriteLine("\n------------------------------------------------");
            return true;
        }
        catch (AmazonCloudFormationException ex)
        {
            Console.WriteLine("Unable to get stack information:\n" + ex.Message);
            return false;
        }
        catch (AmazonServiceException ex)
        {
            if (ex.Message.Contains("Unable to get IAM security credentials"))
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("If you are usnig SSO, be sure to install" +
                                  " the AWSSDK.SSO and AWSSDK.SSOOIDC packages.");
            }
            else
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return false;
        }
        catch (ArgumentNullException ex)
        {
            if (ex.Message.Contains("Options property cannot be empty: ClientName"))
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("If you are using SSO, have you logged in?");
            }
            else
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            return false;
        }
    }
```
+  如需 API 詳細資訊，請參閱*《適用於 .NET 的 AWS SDK API 參考》*中的 [DescribeStackResources](https://docs.aws.amazon.com/goto/DotNetSDKV4/cloudformation-2010-05-15/DescribeStackResources)。

------

# CloudFormation 使用 AWS SDKs的動作
<a name="cloudformation_code_examples_actions"></a>

下列程式碼範例示範如何使用 AWS SDKs執行個別 CloudFormation 動作。每個範例均包含 GitHub 的連結，您可以在連結中找到設定和執行程式碼的相關說明。

這些摘錄會呼叫 CloudFormation API，是必須在內容中執行之大型程式的程式碼摘錄。您可以在 [CloudFormation 使用 AWS SDKs案例](cloudformation_code_examples_scenarios.md) 中查看內容中的動作。

 下列範例僅包含最常使用的動作。如需完整清單，請參閱《[AWS CloudFormation API 參考](https://docs.aws.amazon.com/AWSCloudFormation/latest/APIReference/Welcome.html)》。

**Topics**
+ [`CancelUpdateStack`](cloudformation_example_cloudformation_CancelUpdateStack_section.md)
+ [`ContinueUpdateRollback`](cloudformation_example_cloudformation_ContinueUpdateRollback_section.md)
+ [`CreateStack`](cloudformation_example_cloudformation_CreateStack_section.md)
+ [`DeleteStack`](cloudformation_example_cloudformation_DeleteStack_section.md)
+ [`DescribeStackEvents`](cloudformation_example_cloudformation_DescribeStackEvents_section.md)
+ [`DescribeStackResource`](cloudformation_example_cloudformation_DescribeStackResource_section.md)
+ [`DescribeStackResources`](cloudformation_example_cloudformation_DescribeStackResources_section.md)
+ [`DescribeStacks`](cloudformation_example_cloudformation_DescribeStacks_section.md)
+ [`EstimateTemplateCost`](cloudformation_example_cloudformation_EstimateTemplateCost_section.md)
+ [`GetTemplate`](cloudformation_example_cloudformation_GetTemplate_section.md)
+ [`ListStackResources`](cloudformation_example_cloudformation_ListStackResources_section.md)
+ [`ListStacks`](cloudformation_example_cloudformation_ListStacks_section.md)
+ [`UpdateStack`](cloudformation_example_cloudformation_UpdateStack_section.md)
+ [`ValidateTemplate`](cloudformation_example_cloudformation_ValidateTemplate_section.md)

# 搭配使用 `CancelUpdateStack` 與 CLI
<a name="cloudformation_example_cloudformation_CancelUpdateStack_section"></a>

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

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

**AWS CLI**  
**取消進行中的堆疊更新**  
下列 `cancel-update-stack` 命令會取消 `myteststack` 堆疊上的堆疊更新：  

```
aws cloudformation cancel-update-stack --stack-name myteststack
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [CancelUpdateStack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/cancel-update-stack.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：取消指定堆疊的更新。**  

```
Stop-CFNUpdateStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [CancelUpdateStack](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：取消指定堆疊的更新。**  

```
Stop-CFNUpdateStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CancelUpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `ContinueUpdateRollback` 與 CLI
<a name="cloudformation_example_cloudformation_ContinueUpdateRollback_section"></a>

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

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

**AWS CLI**  
**重試更新還原**  
下列 `continue-update-rollback` 範例從先前失敗的堆疊更新處繼續還原操作。  

```
aws cloudformation continue-update-rollback \
    --stack-name my-stack
```
此命令不會產生輸出。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [ContinueUpdateRollback](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/continue-update-rollback.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：繼續還原具名堆疊，其應處於 'UPDATE\$1ROLLBACK\$1FAILED' 狀態。如果繼續還原成功，堆疊將進入狀態 'UPDATE\$1ROLLBACK\$1COMPLETE'。**  

```
Resume-CFNUpdateRollback -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [ContinueUpdateRollback](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：繼續還原具名堆疊，其應處於 'UPDATE\$1ROLLBACK\$1FAILED' 狀態。如果繼續還原成功，堆疊將進入狀態 'UPDATE\$1ROLLBACK\$1COMPLETE'。**  

```
Resume-CFNUpdateRollback -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ContinueUpdateRollback](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `CreateStack` 與 CLI
<a name="cloudformation_example_cloudformation_CreateStack_section"></a>

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

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

**AWS CLI**  
**建立 AWS CloudFormation 堆疊**  
以下 `create-stacks` 命令使用 `sampletemplate.json` 範本建立名為 `myteststack` 的堆疊：  

```
aws cloudformation create-stack --stack-name myteststack --template-body file://sampletemplate.json --parameters ParameterKey=KeyPairName,ParameterValue=TestKey ParameterKey=SubnetIDs,ParameterValue=SubnetID1\\,SubnetID2
```
輸出：  

```
{
    "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896"
}
```
如需詳細資訊，請參閱《*AWS CloudFormation 使用者指南*》中的堆疊。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [CreateStack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/create-stack.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：使用指定的名稱建立新堆疊。範本是根據提供的內容和自訂參數 ('PK1' 和 'PK2' 代表範本內容中宣告的參數名稱，'PV1' 和 'PV2' 代表這些參數的值) 進行剖析。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果堆疊建立失敗，則不會還原。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" }) `
             -DisableRollback $true
```
**範例 2：使用指定的名稱建立新堆疊。範本是根據提供的內容和自訂參數 ('PK1' 和 'PK2' 代表範本內容中宣告的參數名稱，'PV1' 和 'PV2' 代表這些參數的值) 進行剖析。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果堆疊建立失敗，則會還原。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "PK1"
$p1.ParameterValue = "PV1"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "PK2"
$p2.ParameterValue = "PV2"

New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( $p1, $p2 ) `
             -OnFailure "ROLLBACK"
```
**範例 3：使用指定的名稱建立新堆疊。範本是從具有自訂參數 ('PK1' 代表範本內容中宣告的參數名稱，'PV1' 代表參數的值) 的 Amazon S3 URL 取得。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果建立堆疊失敗，則會還原 (與指定 -DisableRollback \$1false 相同)。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 4：使用指定的名稱建立新堆疊。範本是從具有自訂參數 ('PK1' 代表範本內容中宣告的參數名稱，'PV1' 代表參數的值) 的 Amazon S3 URL 取得。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果建立堆疊失敗，則會還原 (與指定 -DisableRollback \$1false 相同)。指定的通知 AEN 會收到已發佈的堆疊相關事件。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" } `
             -NotificationARN @( "arn1", "arn2" )
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [CreateStack](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：使用指定的名稱建立新堆疊。範本是根據提供的內容和自訂參數 ('PK1' 和 'PK2' 代表範本內容中宣告的參數名稱，'PV1' 和 'PV2' 代表這些參數的值) 進行剖析。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果堆疊建立失敗，則不會還原。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" }) `
             -DisableRollback $true
```
**範例 2：使用指定的名稱建立新堆疊。範本是根據提供的內容和自訂參數 ('PK1' 和 'PK2' 代表範本內容中宣告的參數名稱，'PV1' 和 'PV2' 代表這些參數的值) 進行剖析。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果堆疊建立失敗，則會還原。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "PK1"
$p1.ParameterValue = "PV1"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "PK2"
$p2.ParameterValue = "PV2"

New-CFNStack -StackName "myStack" `
             -TemplateBody "{TEMPLATE CONTENT HERE}" `
             -Parameter @( $p1, $p2 ) `
             -OnFailure "ROLLBACK"
```
**範例 3：使用指定的名稱建立新堆疊。範本是從具有自訂參數 ('PK1' 代表範本內容中宣告的參數名稱，'PV1' 代表參數的值) 的 Amazon S3 URL 取得。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果建立堆疊失敗，則會還原 (與指定 -DisableRollback \$1false 相同)。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 4：使用指定的名稱建立新堆疊。範本是從具有自訂參數 ('PK1' 代表範本內容中宣告的參數名稱，'PV1' 代表參數的值) 的 Amazon S3 URL 取得。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。如果建立堆疊失敗，則會還原 (與指定 -DisableRollback \$1false 相同)。指定的通知 AEN 會收到已發佈的堆疊相關事件。**  

```
New-CFNStack -StackName "myStack" `
             -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
             -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" } `
             -NotificationARN @( "arn1", "arn2" )
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [CreateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `DeleteStack` 與 CLI
<a name="cloudformation_example_cloudformation_DeleteStack_section"></a>

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

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

**AWS CLI**  
**刪除堆疊**  
以下 `delete-stack` 範例會刪除指定的堆疊。  

```
aws cloudformation delete-stack \
    --stack-name my-stack
```
此命令不會產生輸出。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DeleteStack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/delete-stack.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：刪除指定的堆疊。**  

```
Remove-CFNStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V4)*》中的 [DeleteStack](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：刪除指定的堆疊。**  

```
Remove-CFNStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [DeleteStack](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `DescribeStackEvents` 與 CLI
<a name="cloudformation_example_cloudformation_DescribeStackEvents_section"></a>

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

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

**AWS CLI**  
**描述堆疊事件**  
下列 `describe-stack-events` 範例顯示指定堆疊的 2 個最近事件。  

```
aws cloudformation describe-stack-events \
    --stack-name my-stack \
    --max-items 2

{
    "StackEvents": [
        {
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "EventId": "4e1516d0-e4d6-xmpl-b94f-0a51958a168c",
            "StackName": "my-stack",
            "LogicalResourceId": "my-stack",
            "PhysicalResourceId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "ResourceType": "AWS::CloudFormation::Stack",
            "Timestamp": "2019-10-02T05:34:29.556Z",
            "ResourceStatus": "UPDATE_COMPLETE"
        },
        {
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "EventId": "4dd3c810-e4d6-xmpl-bade-0aaf8b31ab7a",
            "StackName": "my-stack",
            "LogicalResourceId": "my-stack",
            "PhysicalResourceId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "ResourceType": "AWS::CloudFormation::Stack",
            "Timestamp": "2019-10-02T05:34:29.127Z",
            "ResourceStatus": "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"
        }
    ],
    "NextToken": "eyJOZXh0VG9XMPLiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiAyfQ=="
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DescribeStackEvents](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-events.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回特定堆疊的所有堆疊相關事件。**  

```
Get-CFNStackEvent -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [DescribeStackEvents](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回特定堆疊的所有堆疊相關事件。**  

```
Get-CFNStackEvent -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStackEvents](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `DescribeStackResource` 與 CLI
<a name="cloudformation_example_cloudformation_DescribeStackResource_section"></a>

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

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

**AWS CLI**  
**取得堆疊資源的相關資訊**  
下列 `describe-stack-resource` 範例顯示指定的堆疊中名為 `MyFunction` 的資源詳細資訊。  

```
aws cloudformation describe-stack-resource \
    --stack-name MyStack \
    --logical-resource-id MyFunction
```
輸出：  

```
{
    "StackResourceDetail": {
        "StackName": "MyStack",
        "StackId": "arn:aws:cloudformation:us-east-2:123456789012:stack/MyStack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
        "LogicalResourceId": "MyFunction",
        "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
        "ResourceType": "AWS::Lambda::Function",
        "LastUpdatedTimestamp": "2019-10-02T05:34:27.989Z",
        "ResourceStatus": "UPDATE_COMPLETE",
        "Metadata": "{}",
        "DriftInformation": {
            "StackResourceDriftStatus": "IN_SYNC"
        }
    }
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DescribeStackResource](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-resource.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回透過邏輯 ID "MyDBInstance" 在與指定堆疊相關聯的範本中識別的資源描述。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [DescribeStackResource](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回透過邏輯 ID "MyDBInstance" 在與指定堆疊相關聯的範本中識別的資源描述。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStackResource](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `DescribeStackResources` 與 CLI
<a name="cloudformation_example_cloudformation_DescribeStackResources_section"></a>

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

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

**AWS CLI**  
**取得堆疊資源的相關資訊**  
下列 `describe-stack-resources` 範例顯示指定之堆疊中的資源詳細資訊。  

```
aws cloudformation describe-stack-resources \
    --stack-name my-stack
```
輸出：  

```
{
    "StackResources": [
        {
            "StackName": "my-stack",
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "LogicalResourceId": "bucket",
            "PhysicalResourceId": "my-stack-bucket-1vc62xmplgguf",
            "ResourceType": "AWS::S3::Bucket",
            "Timestamp": "2019-10-02T04:34:11.345Z",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        },
        {
            "StackName": "my-stack",
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "LogicalResourceId": "function",
            "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
            "ResourceType": "AWS::Lambda::Function",
            "Timestamp": "2019-10-02T05:34:27.989Z",
            "ResourceStatus": "UPDATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        },
        {
            "StackName": "my-stack",
            "StackId": "arn:aws:cloudformation:us-west-2:123456789012:stack/my-stack/d0a825a0-e4cd-xmpl-b9fb-061c69e99204",
            "LogicalResourceId": "functionRole",
            "PhysicalResourceId": "my-functionRole-HIZXMPLEOM9E",
            "ResourceType": "AWS::IAM::Role",
            "Timestamp": "2019-10-02T04:34:06.350Z",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        }
    ]
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [DescribeStackResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stack-resources.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回最多 100 個與指定堆疊相關聯的資源 AWS 描述。若要取得與堆疊相關聯的所有資源詳細資訊，請使用 Get-CFNStackResourceSummary，這也支援手動分頁結果。**  

```
Get-CFNStackResourceList -StackName "myStack"
```
**範例 2：傳回邏輯 ID "Ec2Instance" 在與指定堆疊相關聯的範本中識別的 Amazon EC2 執行個體描述。**  

```
Get-CFNStackResourceList -StackName "myStack" -LogicalResourceId "Ec2Instance"
```
**範例 3：傳回最多 100 個與堆疊相關聯的資源描述，其中包含由執行個體 ID "i-123456" 識別的 Amazon EC2 執行個體。若要取得與堆疊相關聯的所有資源詳細資訊，請使用 Get-CFNStackResourceSummary，這也支援手動分頁結果。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456"
```
**範例 4：傳回堆疊範本中邏輯 ID "Ec2Instance" 所識別的 Amazon EC2 執行個體描述。堆疊是使用其包含的資源的實體資源 ID 來識別，在此情況下，也會使用執行個體 ID 為 "i-123456" 的 Amazon EC2 執行個體。根據範本內容，也可以使用不同的實體資源來識別堆疊，例如 Amazon S3 儲存貯體。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456" -LogicalResourceId "Ec2Instance"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [DescribeStackResources](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回最多 100 個與指定堆疊相關聯的資源 AWS 描述。若要取得與堆疊相關聯的所有資源詳細資訊，請使用 Get-CFNStackResourceSummary，這也支援手動分頁結果。**  

```
Get-CFNStackResourceList -StackName "myStack"
```
**範例 2：傳回邏輯 ID "Ec2Instance" 在與指定堆疊相關聯的範本中識別的 Amazon EC2 執行個體描述。**  

```
Get-CFNStackResourceList -StackName "myStack" -LogicalResourceId "Ec2Instance"
```
**範例 3：傳回最多 100 個與堆疊相關聯的資源描述，其中包含由執行個體 ID "i-123456" 識別的 Amazon EC2 執行個體。若要取得與堆疊相關聯的所有資源詳細資訊，請使用 Get-CFNStackResourceSummary，這也支援手動分頁結果。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456"
```
**範例 4：傳回堆疊範本中邏輯 ID "Ec2Instance" 所識別的 Amazon EC2 執行個體描述。堆疊是使用其包含的資源的實體資源 ID 來識別，在此情況下，也會使用執行個體 ID 為 "i-123456" 的 Amazon EC2 執行個體。根據範本內容，也可以使用不同的實體資源來識別堆疊，例如 Amazon S3 儲存貯體。**  

```
Get-CFNStackResourceList -PhysicalResourceId "i-123456" -LogicalResourceId "Ec2Instance"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStackResources](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# `DescribeStacks` 搭配 AWS SDK 或 CLI 使用
<a name="cloudformation_example_cloudformation_DescribeStacks_section"></a>

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

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

**AWS CLI**  
**描述 AWS CloudFormation 堆疊**  
以下 `describe-stacks` 範例顯示 `myteststack` 堆疊的摘要資訊：  

```
aws cloudformation describe-stacks --stack-name myteststack
```
輸出：  

```
{
    "Stacks":  [
        {
            "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896",
            "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
            "Tags": [],
            "Outputs": [
                {
                    "Description": "Name of S3 bucket to hold website content",
                    "OutputKey": "BucketName",
                    "OutputValue": "myteststack-s3bucket-jssofi1zie2w"
                }
            ],
            "StackStatusReason": null,
            "CreationTime": "2013-08-23T01:02:15.422Z",
            "Capabilities": [],
            "StackName": "myteststack",
            "StackStatus": "CREATE_COMPLETE",
            "DisableRollback": false
        }
    ]
}
```
如需詳細資訊，請參閱《*AWS CloudFormation 使用者指南*》中的堆疊。  
+  如需 API 詳細資訊，請參閱*《AWS CLI 命令參考》*中的 [DescribeStacks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/describe-stacks.html)。

------
#### [ Go ]

**SDK for Go V2**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [AWS 程式碼範例儲存庫](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/user_pools_and_lambda_triggers#code-examples)中設定和執行。

```
import (
	"context"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/cloudformation"
)

// StackOutputs defines a map of outputs from a specific stack.
type StackOutputs map[string]string

type CloudFormationActions struct {
	CfnClient *cloudformation.Client
}

// GetOutputs gets the outputs from a CloudFormation stack and puts them into a structured format.
func (actor CloudFormationActions) GetOutputs(ctx context.Context, stackName string) StackOutputs {
	output, err := actor.CfnClient.DescribeStacks(ctx, &cloudformation.DescribeStacksInput{
		StackName: aws.String(stackName),
	})
	if err != nil || len(output.Stacks) == 0 {
		log.Panicf("Couldn't find a CloudFormation stack named %v. Here's why: %v\n", stackName, err)
	}
	stackOutputs := StackOutputs{}
	for _, out := range output.Stacks[0].Outputs {
		stackOutputs[*out.OutputKey] = *out.OutputValue
	}
	return stackOutputs
}
```
+  如需 API 詳細資訊，請參閱《適用於 Go 的 AWS SDK  API 參考》**中的 [DescribeStacks](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/cloudformation#Client.DescribeStacks)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回描述所有使用者堆疊的堆疊執行個體集合。**  

```
Get-CFNStack
```
**範例 2：傳回描述指定堆疊的堆疊執行個體**  

```
Get-CFNStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [DescribeStacks](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回描述所有使用者堆疊的堆疊執行個體集合。**  

```
Get-CFNStack
```
**範例 2：傳回描述指定堆疊的堆疊執行個體**  

```
Get-CFNStack -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [DescribeStacks](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `EstimateTemplateCost` 與 CLI
<a name="cloudformation_example_cloudformation_EstimateTemplateCost_section"></a>

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

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

**AWS CLI**  
**估算範本成本**  
下列 `estimate-template-cost` 範例會為目前資料夾中名為 `template.yaml` 的範本產生估算成本。  

```
aws cloudformation estimate-template-cost \
    --template-body file://template.yaml
```
輸出：  

```
{
    "Url": "http://calculator.s3.amazonaws.com/calc5.html?key=cloudformation/7870825a-xmpl-4def-92e7-c4f8dd360cca"
}
```
+  如需 API 詳細資訊，請參閱《*AWS CLI 命令參考*》中的 [EstimateTemplateCost](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/estimate-template-cost.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回 AWS 簡易每月計算器 URL，其中包含查詢字串，說明執行範本所需的資源。範本是從指定的 Amazon S3 URL 和套用的單一自訂參數取得。參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Measure-CFNTemplateCost -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                        -Region us-west-1 `
                        -Parameter @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" }
```
**範例 2：傳回 AWS 簡易每月計算器 URL，其中包含查詢字串，說明執行範本所需的資源。範本會從提供的內容剖析，並套用自訂參數 (此範例假設範本內容已宣告兩個參數：'KeyName' 和 'InstanceType')。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" `
                        -Parameter @( @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" },`
                                      @{ ParameterKey="InstanceType"; ParameterValue="m1.large" })
```
**範例 3：使用 New-Object 建置一組範本參數，並傳回具有查詢字串的 AWS 簡易每月計算器 URL，該字串說明執行範本所需的資源。範本是從提供的內容中剖析，具有自訂參數 (此範例假設範本內容已宣告兩個參數：'KeyName' 和 'InstanceType')。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "KeyName"
$p1.ParameterValue = "myKeyPairName"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "InstanceType"
$p2.ParameterValue = "m1.large"

Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" -Parameter @( $p1, $p2 )
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V4)*》中的 [EstimateTemplateCost](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回 AWS 簡易每月計算器 URL，其中包含查詢字串，說明執行範本所需的資源。範本是從指定的 Amazon S3 URL 和套用的單一自訂參數取得。參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Measure-CFNTemplateCost -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                        -Region us-west-1 `
                        -Parameter @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" }
```
**範例 2：傳回 AWS 簡易每月計算器 URL，其中包含查詢字串，說明執行範本所需的資源。範本會從提供的內容剖析，並套用自訂參數 (此範例假設範本內容已宣告兩個參數：'KeyName' 和 'InstanceType')。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" `
                        -Parameter @( @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" },`
                                      @{ ParameterKey="InstanceType"; ParameterValue="m1.large" })
```
**範例 3：使用 New-Object 建置一組範本參數，並傳回具有查詢字串的 AWS 簡易每月計算器 URL，該字串說明執行範本所需的資源。範本是從提供的內容中剖析，具有自訂參數 (此範例假設範本內容已宣告兩個參數：'KeyName' 和 'InstanceType')。**  

```
$p1 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p1.ParameterKey = "KeyName"
$p1.ParameterValue = "myKeyPairName"

$p2 = New-Object -Type Amazon.CloudFormation.Model.Parameter
$p2.ParameterKey = "InstanceType"
$p2.ParameterValue = "m1.large"

Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" -Parameter @( $p1, $p2 )
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V5)*》中的 [EstimateTemplateCost](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `GetTemplate` 與 CLI
<a name="cloudformation_example_cloudformation_GetTemplate_section"></a>

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

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

**AWS CLI**  
**檢視 an AWS CloudFormation 堆疊的範本內文**  
下列 `get-template` 命令示範 `myteststack` 堆疊的範本：  

```
aws cloudformation get-template --stack-name myteststack
```
輸出：  

```
{
    "TemplateBody": {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Outputs": {
            "BucketName": {
                "Description": "Name of S3 bucket to hold website content",
                "Value": {
                    "Ref": "S3Bucket"
                }
            }
        },
        "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
        "Resources": {
            "S3Bucket": {
                "Type": "AWS::S3::Bucket",
                "Properties": {
                    "AccessControl": "PublicRead"
                }
            }
        }
    }
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [GetTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/get-template.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回與指定堆疊相關聯的範本。**  

```
Get-CFNTemplate -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [GetTemplate](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回與指定堆疊相關聯的範本。**  

```
Get-CFNTemplate -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [GetTemplate](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `ListStackResources` 與 CLI
<a name="cloudformation_example_cloudformation_ListStackResources_section"></a>

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

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

**AWS CLI**  
**列出堆疊中的資源**  
下列命令顯示指定堆疊中的資源清單。  

```
aws cloudformation list-stack-resources \
    --stack-name my-stack
```
輸出：  

```
{
    "StackResourceSummaries": [
        {
            "LogicalResourceId": "bucket",
            "PhysicalResourceId": "my-stack-bucket-1vc62xmplgguf",
            "ResourceType": "AWS::S3::Bucket",
            "LastUpdatedTimestamp": "2019-10-02T04:34:11.345Z",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        },
        {
            "LogicalResourceId": "function",
            "PhysicalResourceId": "my-function-SEZV4XMPL4S5",
            "ResourceType": "AWS::Lambda::Function",
            "LastUpdatedTimestamp": "2019-10-02T05:34:27.989Z",
            "ResourceStatus": "UPDATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        },
        {
            "LogicalResourceId": "functionRole",
            "PhysicalResourceId": "my-functionRole-HIZXMPLEOM9E",
            "ResourceType": "AWS::IAM::Role",
            "LastUpdatedTimestamp": "2019-10-02T04:34:06.350Z",
            "ResourceStatus": "CREATE_COMPLETE",
            "DriftInformation": {
                "StackResourceDriftStatus": "IN_SYNC"
            }
        }
    ]
}
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [ListStackResources](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stack-resources.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回與指定堆疊相關聯的所有資源的描述。**  

```
Get-CFNStackResourceSummary -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [ListStackResources](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回與指定堆疊相關聯的所有資源的描述。**  

```
Get-CFNStackResourceSummary -StackName "myStack"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListStackResources](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `ListStacks` 與 CLI
<a name="cloudformation_example_cloudformation_ListStacks_section"></a>

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

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

**AWS CLI**  
**列出 AWS CloudFormation 堆疊**  
以下 `list-stacks` 命令示範狀態為 `CREATE_COMPLETE` 之所有堆疊的摘要：  

```
aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE
```
輸出：  

```
[
    {
        "StackId": "arn:aws:cloudformation:us-east-1:123456789012:stack/myteststack/466df9e0-0dff-08e3-8e2f-5088487c4896",
        "TemplateDescription": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
        "StackStatusReason": null,
        "CreationTime": "2013-08-26T03:27:10.190Z",
        "StackName": "myteststack",
        "StackStatus": "CREATE_COMPLETE"
    }
]
```
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [ListStacks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/list-stacks.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：傳回所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary
```
**範例 2：傳回目前正在建立之所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary -StackStatusFilter "CREATE_IN_PROGRESS"
```
**範例 3：傳回目前正在建立或更新之所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary -StackStatusFilter @("CREATE_IN_PROGRESS", "UPDATE_IN_PROGRESS")
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [ListStacks](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：傳回所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary
```
**範例 2：傳回目前正在建立之所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary -StackStatusFilter "CREATE_IN_PROGRESS"
```
**範例 3：傳回目前正在建立或更新之所有堆疊的摘要資訊。**  

```
Get-CFNStackSummary -StackStatusFilter @("CREATE_IN_PROGRESS", "UPDATE_IN_PROGRESS")
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ListStacks](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `UpdateStack` 與 CLI
<a name="cloudformation_example_cloudformation_UpdateStack_section"></a>

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

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

**AWS CLI**  
**更新 AWS CloudFormation 堆疊**  
以下 `update-stack` 命令更新 `mystack` 堆疊的範本和輸入參數：  

```
aws cloudformation update-stack --stack-name mystack --template-url https://s3.amazonaws.com/sample/updated.template --parameters ParameterKey=KeyPairName,ParameterValue=SampleKeyPair ParameterKey=SubnetIDs,ParameterValue=SampleSubnetID1\\,SampleSubnetID2
```
以下 `update-stack` 命令僅更新 `mystack` 堆疊的 `SubnetIDs` 參數值。如果您未指定參數值，則會使用範本中所指定的預設值：  

```
aws cloudformation update-stack --stack-name mystack --template-url https://s3.amazonaws.com/sample/updated.template --parameters ParameterKey=KeyPairName,UsePreviousValue=true ParameterKey=SubnetIDs,ParameterValue=SampleSubnetID1\\,UpdatedSampleSubnetID2
```
以下 `update-stack` 命令會將兩個堆疊通知主題新增至 `mystack` 堆疊：  

```
aws cloudformation update-stack --stack-name mystack --use-previous-template --notification-arns "arn:aws:sns:use-east-1:123456789012:mytopic1" "arn:aws:sns:us-east-1:123456789012:mytopic2"
```
如需詳細資訊，請參閱《*AWS CloudFormation 使用者指南*》中的 [AWS CloudFormation 堆疊更新](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks.html)。  
+  如需 API 詳細資訊，請參閱《AWS CLI 命令參考》**中的 [UpdateStack](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/update-stack.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 代表範本中宣告的參數名稱，而 'PV1' 代表其值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 2：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**範例 3：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 代表範本中宣告的參數名稱，而 'PV2' 代表其值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" -TemplateBody "{Template Content Here}" -Parameters @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 4：使用從 Amazon S3 取得的指定範本和自訂參數來更新堆疊 'myStack'。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**範例 5：更新堆疊 'myStack'，在本範例中假設包含 IAM 資源，具有從 Amazon S3 取得的指定範本和自訂參數。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。包含 IAM 資源的堆疊需要指定 -Capabilities "CAPABILITY\$1IAM" 參數，否則更新會失敗，並顯示 'InsufficientCapabilities' 錯誤。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } ) `
                -Capabilities "CAPABILITY_IAM"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V4)》**中的 [UpdateStack](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 代表範本中宣告的參數名稱，而 'PV1' 代表其值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 2：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**範例 3：使用指定的範本和自訂參數更新堆疊 'myStack'。'PK1' 代表範本中宣告的參數名稱，而 'PV2' 代表其值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" -TemplateBody "{Template Content Here}" -Parameters @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**範例 4：使用從 Amazon S3 取得的指定範本和自訂參數來更新堆疊 'myStack'。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**範例 5：更新堆疊 'myStack'，在本範例中假設包含 IAM 資源，具有從 Amazon S3 取得的指定範本和自訂參數。'PK1' 和 'PK2' 代表範本中宣告的參數名稱，'PV1' 和 'PV2' 代表其請求的值。自訂參數也可以使用 'Key' 和 'Value' (而不是 'ParameterKey' 和 'ParameterValue') 來指定。包含 IAM 資源的堆疊需要指定 -Capabilities "CAPABILITY\$1IAM" 參數，否則更新會失敗，並顯示 'InsufficientCapabilities' 錯誤。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } ) `
                -Capabilities "CAPABILITY_IAM"
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# 搭配使用 `ValidateTemplate` 與 CLI
<a name="cloudformation_example_cloudformation_ValidateTemplate_section"></a>

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

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

**AWS CLI**  
**驗證 an AWS CloudFormation 範本**  
下列 `validate-template` 命令可驗證 `sampletemplate.json` 範本：  

```
aws cloudformation validate-template --template-body file://sampletemplate.json
```
輸出：  

```
{
    "Description": "AWS CloudFormation Sample Template S3_Bucket: Sample template showing how to create a publicly accessible S3 bucket. **WARNING** This template creates an S3 bucket. You will be billed for the AWS resources used if you create a stack from this template.",
    "Parameters": [],
    "Capabilities": []
}
```
如需詳細資訊，請參閱《 AWS CloudFormation *AWS 使用者指南》中的使用 CloudFormation *範本。  
+  如需 API 詳細資訊，請參閱《*AWS CLI 命令參考*》中的 [ValidateTemplate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/cloudformation/validate-template.html)。

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**範例 1：驗證指定的範本內容。輸出中詳細說明範本的功能、描述和參數。**  

```
Test-CFNTemplate -TemplateBody "{TEMPLATE CONTENT HERE}"
```
**範例 2：驗證透過 Amazon S3 URL 存取的指定範本。輸出中詳細說明範本的功能、描述和參數。**  

```
Test-CFNTemplate -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template
```
+  如需 API 詳細資訊，請參閱《*AWS Tools for PowerShell Cmdlet 參考 (V4)*》中的 [ValidateTemplate](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**範例 1：驗證指定的範本內容。輸出中詳細說明範本的功能、描述和參數。**  

```
Test-CFNTemplate -TemplateBody "{TEMPLATE CONTENT HERE}"
```
**範例 2：驗證透過 Amazon S3 URL 存取的指定範本。輸出中詳細說明範本的功能、描述和參數。**  

```
Test-CFNTemplate -TemplateURL https://s3.amazonaws.com/amzn-s3-demo-bucket/templatefile.template
```
+  如需 API 詳細資訊，請參閱《AWS Tools for PowerShell Cmdlet 參考 (V5)》**中的 [ValidateTemplate](https://docs.aws.amazon.com/powershell/v5/reference)。

------

# CloudFormation 使用 AWS SDKs案例
<a name="cloudformation_code_examples_scenarios"></a>

下列程式碼範例示範如何在 AWS SDKs中 CloudFormation 實作常見案例。這些案例說明如何透過在 內呼叫多個函數 CloudFormation 或與其他函數結合，來完成特定任務 AWS 服務。每個案例均包含完整原始碼的連結，您可在連結中找到如何設定和執行程式碼的相關指示。

案例的目標是獲得中等水平的經驗，協助您了解內容中的服務動作。

**Topics**
+ [建立 REST API 以追蹤 COVID-19 資料](cloudformation_example_cross_ApiGatewayDataTracker_section.md)

# 建立 API Gateway REST API 以追蹤 COVID-19 資料
<a name="cloudformation_example_cross_ApiGatewayDataTracker_section"></a>

以下程式碼範例示範如何建立 REST API，此 API 使用虛構資料模擬追蹤美國 COVID-19 每日病例的系統。

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

**適用於 Python 的 SDK (Boto3)**  
 示範如何使用 AWS Chalice 搭配 適用於 Python (Boto3) 的 AWS SDK 來建立使用 Amazon API Gateway AWS Lambda和 Amazon DynamoDB 的無伺服器 REST API。REST API 使用虛構資料模擬追蹤美國 COVID-19 每日病例的系統。了解如何：  
+ 使用 AWS Chalice 定義 Lambda 函數中的路由，這些函數稱為 來處理透過 API Gateway 發出的 REST 請求。
+ 使用 Lambda 函式在 DynamoDB 資料表中擷取和存放資料，以便為 REST 請求提供服務。
+ 在 AWS CloudFormation 範本中定義資料表結構和安全角色資源。
+ 使用 AWS Chalice 和 CloudFormation 封裝和部署所有必要的資源。
+ 使用 CloudFormation 清理所有已建立的資源。
 如需完整的原始碼和如何設定及執行的指示，請參閱 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/cross_service/apigateway_covid-19_tracker) 上的完整範例。  

**此範例中使用的服務**
+ API Gateway
+ CloudFormation
+ DynamoDB
+ Lambda

------