

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用的代码示 CloudFormation 例 AWS SDKs
<a name="cloudformation_code_examples"></a>

以下代码示例向您展示了如何 AWS CloudFormation 使用 AWS 软件开发套件 (SDK)。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

*场景*是向您展示如何通过在一个服务中调用多个函数或与其他 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>

以下代码示例说明如何使用 with 的基础 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>

以下代码示例演示了如何使用执行单个 CloudFormation 操作 AWS SDKs。每个示例都包含一个指向的链接 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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：取消指定堆栈的更新。**  

```
Stop-CFNUpdateStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [CancelUpdateStack](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：取消指定堆栈的更新。**  

```
Stop-CFNUpdateStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：继续指定堆栈的回滚，该堆栈的状态应为“UPDATE\$1ROLLBACK\$1FAILED”。如果继续回滚成功，堆栈将进入“UPDATE\$1ROLLBACK\$1COMPLETE”状态。**  

```
Resume-CFNUpdateRollback -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [ContinueUpdateRollback](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：继续指定堆栈的回滚，该堆栈的状态应为“UPDATE\$1ROLLBACK\$1FAILED”。如果继续回滚成功，堆栈将进入“UPDATE\$1ROLLBACK\$1COMPLETE”状态。**  

```
Resume-CFNUpdateRollback -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：使用指定名称创建新堆栈。模板是从提供的内容中解析出来的，带有自定义参数（PK1'PK2' 和 '' 代表模板内容中声明的参数的名称，PV1'和' PV2 '代表这些参数的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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 '代表这些参数的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用指定名称创建新堆栈。该模板是从带有自定义参数的 Amazon S3 URL 中获取的（PK1“” 表示模板内容中声明的参数的名称，PV1“” 表示参数的值。 也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用指定名称创建新堆栈。该模板是从带有自定义参数的 Amazon S3 URL 中获取的（PK1“” 表示模板内容中声明的参数的名称，PV1“” 表示参数的值。 也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。 如果堆栈创建失败，则会将其回滚（与指定相同-DisableRollback \$1false）。指定的通知 AENs 将收到已发布的堆栈相关事件。**  

```
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 参考 (V* 4) [CreateStack](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：使用指定名称创建新堆栈。模板是从提供的内容中解析出来的，带有自定义参数（PK1'PK2' 和 '' 代表模板内容中声明的参数的名称，PV1'和' PV2 '代表这些参数的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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 '代表这些参数的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用指定名称创建新堆栈。该模板是从带有自定义参数的 Amazon S3 URL 中获取的（PK1“” 表示模板内容中声明的参数的名称，PV1“” 表示参数的值。 也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用指定名称创建新堆栈。该模板是从带有自定义参数的 Amazon S3 URL 中获取的（PK1“” 表示模板内容中声明的参数的名称，PV1“” 表示参数的值。 也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。 如果堆栈创建失败，则会将其回滚（与指定相同-DisableRollback \$1false）。指定的通知 AENs 将收到已发布的堆栈相关事件。**  

```
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 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：删除指定的堆栈。**  

```
Remove-CFNStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DeleteStack](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：删除指定的堆栈。**  

```
Remove-CFNStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回指定堆栈的所有堆栈相关事件。**  

