

# AWS CLI 和 PowerShell 的 CloudFormation 堆栈操作命令示例
<a name="service_code_examples"></a>

以下命令行示例演示了如何使用 AWS CLI 和 PowerShell 执行各个 CloudFormation 操作。这些示例仅包括最常用的操作。有关完整列表，请参阅*《AWS CLI 命令参考》*中的 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/)。

本指南中的示例使用反斜杠 (\$1) 的惯例来表示长命令行在下一行继续。

**Topics**
+ [取消堆栈更新](#cancel-update-stack-sdk)
+ [继续回滚更新](#continue-update-rollback-sdk)
+ [创建堆栈](#create-stack-sdk)
+ [创建包含转换的堆栈](#deploy-sdk)
+ [删除堆栈](#delete-stack-sdk)
+ [描述堆栈事件](#describe-stack-events-sdk)
+ [描述堆栈资源](#describe-stack-resource-sdk)
+ [描述堆栈资源](#describe-stack-resources-sdk)
+ [描述堆栈](#describe-stacks-sdk)
+ [获取模板](#get-template-sdk)
+ [列出堆栈资源](#list-stack-resources-sdk)
+ [列出堆栈](#list-stacks-sdk)
+ [更新堆栈](#update-stack-sdk)
+ [验证模板](#validate-template-sdk)
+ [使用 AWS CLI 将本地构件上传到 S3 存储桶](using-cfn-cli-package.md)

## 取消堆栈更新
<a name="cancel-update-stack-sdk"></a>

[https://docs.aws.amazon.com/cli/latest/reference/cloudformation/cancel-update-stack.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/cancel-update-stack.html) 命令用于取消堆栈更新。有关更多信息，请参阅 [取消堆栈更新](using-cfn-stack-update-cancel.md)。

------
#### [ 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 Reference（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 Reference（V5）》中的 [CancelUpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)**。

------

## 继续回滚更新
<a name="continue-update-rollback-sdk"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/continue-update-rollback.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/continue-update-rollback.html) 命令继续回滚更新。有关更多信息，请参阅 [继续回滚更新](using-cfn-updating-stacks-continueupdaterollback.md)。

------
#### [ 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 Reference（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 Reference（V5）》中的 [ContinueUpdateRollback](https://docs.aws.amazon.com/powershell/v5/reference)**。

------

## 创建堆栈
<a name="create-stack-sdk"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html) 命令创建堆栈。您必须提供堆栈名称、有效模板的位置和所有输入参数。参数键名称区分大小写。如果您输入错误的参数键名称，则 CloudFormation 不会创建堆栈，并且会报告模板不包含该参数。

以下示例演示了如何使用指定的名称、模板和输入参数创建新堆栈。

------
#### [ 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 时相同）。指定的通知 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 Reference（V4）》**中的 [CreateStack](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for 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 时相同）。指定的通知 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 Reference（V5）》**中的 [CreateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

------

**注意**  
您可以使用 AWS CLI `--template-url` 选项在 Amazon S3 或 AWS Systems Manager 中指定模板文件位置。  
对于 Amazon S3，URL 必须以 `https://` 开头。不支持 S3 静态网站 URL。  

```
--template-url https://s3.region-code.amazonaws.com/bucket-name/template-name
```
对于 AWS Systems Manager，请使用以下格式：  

```
--template-url "ssm-doc://arn:aws:ssm:region-code:account-id:document/document-name"
```

## 创建包含转换的堆栈
<a name="deploy-sdk"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/) 命令创建包含转换的堆栈。使用模板创建包含转换的堆栈时，您必须使用更改集。`deploy` 命令将两个步骤（创建更改集和执行变更集）合并为一个命令。

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

以下 `deploy` 命令将使用指定的名称、模板和输入参数创建一个堆栈。

```
aws cloudformation deploy --stack-name myteststack \
  --template /path_to_template/my-template.json \
  --parameter-overrides Key1=Value1 Key2=Value2
```

------

## 删除堆栈
<a name="delete-stack-sdk"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/delete-stack.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/delete-stack.html) 命令删除堆栈。有关更多信息，请参阅 [删除堆栈](cfn-console-delete-stack.md)。

------
#### [ 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 Reference（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 Reference（V5）》**中的 [DeleteStack](https://docs.aws.amazon.com/powershell/v5/reference)。

------

如果删除失败并返回 `DELETE_FAILED` 状态，可以选择使用 `--deletion-mode` 选项强制删除堆栈。以下是可以与 `deletion-mode` 一起使用的值：
+ `STANDARD`：正常删除堆栈。这是默认删除模式。
+ `FORCE_DELETE_STACK`：删除堆栈并跳过所有无法删除的资源。

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

以下 `delete-stack` 命令将 `FORCE_DELETE_STACK` 值与 `deletion-mode` 参数结合使用，强制删除 `myteststack` 堆栈：

```
aws cloudformation delete-stack --stack-name myteststack \
    --deletion-mode FORCE_DELETE_STACK
```

此命令不生成任何输出。

------

使用 `FORCE_DELETE_STACK` 后，您可以使用 `list-stack-resources` 命令列出在堆栈删除过程中跳过的资源。保留的资源将显示为 DELETE\$1SKIPPED 状态。有关更多信息，请参阅 [列出堆栈资源](#list-stack-resources-sdk)。

## 描述堆栈事件
<a name="describe-stack-events-sdk"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-events.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/describe-stack-events.html) 命令描述堆栈事件。有关更多信息，请参阅 [监控堆栈进度](monitor-stack-progress.md)。

------
#### [ 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 Reference（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 Reference（V5）》中的 [DescribeStackEvents](https://docs.aws.amazon.com/powershell/v5/reference)**。

------

## 描述堆栈资源
<a name="describe-stack-resource-sdk"></a>

------
#### [ 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 “MyDBInstance”标识的资源的描述。**  

```
Get-CFNStackResource -StackName "myStack" -LogicalResourceId "MyDBInstance"
```
+  有关 API 详细信息，请参阅《AWS Tools for PowerShell Cmdlet Reference（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 Reference（V5）》中的 [DescribeStackResource](https://docs.aws.amazon.com/powershell/v5/reference)**。

------

## 描述堆栈资源
<a name="describe-stack-resources-sdk"></a>

------
#### [ 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 Reference（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：对于包含用实例 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 Reference（V5）》中的 [DescribeStackResources](https://docs.aws.amazon.com/powershell/v5/reference)**。

------

## 描述堆栈
<a name="describe-stacks-sdk"></a>

------
#### [ 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 Reference》中的 [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 Reference（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 Reference（V5）》中的 [DescribeStacks](https://docs.aws.amazon.com/powershell/v5/reference)**。

------

默认情况下，`describe-stacks` 命令返回参数值。为了防止返回密码等敏感参数值，请在 CloudFormation 模板中包含一个设置为 `TRUE` 的 `NoEcho` 属性。

**重要**  
使用 `NoEcho` 属性不会遮蔽在以下各区段中存储的任何信息：  
`Metadata` 模板区段。CloudFormation 不会转换、修改或编辑您在 `Metadata` 部分中包含的任何信息。有关更多信息，请参阅 [Metadata](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html)。
`Outputs` 模板区段。有关更多信息，请参阅 [Outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html)。
资源定义的 `Metadata` 属性。有关更多信息，请参阅 [`Metadata` 属性](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-attribute-metadata.html)。
强烈建议您不要使用这些机制来包含敏感信息，例如密码。

**重要**  
我们建议不要将敏感信息直接嵌入 CloudFormation 模板中，而应使用堆栈模板中的动态参数来引用在 CloudFormation 外部存储和管理的敏感信息，例如 AWS Systems Manager Parameter Store 或 AWS Secrets Manager 中的敏感信息。  
有关更多信息，请参阅[请勿将凭证嵌入您的模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/security-best-practices.html#creds)最佳实践。

## 获取模板
<a name="get-template-sdk"></a>

------
#### [ 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 Reference（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 Reference（V5）》中的 [GetTemplate](https://docs.aws.amazon.com/powershell/v5/reference)**。

------

## 列出堆栈资源
<a name="list-stack-resources-sdk"></a>

------
#### [ 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 Reference（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 Reference（V5）》**中的 [ListStackResources](https://docs.aws.amazon.com/powershell/v5/reference)。

------

## 列出堆栈
<a name="list-stacks-sdk"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stacks.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/list-stacks.html) 命令列出堆栈。要只列出具有指定状态代码的堆栈，请添加 `--stack-status-filter` 选项。可以为 `--stack-status-filter` 选项指定一个或多个堆栈状态代码。有关更多信息，请参阅 [堆栈状态代码](view-stack-events.md#cfn-console-view-stack-data-resources-status-codes)。

------
#### [ 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 Reference（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 Reference（V5）》**中的 [ListStacks](https://docs.aws.amazon.com/powershell/v5/reference)。

------

## 更新堆栈
<a name="update-stack-sdk"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/update-stack.html) 命令可直接更新堆栈。您指定要更新的堆栈、参数值和功能，如果您希望使用更新后的模板，还需指定模板的名称。有关更多信息，请参阅 [直接更新堆栈](using-cfn-updating-stacks-direct.md)。

------
#### [ 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 堆栈更新](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 Reference（V4）》**中的 [UpdateStack](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for 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 Reference（V5）》**中的 [UpdateStack](https://docs.aws.amazon.com/powershell/v5/reference)。

------

**注意**  
要移除所有通知，请为 `--notification-arns` 选项指定 `[]`。

## 验证模板
<a name="validate-template-sdk"></a>

使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/validate-template.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/validate-template.html) 命令检查模板文件的语法错误。

在验证期间，CloudFormation 首先检查模板是否是有效的 JSON。如果不是，CloudFormation 会检查模板是否是有效的 YAML。如果两种检查都失败，CloudFormation 会返回模板验证错误。

------
#### [ 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 CloudTrail 用户指南》中的“使用 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 Reference（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 Reference（V5）》中的 [ValidateTemplate](https://docs.aws.amazon.com/powershell/v5/reference)**。

------

以下是产生验证错误的响应示例。

```
{
    "ResponseMetadata": {
        "RequestId": "4ae33ec0-1988-11e3-818b-e15a6df955cd"
    },
    "Errors": [
        {
            "Message": "Template format error: JSON not well-formed. (line 11, column 8)",
            "Code": "ValidationError",
            "Type": "Sender"
        }
    ],
    "Capabilities": [],
    "Parameters": []
}
A client error (ValidationError) occurred: Template format error: JSON not well-formed. (line 11, column 8)
```

**注意**  
`validate-template` 命令仅用于检查模板的语法。它不能确保您为资源指定的属性值对该资源有效，也无法确定创建堆栈时将存在的资源数量。  
要检查操作有效性，需要尝试创建堆栈。CloudFormation 堆栈没有沙盒或测试区域，因此您需要为测试期间创建的资源付费。

**示例可用性**  
找不到所需的内容？ 通过使用本页底部的**提供反馈**链接来请求代码示例。

# 使用 AWS CLI 将本地构件上传到 S3 存储桶
<a name="using-cfn-cli-package"></a>

现在，您可以使用 AWS CLI 命令将 CloudFormation 模板引用的本地构件上传到 Amazon S3 存储桶。本地构件是您在模板中引用的文件。您可以在模板中指定本地构件，然后使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html) 命令快速上传它们，而不是将文件手动上传到 S3 存储桶，然后向模板添加其位置。

本地项目是 **package** 命令将向 Amazon S3 上传的文件或文件夹的路径。例如，构件可以是 AWS Lambda 函数的源代码或 Amazon API Gateway REST API 的 OpenAPI 文件的本地路径。

使用 **package** 命令时：
+ 如果您指定一个文件，此命令会将该文件直接上传到 S3 存储桶。
+ 如果您指定一个文件夹，则命令将为该文件夹创建一个 `.zip` 文件，然后上传该 `.zip` 文件。
+ 如果您未指定路径，则命令将为工作目录创建一个 `.zip` 文件，然后上传该文件。

您可指定绝对路径或相对路径，其中相对路径相对于模板的位置。

在上传项目之后，此命令将返回模板的副本，并将对本地项目的引用替换为命令已将项目上传到的 S3 位置。然后，您可使用返回的模板创建或更新堆栈。

**注意**  
您只能对 **package** 命令支持的资源属性使用本地项目。有关此命令的更多信息和支持的资源属性的列表，请参阅 [AWS CLI 命令参考](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/index.html)中的 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html) 文档。



## 先决条件
<a name="using-cfn-cli-package-prerequisites"></a>

在开始之前，您必须有一个现有的 Amazon S3 存储桶。

## 打包并部署包含本地构件的模板
<a name="package-and-deploy-a-template-with-local-artifacts"></a>

以下模板指定 Lambda 函数的源代码的本地项目。此源代码存储在 `/home/user/code/lambdafunction` 文件夹中。

**原始模板**

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::Serverless-2016-10-31",
  "Resources": {
    "MyFunction": {
      "Type": "AWS::Serverless::Function",
      "Properties": {
        "Handler": "index.handler",
        "Runtime": "nodejs18.x",
        "CodeUri": "/home/user/code/lambdafunction"
      }
    }
  }
}
```

以下 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/package.html) 命令创建函数源代码文件夹的 `.zip` 文件，然后将该文件上传到指定存储桶的根目录。

```
aws cloudformation package \
  --s3-bucket amzn-s3-demo-bucket \
  --template /path_to_template/template.json \
  --output-template-file packaged-template.json \
  --output json
```

该命令在 `--output-template-file` 指定的路径上生成一个新模板。它将构件引用替换为 Amazon S3 位置，如下图所示。`.zip` 文件是使用文件夹内容的 MD5 校验和命名的，而不是使用文件夹名称本身。

**结果模板**

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::Serverless-2016-10-31",
  "Resources": {
    "MyFunction": {
      "Type": "AWS::Serverless::Function",
      "Properties": {
        "Handler": "index.handler",
        "Runtime": "nodejs18.x",
        "CodeUri": "s3://amzn-s3-demo-bucket/md5 checksum"
      }
    }
  }
}
```

打包模板的构件后，使用 [https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/deploy/) 命令部署已处理的模板。

```
aws cloudformation deploy \
  --template-file packaged-template.json \
  --stack-name stack-name
```

部署大于 51200 字节的模板时，使用带有 `--s3-bucket` 选项的 **deploy** 命令将模板上传到 S3，如下例所示。

```
aws cloudformation deploy \
  --template-file packaged-template.json \
  --stack-name stack-name \
  --s3-bucket amzn-s3-demo-bucket
```

**注意**  
有关使用 **package** 命令上传本地构件的另一个示例，请参阅[使用嵌套堆栈将模板拆分为可重复使用的部分](using-cfn-nested-stacks.md)。