

# 使用伪参数获取 AWS 值
<a name="pseudo-parameter-reference"></a>

伪参数是内置变量，用于提供对重要 AWS 环境信息的访问权限，例如可能因部署或环境的不同而发生变化的账户 ID、区域名称和堆栈详细信息等。

您可以使用伪参数代替硬编码值，以此确保模板更便于移植，更易于跨不同 AWS 账户和区域重复使用。

## 语法
<a name="pseudo-parameter-syntax"></a>

您可以使用 `Ref` 内置函数或 `Fn::Sub` 内部函数来引用伪参数。

### Ref
<a name="pseudo-parameter-ref-syntax"></a>

`Ref` 内置函数使用以下常规语法。有关更多信息，请参阅 [Ref](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-ref.html)。

#### JSON
<a name="pseudo-parameter-ref-syntax.json"></a>

```
{ "Ref" : "AWS::PseudoParameter" }
```

#### YAML
<a name="pseudo-parameter-ref-syntax.yaml"></a>

```
!Ref AWS::PseudoParameter
```

### Fn::Sub
<a name="pseudo-parameter-sub-syntax"></a>

`Fn::Sub` 内置函数使用不同的格式，其中包括伪参数周围的 `${}` 语法。有关更多信息，请参阅 [Fn::Sub](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-sub.html)。

#### JSON
<a name="pseudo-parameter-sub-syntax.json"></a>

```
{ "Fn::Sub" : "${AWS::PseudoParameter}" }
```

#### YAML
<a name="pseudo-parameter-sub-syntax.yaml"></a>

```
!Sub '${AWS::PseudoParameter}'
```

## 可用伪参数
<a name="available-pseudo-parameters"></a>

### `AWS::AccountId`
<a name="cfn-pseudo-param-accountid"></a>

返回在其中创建堆栈的账户的 AWS 账户 ID，如 `123456789012`。

此伪参数通常用于定义 IAM 角色、策略和其他涉及账户特定 ARN 的资源策略。

### `AWS::NotificationARNs`
<a name="cfn-pseudo-param-notificationarns"></a>

返回接收堆栈事件通知的 Amazon SNS 主题的 Amazon 资源名称（ARN）列表。在创建或更新堆栈时，您可以通过 AWS CLI 中的 `--notification-arns` 选项或通过控制台指定这些 ARN。

与返回单个值的其他伪参数不同，`AWS::NotificationARNs` 会返回 ARN 列表。要访问列表中的特定 ARN，使用 `Fn::Select` 内置函数。有关更多信息，请参阅 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-select.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-select.html)。

### `AWS::NoValue`
<a name="cfn-pseudo-param-novalue"></a>

