

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

# CloudFormation 範本 Resources 語法
<a name="resources-section-structure"></a>

`Resources` 區段是 CloudFormation 範本中所需的頂層區段。它會宣告您希望 CloudFormation 在堆疊中佈建和設定 AWS 的資源。

## 語法
<a name="resources-section-structure-syntax"></a>

`Resources` 區段使用下列語法：

### JSON
<a name="resources-section-structure-syntax.json"></a>

```
"Resources" : {
    "LogicalResourceName1" : {
        "Type" : "AWS::ServiceName::ResourceType",
        "Properties" : {
            "PropertyName1" : "PropertyValue1",
            ...
        }
    },

    "LogicalResourceName2" : {
        "Type" : "AWS::ServiceName::ResourceType",
        "Properties" : {
            "PropertyName1" : "PropertyValue1",
            ...
        }
    }
}
```

### YAML
<a name="resources-section-structure-syntax.yaml"></a>

```
Resources:
  LogicalResourceName1:
    Type: AWS::ServiceName::ResourceType
    Properties:
      PropertyName1: PropertyValue1
      ...

  LogicalResourceName2:
    Type: AWS::ServiceName::ResourceType
    Properties:
      PropertyName1: PropertyValue1
      ...
```

## 邏輯 ID (也稱為*邏輯名稱*)
<a name="resources-section-logical-id"></a>

在 CloudFormation 範本內，資源會以其邏輯資源名稱來識別。這些名稱必須是英數字元 (A-Za-z0-9)，而且在範本內必須是唯一的。邏輯名稱可用於參考範本其他區段的資源。

## Resource Type (資源類型)
<a name="resources-section-resource-type"></a>

每個資源必須有 `Type` 屬性，以定義該 AWS 資源的種類。`Type` 屬性擁有的格式為 `AWS::ServiceName::ResourceType`。例如，Amazon S3 儲存貯體的 `Type` 屬性為 `AWS::S3::Bucket`。

如需受支援資源類型的完整清單，請參閱 [AWS 資源和屬性類型參考](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-template-resource-type-ref.html)。

## 資源屬性
<a name="resources-section-resource-properties"></a>

資源屬性是您可指定的其他選項，用於定義特定資源類型的組態詳細資訊。有些屬性是必要的，有些則為選用。某些屬性具有預設值，因此指定這些屬性為選用。

如需每個資源類型所支援屬性的詳細資訊，請參閱《[AWS 資源和屬性類型參考》](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-template-resource-type-ref.html)中的主題。

屬性值可以是常值字串、字串清單、動態參考、布林值、參數參考、虛擬參考，或函數所傳回的值。下列範例顯示如何宣告不同的屬性值類型：

### JSON
<a name="resource-properties-example.json"></a>

```
"Properties" : {
    "String" : "A string value",
    "Number" : 123,
    "LiteralList" : [ "first-value", "second-value" ],
    "Boolean" : true
}
```

### YAML
<a name="resource-properties-example.yaml"></a>

```
Properties:
  String: A string value 
  Number: 123
  LiteralList:
    - first-value
    - second-value
  Boolean: true
```

## 實體 ID
<a name="resources-section-physical-id"></a>

除了邏輯 ID 之外，特定資源也會有實體 ID，這是該資源的實際指派名稱 (例如 EC2 執行個體 ID 或 S3 儲存貯體名稱)。使用實體 ID 來識別 CloudFormation 範本外部的資源，但只在建立資源之後。例如，假設您為 EC2 執行個體資源指定邏輯 ID `MyEC2Instance`。當 CloudFormation 建立執行個體時，CloudFormation 會自動產生並指派實體 ID (例如 `i-1234567890abcdef0`) 給執行個體。您可以使用此實體 ID 來識別執行個體，以及使用 Amazon EC2 主控台來檢視其屬性 (例如 DNS 名稱)。

對於 Amazon S3 儲存貯體及許多其他資源，若您未明確指定，CloudFormation 會自動為資源產生唯一的實體名稱。此實體名稱基於 CloudFormation 堆疊的名稱、CloudFormation 範本中指定的資源邏輯名稱，以及唯一 ID 的組合。例如，若您的 Amazon S3 儲存貯體在名為 `MyStack` 的堆疊中具有邏輯名稱 `MyBucket`，CloudFormation 可能會將儲存貯體命名為下列實體名稱 `MyStack-MyBucket-abcdefghijk1`。