```
Get-CFNStackEvent -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeStackEvents](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回指定堆栈的所有堆栈相关事件。**  

```
Get-CFNStackEvent -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回模板中以逻辑 ID DBInstance “我的” 标识的与指定堆栈关联的资源的描述。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeStackResource](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回模板中以逻辑 ID DBInstance “我的” 标识的与指定堆栈关联的资源的描述。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回与指定堆栈关联的多达 100 个资源的 AWS 资源描述。要获取与堆栈关联的所有资源的详细信息，请使用 Get-CFNStackResourceSummary，它还支持手动分页结果。**  

```
Get-CFNStackResourceList -StackName "myStack"
```
**示例 2：返回与指定堆栈关联的模板中用逻辑 ID “Ec2Instance”标识的 Amazon EC2 实例的描述。**  

```
Get-CFNStackResourceList -StackName "myStack" -LogicalResourceId "Ec2Instance"
```
**示例 3：对于包含用实例 ID “i-123456”标识的 Amazon EC2 实例的堆栈，返回与该堆栈关联的最多 100 个资源的描述。要获取与堆栈关联的所有资源的详细信息，请使用 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 参考 (V* 4) [DescribeStackResources](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回与指定堆栈关联的多达 100 个资源的 AWS 资源描述。要获取与堆栈关联的所有资源的详细信息，请使用 Get-CFNStackResourceSummary，它还支持手动分页结果。**  

```
Get-CFNStackResourceList -StackName "myStack"
```
**示例 2：返回与指定堆栈关联的模板中用逻辑 ID “Ec2Instance”标识的 Amazon EC2 实例的描述。**  

```
Get-CFNStackResourceList -StackName "myStack" -LogicalResourceId "Ec2Instance"
```
**示例 3：对于包含用实例 ID “i-123456”标识的 Amazon EC2 实例的堆栈，返回与该堆栈关联的最多 100 个资源的描述。要获取与堆栈关联的所有资源的详细信息，请使用 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 参考 (V* 5) [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 ]

**适用于 Go 的 SDK 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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回描述用户的所有堆栈的堆栈实例集合。**  

```
Get-CFNStack
```
**示例 2：返回描述指定堆栈的堆栈实例**  

```
Get-CFNStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [DescribeStacks](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回描述用户的所有堆栈的堆栈实例集合。**  

```
Get-CFNStack
```
**示例 2：返回描述指定堆栈的堆栈实例**  

```
Get-CFNStack -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回一个带有查询字符串的 AWS 简单月度计算器网址，该字符串描述了运行模板所需的资源。模板是从指定的 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 简单月度结算器网址，该字符串描述了运行模板所需的资源。模板是根据提供的内容和应用的自定义参数进行解析的（此示例假设模板内容会声明两个参数，'和KeyName' InstanceType '）。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" `
                        -Parameter @( @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" },`
                                      @{ ParameterKey="InstanceType"; ParameterValue="m1.large" })
```
**示例 3：使用 New-Object 生成模板参数集，并返回一个 “ AWS 简单月度计算器” 网址，其中包含描述运行模板所需资源的查询字符串。模板是从提供的内容中解析出来的，并带有自定义参数（此示例假设模板内容会声明两个参数，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 参考 (V* 4) [EstimateTemplateCost](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回一个带有查询字符串的 AWS 简单月度计算器网址，该字符串描述了运行模板所需的资源。模板是从指定的 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 简单月度结算器网址，该字符串描述了运行模板所需的资源。模板是根据提供的内容和应用的自定义参数进行解析的（此示例假设模板内容会声明两个参数，'和KeyName' InstanceType '）。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Measure-CFNTemplateCost -TemplateBody "{TEMPLATE CONTENT HERE}" `
                        -Parameter @( @{ ParameterKey="KeyName"; ParameterValue="myKeyPairName" },`
                                      @{ ParameterKey="InstanceType"; ParameterValue="m1.large" })
```
**示例 3：使用 New-Object 生成模板参数集，并返回一个 “ AWS 简单月度计算器” 网址，其中包含描述运行模板所需资源的查询字符串。模板是从提供的内容中解析出来的，并带有自定义参数（此示例假设模板内容会声明两个参数，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 参考 (V* 5) [EstimateTemplateCost](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

# 将 `GetTemplate` 与 CLI 配合使用
<a name="cloudformation_example_cloudformation_GetTemplate_section"></a>

以下代码示例演示如何使用 `GetTemplate`。

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

**AWS CLI**  
**查看 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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回与指定堆栈关联的模板。**  

```
Get-CFNTemplate -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [GetTemplate](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回与指定堆栈关联的模板。**  

```
Get-CFNTemplate -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：返回与指定堆栈关联的所有资源的描述。**  

```
Get-CFNStackResourceSummary -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 4) [ListStackResources](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：返回与指定堆栈关联的所有资源的描述。**  

```
Get-CFNStackResourceSummary -StackName "myStack"
```
+  有关 API 的详细信息，请参阅 *AWS Tools for PowerShell Cmdlet 参考 (V* 5) [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 ]

**适用于 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 参考 (V* 4) [ListStacks](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 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 参考 (V* 5) [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 ]

**适用于 PowerShell V4 的工具**  
**示例 1：使用指定的模板和自定义参数更新堆栈 “MyStack”。 'PK1' 表示模板中声明的参数的名称，而 'PV1' 表示其值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**示例 2：使用指定的模板和自定义参数更新堆栈 “MyStack”。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**示例 3：使用指定的模板和自定义参数更新堆栈 “MyStack”。 'PK1' 表示模板中声明的参数的名称，而 'PV2' 表示其值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" -TemplateBody "{Template Content Here}" -Parameters @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**示例 4：使用从 Amazon S3 获得的指定模板和自定义参数更新堆栈 “MyStack”。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用从 Amazon S3 获取的指定模板和自定义参数更新堆栈 “MyStack”（在本示例中假设该堆栈包含 IAM 资源）。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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 参考 (V* 4) [UpdateStack](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 PowerShell V5 的工具**  
**示例 1：使用指定的模板和自定义参数更新堆栈 “MyStack”。 'PK1' 表示模板中声明的参数的名称，而 'PV1' 表示其值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**示例 2：使用指定的模板和自定义参数更新堆栈 “MyStack”。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" `
                -TemplateBody "{Template Content Here}" `
                -Parameter @( @{ ParameterKey="PK1"; ParameterValue="PV1" }, @{ ParameterKey="PK2"; ParameterValue="PV2" } )
```
**示例 3：使用指定的模板和自定义参数更新堆栈 “MyStack”。 'PK1' 表示模板中声明的参数的名称，而 'PV2' 表示其值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “ParameterKey” 和 “ParameterValue”。**  

```
Update-CFNStack -StackName "myStack" -TemplateBody "{Template Content Here}" -Parameters @{ ParameterKey="PK1"; ParameterValue="PV1" }
```
**示例 4：使用从 Amazon S3 获得的指定模板和自定义参数更新堆栈 “MyStack”。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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：使用从 Amazon S3 获取的指定模板和自定义参数更新堆栈 “MyStack”（在本示例中假设该堆栈包含 IAM 资源）。 PK1'和' PK2 '表示模板中声明的参数的名称，' 和 PV1 'PV2' 代表其请求的值。也可以使用 “密钥” 和 “值” 来指定自定义参数，而不是 “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 参考 (V* 5) [UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

# 将 `ValidateTemplate` 与 CLI 配合使用
<a name="cloudformation_example_cloudformation_ValidateTemplate_section"></a>

以下代码示例演示如何使用 `ValidateTemplate`。

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

**AWS CLI**  
**验证 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 ]

**适用于 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 参考 (V* 4) [ValidateTemplate](https://docs.aws.amazon.com/powershell/v4/reference)中的。

**适用于 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 参考 (V* 5) [ValidateTemplate](https://docs.aws.amazon.com/powershell/v5/reference)中的。

------

# CloudFormation 使用场景 AWS SDKs
<a name="cloudformation_code_examples_scenarios"></a>

以下代码示例向您展示了如何在中 CloudFormation 实现常见场景 AWS SDKs。这些场景向您展示了如何通过在其中调用多个函数 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 来创建使用亚马逊 API Gateway 和 Amazon DynamoDB 的无服务器 REST API。 AWS Lambda REST API 模拟一个使用虚构数据跟踪美国每日 COVID-19 病例的系统。了解如何：  
+ 使用 AWS Chalice 在 Lambda 函数中定义路由，这些函数用于处理通过 API Gateway 发出的 REST 请求。
+ 使用 Lambda 函数在 DynamoDB 表中检索数据并存储数据以处理 REST 请求。
+ 在 AWS CloudFormation 模板中定义表结构和安全角色资源。
+ 使用 AWS Chalice and 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

------