如果在 `Fn::If` 内部函数中指定为返回值，则删除相应的资源属性。有关更多信息，请参阅 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-if](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-conditions.html#intrinsic-function-reference-conditions-if)。

如果需要创建只有在特定条件下才会被包含的条件资源属性，此伪参数特别有用。

### `AWS::Partition`
<a name="cfn-pseudo-param-partition"></a>

返回资源所处的分区。对于标准 AWS 区域，分区是 `aws`。对于位于其他分区中的资源，则分区是 `aws-`*partitionname*。例如，中国（北京和宁夏）区域中的资源的分区为 `aws-cn`，AWS GovCloud（US-West）区域中的资源的分区为 `aws-us-gov`。

分区是资源 ARN 的一部分。使用 `AWS::Partition` 可确保模板在不同的 AWS 分区中正常运行。

### `AWS::Region`
<a name="cfn-pseudo-param-region"></a>

返回代表在其中创建包容性资源的区域的字符串，如 `us-west-2`。

这是最常用的伪参数之一，因为它能让模板适应不同的 AWS 区域，无需另行修改。

### `AWS::StackId`
<a name="cfn-pseudo-param-stackid"></a>

返回堆栈 ID（ARN），例如 `arn:aws:cloudformation:us-west-2:123456789012:stack/teststack/51af3dc0-da77-11e4-872e-1234567db123`。

### `AWS::StackName`
<a name="cfn-pseudo-param-stackname"></a>

返回堆栈名称，例如 `teststack`。

堆栈名称通常用于创建唯一资源名称，方便轻松识别出相应堆栈。

### `AWS::URLSuffix`
<a name="cfn-pseudo-param-urlsuffix"></a>

返回堆栈部署所在的 AWS 区域中的 AWS 域后缀。后缀通常为 `amazonaws.com`，但中国（北京）区域的后缀为 `amazonaws.com.cn`。

在为 AWS 服务端点构建 URL 时，此参数特别有用。

## 示例
<a name="pseudo-parameter-examples"></a>

**Topics**
+ [基本用法](#pseudo-parameter-basic-example)
+ [使用 AWS::NotificationARNs](#pseudo-parameter-notification-example)
+ [AWS::NoValue 条件属性](#pseudo-parameter-novalue-example)

### 基本用法
<a name="pseudo-parameter-basic-example"></a>

以下示例创建了两个资源：一个 Amazon SNS 主题和一个向该主题发送通知的 CloudWatch 警报。它们使用 `AWS::StackName`、`AWS::Region` 和 `AWS::AccountId` 将堆栈名称、当前 AWS 区域和账户 ID 动态插入到资源名称、描述和 ARN 中。

#### JSON
<a name="pseudo-parameter-basic-example.json"></a>

```
{
    "Resources": {
        "MyNotificationTopic": {
            "Type": "AWS::SNS::Topic",
            "Properties": {
                "DisplayName": { "Fn::Sub": "Notifications for ${AWS::StackName}" }
            }
        },
        "CPUAlarm": {
            "Type": "AWS::CloudWatch::Alarm",
            "Properties": {
                "AlarmDescription": { "Fn::Sub": "Alarm for high CPU in ${AWS::Region}" },
                "AlarmName": { "Fn::Sub": "${AWS::StackName}-HighCPUAlarm" },
                "MetricName": "CPUUtilization",
                "Namespace": "AWS/EC2",
                "Statistic": "Average",
                "Period": 300,
                "EvaluationPeriods": 1,
                "Threshold": 80,
                "ComparisonOperator": "GreaterThanThreshold",
                "AlarmActions": [{ "Fn::Sub": "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:${MyNotificationTopic}" }]
            }
        }
    }
}
```

#### YAML
<a name="pseudo-parameter-basic-example.yaml"></a>

```
Resources:
  MyNotificationTopic:
    Type: AWS::SNS::Topic
    Properties:
      DisplayName: !Sub Notifications for ${AWS::StackName}
  CPUAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: !Sub Alarm for high CPU in ${AWS::Region}
      AlarmName: !Sub ${AWS::StackName}-HighCPUAlarm
      MetricName: CPUUtilization
      Namespace: AWS/EC2
      Statistic: Average
      Period: 300
      EvaluationPeriods: 1
      Threshold: 80
      ComparisonOperator: GreaterThanThreshold
      AlarmActions:
        - !Sub arn:aws:sns:${AWS::Region}:${AWS::AccountId}:${MyNotificationTopic}
```

### 使用 AWS::NotificationARNs
<a name="pseudo-parameter-notification-example"></a>

以下示例配置了一个自动扩缩组来发送有关实例启动事件和启动错误的通知。该配置使用 `AWS::NotificationARNs` 伪参数，提供堆栈创建期间指定的 Amazon SNS 主题 ARN 的列表。`Fn::Select` 函数会从该列表中选择第一个 ARN。

#### JSON
<a name="pseudo-parameter-notification-example.json"></a>

```
"myASG": {
   "Type": "AWS::AutoScaling::AutoScalingGroup",
   "Properties": {
      "LaunchTemplate": {
         "LaunchTemplateId": { "Ref": "myLaunchTemplate" },
         "Version": { "Fn::GetAtt": [ "myLaunchTemplate", "LatestVersionNumber" ] }
       },
       "MaxSize": "1",
       "MinSize": "1",
       "VPCZoneIdentifier": [
          "subnetIdAz1",
          "subnetIdAz2",
          "subnetIdAz3"
      ],
      "NotificationConfigurations" : [{
         "TopicARN" : { "Fn::Select" : [ "0", { "Ref" : "AWS::NotificationARNs" } ] },
         "NotificationTypes" : [ "autoscaling:EC2_INSTANCE_LAUNCH", "autoscaling:EC2_INSTANCE_LAUNCH_ERROR" ]
      }]
   }
}
```

#### YAML
<a name="pseudo-parameter-notification-example.yaml"></a>

```
myASG:
  Type: AWS::AutoScaling::AutoScalingGroup
  Properties:
    LaunchTemplate:
      LaunchTemplateId: !Ref myLaunchTemplate
      Version: !GetAtt myLaunchTemplate.LatestVersionNumber
    MinSize: '1'
    MaxSize: '1'
    VPCZoneIdentifier:
      - subnetIdAz1
      - subnetIdAz2
      - subnetIdAz3
    NotificationConfigurations:
      - TopicARN:
          Fn::Select:
          - '0'
          - Ref: AWS::NotificationARNs
        NotificationTypes:
        - autoscaling:EC2_INSTANCE_LAUNCH
        - autoscaling:EC2_INSTANCE_LAUNCH_ERROR
```

### AWS::NoValue 条件属性
<a name="pseudo-parameter-novalue-example"></a>

以下示例创建了一个 Amazon RDS 数据库实例，仅当提供了快照 ID 时，该数据库实例才会使用快照。如果 `UseDBSnapshot` 条件计算为 true，则 CloudFormation 对 `DBSnapshotIdentifier` 属性使用 `DBSnapshotName` 参数值。如果条件计算为 false，则 CloudFormation 删除 `DBSnapshotIdentifier` 属性。

#### JSON
<a name="pseudo-parameter-novalue-example.json"></a>

```
"MyDB" : {
  "Type" : "AWS::RDS::DBInstance",
  "Properties" : {
    "AllocatedStorage" : "5",
    "DBInstanceClass" : "db.t2.small",
    "Engine" : "MySQL",
    "EngineVersion" : "5.5",
    "MasterUsername" : { "Ref" : "DBUser" },
    "MasterUserPassword" : { "Ref" : "DBPassword" },
    "DBParameterGroupName" : { "Ref" : "MyRDSParamGroup" },
    "DBSnapshotIdentifier" : {
      "Fn::If" : [
        "UseDBSnapshot",
        {"Ref" : "DBSnapshotName"},
        {"Ref" : "AWS::NoValue"}
      ]
    }
  }
}
```

#### YAML
<a name="pseudo-parameter-novalue-example.yaml"></a>

```
MyDB:
  Type: AWS::RDS::DBInstance
  Properties:
    AllocatedStorage: '5'
    DBInstanceClass: db.t2.small
    Engine: MySQL
    EngineVersion: '5.5'
    MasterUsername:
      Ref: DBUser
    MasterUserPassword:
      Ref: DBPassword
    DBParameterGroupName:
      Ref: MyRDSParamGroup
    DBSnapshotIdentifier:
      Fn::If:
        - UseDBSnapshot
        - Ref: DBSnapshotName
        - Ref: AWS::NoValue
```