針對支援自訂名稱的資源，您可以指派自己的實體名稱，協助您快速識別資源。例如，您可以將存放日誌的 S3 儲存貯體命名為 `MyPerformanceLogs`。如需詳細資訊，請參閱[名稱類型](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-properties-name.html)。

## 參考資源
<a name="using-cross-resource-references"></a>

您通常需要根據另一個資源的名稱或屬性，設定某個資源的屬性。例如，您可建立使用 EC2 安全群組的 EC2 執行個體，或 S3 儲存貯體支援的 CloudFront 分佈。所有這些資源都可在相同的 CloudFormation 範本中建立。

CloudFormation 提供內建函數，您可以用來參考其他資源及其屬性。這些函數可讓您在資源之間建立相依關係，並將值從一個資源傳遞到另一個資源。

### `Ref` 函數
<a name="resource-properties-ref"></a>

`Ref` 函數通常用於擷取相同 CloudFormation 範本中所定義資源的識別屬性。傳回的內容要取決於資源的類型。對於大多數資源，它會傳回資源的實體名稱。然而，對於某些資源類型，它可能會傳回不同的值，例如 `AWS::EC2::EIP` 資源的 IP 位址或 Amazon SNS 主題的 Amazon Resource Name (ARN)。

以下範例會示範屬性中 `Ref` 函數的使用方式。在每個範例中，`Ref` 函數會傳回範本中其他位置所宣告 `LogicalResourceName` 資源的實際名稱。YAML 範例中的 `!Ref` 語法範例只是撰寫 `Ref` 函數的較短方式。

#### JSON
<a name="resource-properties-ref-example.json"></a>

```
"Properties" : {
    "PropertyName" : { "Ref" : "LogicalResourceName" }
}
```

#### YAML
<a name="resource-properties-ref-example.yaml"></a>

```
Properties:
  PropertyName1:
    Ref: LogicalResourceName
  PropertyName2: !Ref LogicalResourceName
```

如需 `Ref` 函數的詳細資訊，請參閱 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-ref.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-ref.html)。

### `Fn::GetAtt` 函數
<a name="resource-properties-getatt"></a>

如果為資源傳回的參數或值完全是您想要的，`Ref` 函數會很有幫助。不過，您可能會需要資源的其他屬性。例如，如果您想要建立有 S3 來源的 CloudFront 分佈，您需要使用 DNS 樣式地址指定儲存貯體位置。多項有其他屬性的資源，其值可用於範本中。您可以使用 `Fn::GetAtt` 函數取得這些屬性。

以下範例會示範屬性中 `GetAtt` 函數的使用方式。`Fn::GetAtt` 函數需要兩個參數擷取資源邏輯名稱及屬性名稱。YAML 範例中的 `!GetAtt` 語法範例只是撰寫 `GetAtt` 函數的較短方式。

#### JSON
<a name="resource-properties-getatt-example.json"></a>

```
"Properties" : {
    "PropertyName" : {
        "Fn::GetAtt" : [ "LogicalResourceName", "AttributeName" ]
    }
}
```

#### YAML
<a name="resource-properties-getatt-example.yaml"></a>

```
Properties:
  PropertyName1:
    Fn::GetAtt:
      - LogicalResourceName
      - AttributeName
  PropertyName2: !GetAtt LogicalResourceName.AttributeName
```

如需 `GetAtt` 函數的詳細資訊，請參閱 [https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-getatt.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/intrinsic-function-reference-getatt.html)。

## 範例
<a name="resources-section-structure-examples"></a>

下列範例說明如何宣告資源，以及 CloudFormation 範本如何參考定義在相同範本中的其他資源，以及現有的 AWS 資源。

