

# 通用模板代码段
<a name="quickref-general"></a>

以下示例介绍了并非特定于某个 AWS 服务的不同 CloudFormation 模板功能。

**Topics**
+ [Base64 编码的 UserData 属性](#scenario-userdata-base64)
+ [使用 Base64 编码的 UserData 属性，具有 AccessKey 和 SecretKey](#scenario-userdata-base64-with-keys)
+ [含一个文字字符串参数的 Parameters 部分](#scenario-one-string-parameter)
+ [含有带正则表达式约束的字符串参数的 Parameters 部分](#scenario-constraint-string-parameter)
+ [含有数字参数的 Parameters 部分，带有 MinValue 和 MaxValue 约束](#scenario-one-number-min-parameter)
+ [含有数字参数的 Parameters 部分，带有 AllowedValues 约束](#scenario-one-number-parameter)
+ [含一个文字 CommaDelimitedList 参数的 Parameters 部分](#scenario-one-list-parameter)
+ [包含基于伪参数的参数值的 Parameters 部分](#scenario-one-pseudo-parameter)
+ [带有三个映射的 Mapping 部分](#scenario-mapping-with-four-maps)
+ [基于文字字符串的 Description](#scenario-description-from-literal-string)
+ [带有一个文件字符串输出的 Outputs 部分](#scenario-output-with-literal-string)
+ [包含一个资源引用和一个伪参数输出的 Outputs 部分](#scenario-output-with-ref-and-pseudo-ref)
+ [包含一个基于函数的输出、一个文字字符串、一个引用和一个伪参数的 Outputs 部分](#scenario-output-with-complex-spec)
+ [模板格式版本](#scenario-format-version)
+ [AWS Tags 属性](#scenario-format-aws-tag)

## Base64 编码的 UserData 属性
<a name="scenario-userdata-base64"></a>

此示例演示了使用 `Fn::Base64` 和 `Fn::Join` 函数的 `UserData` 属性集合。引用 `MyValue` 和 `MyName` 是必须要在模板的 `Parameters` 部分定义的参数。文字字符串 `Hello World` 只是此示例传输作为 `UserData` 的一部分的另一个值。

### JSON
<a name="quickref-general-example-1.json"></a>

```
1. "UserData" : {
2.     "Fn::Base64" : {
3.         "Fn::Join" : [ ",", [
4.             { "Ref" : "MyValue" },
5.             { "Ref" : "MyName" },
6.             "Hello World" ] ]
7.     }
8. }
```

### YAML
<a name="quickref-general-example-1.yaml"></a>

```
1. UserData:
2.   Fn::Base64: !Sub |
3.      Ref: MyValue
4.      Ref: MyName
5.      Hello World
```

## 使用 Base64 编码的 UserData 属性，具有 AccessKey 和 SecretKey
<a name="scenario-userdata-base64-with-keys"></a>

此示例演示了使用 `Fn::Base64` 和 `Fn::Join` 函数的 `UserData` 属性集合。它包含 `AccessKey` 和 `SecretKey` 信息。参考 `AccessKey` 和 `SecretKey` 是必须要在模板的 Parameters 部分中定义的参数。

### JSON
<a name="quickref-general-example-2.json"></a>

```
1. "UserData" : {
2.     "Fn::Base64" : {
3.         "Fn::Join" : [ "", [
4.             "ACCESS_KEY=", { "Ref" : "AccessKey" },
5.             "SECRET_KEY=", { "Ref" : "SecretKey" } ]
6.         ]
7.     }
8. }
```

### YAML
<a name="quickref-general-example-2.yaml"></a>

```
1. UserData:
2.   Fn::Base64: !Sub |
3.      ACCESS_KEY=${AccessKey}
4.      SECRET_KEY=${SecretKey}
```

## 含一个文字字符串参数的 Parameters 部分
<a name="scenario-one-string-parameter"></a>

以下示例描述了有效的 Parameters 部分声明，其中声明有单个 `String` 类型参数。

### JSON
<a name="quickref-general-example-3.json"></a>

```
1. "Parameters" : {
2.     "UserName" : {
3.         "Type" : "String",
4.         "Default" : "nonadmin",
5.         "Description" : "Assume a vanilla user if no command-line spec provided"
6.     }
7. }
```

### YAML
<a name="quickref-general-example-3.yaml"></a>

```
1. Parameters:
2.   UserName:
3.     Type: String
4.     Default: nonadmin
5.     Description: Assume a vanilla user if no command-line spec provided
```

## 含有带正则表达式约束的字符串参数的 Parameters 部分
<a name="scenario-constraint-string-parameter"></a>

以下示例描述了有效的 Parameters 部分声明，其中声明有单个 `String` 类型参数。`AdminUserAccount` 参数的默认值为 `admin`。参数值的最小长度必须为 1，最大长度必须为 16，且其中包含字母字符和数字，但必须以字母字符开头。

### JSON
<a name="quickref-general-example-4.json"></a>

```
 1. "Parameters" : {
 2.     "AdminUserAccount": {
 3.       "Default": "admin",
 4.       "NoEcho": "true",
 5.       "Description" : "The admin account user name",
 6.       "Type": "String",
 7.       "MinLength": "1",
 8.       "MaxLength": "16",
 9.       "AllowedPattern" : "[a-zA-Z][a-zA-Z0-9]*"
10.     }
11. }
```

### YAML
<a name="quickref-general-example-4.yaml"></a>

```
1. Parameters:
2.   AdminUserAccount:
3.     Default: admin
4.     NoEcho: true
5.     Description: The admin account user name
6.     Type: String
7.     MinLength: 1
8.     MaxLength: 16
9.     AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*'
```

## 含有数字参数的 Parameters 部分，带有 MinValue 和 MaxValue 约束
<a name="scenario-one-number-min-parameter"></a>

以下示例描述了有效的 Parameters 部分声明，其中声明有单个 `Number` 类型参数。`WebServerPort` 参数的默认值为 80，最小值为 1，最大值为 65535。

### JSON
<a name="quickref-general-example-5.json"></a>

```
1. "Parameters" : {
2.     "WebServerPort": {
3.       "Default": "80",
4.       "Description" : "TCP/IP port for the web server",
5.       "Type": "Number",
6.       "MinValue": "1",
7.       "MaxValue": "65535"
8.     }
9. }
```

### YAML
<a name="quickref-general-example-5.yaml"></a>

```
1. Parameters:
2.   WebServerPort:
3.     Default: 80
4.     Description: TCP/IP port for the web server
5.     Type: Number
6.     MinValue: 1
7.     MaxValue: 65535
```

## 含有数字参数的 Parameters 部分，带有 AllowedValues 约束
<a name="scenario-one-number-parameter"></a>

以下示例描述了有效的 Parameters 部分声明，其中声明有单个 `Number` 类型参数。`WebServerPort` 参数的默认值为 80，且只允许值 80 和 8888。

### JSON
<a name="quickref-general-example-6.json"></a>

```
1. "Parameters" : {
2.     "WebServerPortLimited": {
3.       "Default": "80",
4.       "Description" : "TCP/IP port for the web server",
5.       "Type": "Number",
6.       "AllowedValues" : ["80", "8888"]
7.     }
8. }
```

### YAML
<a name="quickref-general-example-6.yaml"></a>

```
1. Parameters:
2.   WebServerPortLimited:
3.     Default: 80
4.     Description: TCP/IP port for the web server
5.     Type: Number
6.     AllowedValues:
7.     - 80
8.     - 8888
```

## 含一个文字 CommaDelimitedList 参数的 Parameters 部分
<a name="scenario-one-list-parameter"></a>

以下示例描述了有效的 `Parameters` 部分声明，其中声明了单个 `CommaDelimitedList` 类型参数。`NoEcho` 属性设置为 `TRUE`，该属性将使用 **describe-stacks** 输出中的星号（\$1\$1\$1\$1\$1）掩盖其值，但存储在下面指定位置的信息除外。

**重要**  
使用 `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)最佳实践。

### JSON
<a name="quickref-general-example-7.json"></a>

```
1. "Parameters" : {
2.     "UserRoles" : {
3.         "Type" : "CommaDelimitedList",
4.         "Default" : "guest,newhire",
5.         "NoEcho" : "TRUE"
6.     }
7. }
```

### YAML
<a name="quickref-general-example-7.yaml"></a>

```
1. Parameters:
2.   UserRoles:
3.     Type: CommaDelimitedList
4.     Default: "guest,newhire"
5.     NoEcho: true
```

## 包含基于伪参数的参数值的 Parameters 部分
<a name="scenario-one-pseudo-parameter"></a>

以下示例说明 EC2 用户数据中使用伪参数 `AWS::StackName` 和 `AWS::Region` 的命令。有关伪参数的更多信息，请参阅[使用伪参数获取 AWS 值](pseudo-parameter-reference.md)。

### JSON
<a name="quickref-general-example-10.json"></a>

```
 1.           "UserData"       : { "Fn::Base64" : { "Fn::Join" : ["", [
 2.              "#!/bin/bash -xe\n",
 3.              "yum install -y aws-cfn-bootstrap\n",
 4. 
 5.              "/opt/aws/bin/cfn-init -v ",
 6.              "         --stack ", { "Ref" : "AWS::StackName" },
 7.              "         --resource LaunchConfig ",
 8.              "         --region ", { "Ref" : "AWS::Region" }, "\n",
 9. 
10.              "/opt/aws/bin/cfn-signal -e $? ",
11.              "         --stack ", { "Ref" : "AWS::StackName" },
12.              "         --resource WebServerGroup ",
13.              "         --region ", { "Ref" : "AWS::Region" }, "\n"
14.         ]]}}
15.       }
```

### YAML
<a name="quickref-general-example-10.yaml"></a>

```
1. UserData:
2.   Fn::Base64: !Sub |
3.      #!/bin/bash -xe
4.      yum update -y aws-cfn-bootstrap
5.      /opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource LaunchConfig --region ${AWS::Region}
6.      /opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServerGroup --region ${AWS::Region}
```

## 带有三个映射的 Mapping 部分
<a name="scenario-mapping-with-four-maps"></a>

以下示例描述了其中包含三个映射的有效 `Mapping` 部分声明。映射在与 `Stop`、`SlowDown` 或 `Go` 映射密钥匹配时提供分配至相应 `RGBColor` 属性的 RGB 值。

### JSON
<a name="quickref-general-example-11.json"></a>

```
 1. "Mappings" : {
 2.     "LightColor" : {
 3.         "Stop" : {
 4.             "Description" : "red",
 5.             "RGBColor" : "RED 255 GREEN 0 BLUE 0"
 6.         },
 7.         "SlowDown" : {
 8.             "Description" : "yellow",
 9.             "RGBColor" : "RED 255 GREEN 255 BLUE 0"
10.         },
11.         "Go" : {
12.             "Description" : "green",
13.             "RGBColor" : "RED 0 GREEN 128 BLUE 0"
14.         }
15.     }
16. }
```

### YAML
<a name="quickref-general-example-11.yaml"></a>

```
 1. Mappings:
 2.   LightColor:
 3.     Stop:
 4.       Description: red
 5.       RGBColor: "RED 255 GREEN 0 BLUE 0"
 6.     SlowDown:
 7.       Description: yellow
 8.       RGBColor: "RED 255 GREEN 255 BLUE 0"
 9.     Go:
10.       Description: green
11.       RGBColor: "RED 0 GREEN 128 BLUE 0"
```

## 基于文字字符串的 Description
<a name="scenario-description-from-literal-string"></a>

以下示例描述了有效的 `Description` 部分声明，其中的值基于文字字符串。此代码段可用于模板、参数、资源、属性或输出。

### JSON
<a name="quickref-general-example-8.json"></a>

```
1. "Description" : "Replace this value"
```

### YAML
<a name="quickref-general-example-8.yaml"></a>

```
1. Description: "Replace this value"
```

## 带有一个文件字符串输出的 Outputs 部分
<a name="scenario-output-with-literal-string"></a>

此示例显示的是基于文字字符串的输出分配。

### JSON
<a name="quickref-general-example-12.json"></a>

```
1. "Outputs" : {
2.     "MyPhone" : {
3.         "Value" : "Please call 555-5555",
4.         "Description" : "A random message for aws cloudformation describe-stacks"
5.     }
6. }
```

### YAML
<a name="quickref-general-example-12.yaml"></a>

```
1. Outputs:
2.   MyPhone:
3.     Value: Please call 555-5555
4.     Description: A random message for aws cloudformation describe-stacks
```

## 包含一个资源引用和一个伪参数输出的 Outputs 部分
<a name="scenario-output-with-ref-and-pseudo-ref"></a>

此示例显示的是含有两个输出分配的 `Outputs` 部分。一个基于资源，另一个基于伪引用。

### JSON
<a name="quickref-general-example-13.json"></a>

```
1. "Outputs" : {
2.    "SNSTopic" : { "Value" : { "Ref" : "MyNotificationTopic" } },
3.    "StackName" : { "Value" : { "Ref" : "AWS::StackName" } }
4. }
```

### YAML
<a name="quickref-general-example-13.yaml"></a>

```
1. Outputs:
2.   SNSTopic:
3.     Value: !Ref MyNotificationTopic
4.   StackName:
5.     Value: !Ref AWS::StackName
```

## 包含一个基于函数的输出、一个文字字符串、一个引用和一个伪参数的 Outputs 部分
<a name="scenario-output-with-complex-spec"></a>

此示例显示的是带有一个输出分配的输出部分。Join 函数用于连接值，将百分比符号用作分隔符。

### JSON
<a name="quickref-general-example-14.json"></a>

```
1. "Outputs" : {
2.     "MyOutput" : {
3.         "Value" : { "Fn::Join" :
4.             [ "%", [ "A-string", {"Ref" : "AWS::StackName" } ] ]
5.         }
6.     }
7. }
```

### YAML
<a name="quickref-general-example-14.yaml"></a>

```
1. Outputs:
2.   MyOutput:
3.     Value: !Join [ %, [ 'A-string', !Ref 'AWS::StackName' ]]
```

## 模板格式版本
<a name="scenario-format-version"></a>

以下代码段描述了有效的 `AWSTemplateFormatVersion` 部分声明。

### JSON
<a name="quickref-general-example-9.json"></a>

```
1. "AWSTemplateFormatVersion" : "2010-09-09"
```

### YAML
<a name="quickref-general-example-9.yaml"></a>

```
1. AWSTemplateFormatVersion: '2010-09-09'
```

## AWS Tags 属性
<a name="scenario-format-aws-tag"></a>

本示例将展示 AWS `Tags` 属性。您将在资源的 Properties 部分中执行该属性。资源被创建后，会标上您声明的标签。

### JSON
<a name="quickref-general-example-15.json"></a>

```
 1. "Tags" : [
 2.       {
 3.         "Key" : "keyname1",
 4.         "Value" : "value1"
 5.       },
 6.       {
 7.         "Key" : "keyname2",
 8.         "Value" : "value2"
 9.       }
10.     ]
```

### YAML
<a name="quickref-general-example-15.yaml"></a>

```
1. Tags: 
2.   - 
3.     Key: "keyname1"
4.     Value: "value1"
5.   - 
6.     Key: "keyname2"
7.     Value: "value2"
```