**Topics**
+ [宣告具有自訂名稱的單一資源](#resources-section-structure-examples-single-resource)
+ [使用 `Ref` 函數參考其他資源](#resources-section-structure-examples-ref)
+ [透過 `Fn::GetAtt` 函數參考資源屬性](#resources-section-structure-examples-getatt)

### 宣告具有自訂名稱的單一資源
<a name="resources-section-structure-examples-single-resource"></a>

以下範例會宣告邏輯名稱為 `MyBucket` 的 `AWS::S3::Bucket` 類型單一資源。`BucketName` 屬性設定為 *amzn-s3-demo-bucket*，您應以 S3 儲存貯體所需的名稱取代。

若您使用此資源宣告來建立堆疊，CloudFormation 將使用預設設定建立 Amazon S3 儲存貯體。至於 Amazon EC2 執行個體或 Auto Scaling 群組等其他資源，CloudFormation 需要更多資訊。

#### JSON
<a name="resources-section-structure-examples-single-resource.json"></a>

```
{
    "Resources": {
        "MyBucket": {
            "Type": "AWS::S3::Bucket",
            "Properties": {
                "BucketName": "amzn-s3-demo-bucket"
            }
        }
    }
}
```

#### YAML
<a name="resources-section-structure-examples-single-resource.yaml"></a>

```
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
    Properties:
      BucketName: amzn-s3-demo-bucket
```

### 使用 `Ref` 函數參考其他資源
<a name="resources-section-structure-examples-ref"></a>

下列範例顯示定義 EC2 執行個體與安全群組的資源宣告。`Ec2Instance` 資源會使用 `Ref` 函數參考 `InstanceSecurityGroup` 資源，做為其 `SecurityGroupIds` 屬性的一部分。它還包含了範本中未宣告的現有安全群組 (`sg-12a4c434`)。您要使用文字字串參考現有的 AWS 資源。

#### JSON
<a name="resources-section-structure-examples-ref.json"></a>

```
{
    "Resources": {
        "Ec2Instance": {
            "Type": "AWS::EC2::Instance",
            "Properties": {
                "SecurityGroupIds": [
                    {
                        "Ref": "InstanceSecurityGroup"
                    },
                    "sg-12a4c434"
                ],
                "KeyName": "MyKey",
                "ImageId": "ami-1234567890abcdef0"
            }
        },
        "InstanceSecurityGroup": {
            "Type": "AWS::EC2::SecurityGroup",
            "Properties": {
                "GroupDescription": "Enable SSH access via port 22",
                "SecurityGroupIngress": [
                    {
                        "IpProtocol": "tcp",
                        "FromPort": 22,
                        "ToPort": 22,
                        "CidrIp": "0.0.0.0/0"
                    }
                ]
            }
        }
    }
}
```

#### YAML
<a name="resources-section-structure-examples-ref.yaml"></a>

```
Resources:
  Ec2Instance:
    Type: AWS::EC2::Instance
    Properties:
      SecurityGroupIds:
        - !Ref InstanceSecurityGroup
        - sg-12a4c434
      KeyName: MyKey
      ImageId: ami-1234567890abcdef0
  InstanceSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Enable SSH access via port 22
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: 0.0.0.0/0
```

### 透過 `Fn::GetAtt` 函數參考資源屬性
<a name="resources-section-structure-examples-getatt"></a>

下列範例顯示定義 CloudFront 分佈資源及 S3 儲存貯體的資源宣告。`MyDistribution` 資源會使用 `Fn::GetAtt` 函數取得儲存貯體的 `DomainName` 屬性，以指定 `MyBucket` 資源的 DNS 名稱。您要通知 `Fn::GetAtt` 函數在陣列中列出它的兩個參數。對於需要多個參數的函數，您使用陣列指定它們的參數。

#### JSON
<a name="resources-section-structure-examples-getatt.json"></a>

```
{
  "Resources": {
    "MyBucket": {
      "Type": "AWS::S3::Bucket"
    },
    "MyDistribution": {
      "Type": "AWS::CloudFront::Distribution",
      "Properties": {
        "DistributionConfig": {
          "Origins": [
            {
              "DomainName": {
                "Fn::GetAtt": [
                  "MyBucket",
                  "DomainName"
                ]
              },
              "Id": "MyS3Origin",
              "S3OriginConfig": {}
            }
          ],
          "Enabled": "true",
          "DefaultCacheBehavior": {
            "TargetOriginId": "MyS3Origin",
            "ForwardedValues": {
              "QueryString": "false"
            },
            "ViewerProtocolPolicy": "allow-all"
          }
        }
      }
    }
  }
}
```

#### YAML
<a name="resources-section-structure-examples-getatt.yaml"></a>

```
Resources:
  MyBucket:
    Type: AWS::S3::Bucket
  MyDistribution:
    Type: AWS::CloudFront::Distribution
    Properties:
      DistributionConfig:
        Origins:
          - DomainName: !GetAtt 
              - MyBucket
              - DomainName
            Id: MyS3Origin
            S3OriginConfig: {}
        Enabled: 'true'
        DefaultCacheBehavior:
          TargetOriginId: MyS3Origin
          ForwardedValues:
            QueryString: 'false'
          ViewerProtocolPolicy: allow-all
```