

# 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～Z、a～z、0～9) でなければならず、テンプレート内で一意である必要があります。論理名は、テンプレートの他のセクションのリソースを参照するために使用されます。

## リソースタイプ
<a name="resources-section-resource-type"></a>

リソースには、AWS リソースの種類を定義する `Type` 属性が必要です。`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 バケット名など)。CloudFormation テンプレートに記載していないリソースを識別するには物理 ID を使用しますが、リソースの作成後にのみ使用できます。たとえば、EC2 インスタンスリソースに `MyEC2Instance` の論理 ID を指定します。CloudFormation は、インスタンスを作成すると、自動的に物理 ID (`i-1234567890abcdef0`) を生成してインスタンスに割り当てます。この物理 ID を使用して、Amazon EC2 コンソールでインスタンスを特定したり、そのプロパティ (DNS 名など) を表示したりすることができます。

Amazon S3 バケットをはじめとする各種リソースに明示的に物理名を指定していない場合は、CloudFormation が一意の物理名を自動的に生成します。CloudFormation スタックの名前、CloudFormation テンプレートに指定されているリソースの論理名、一意の ID を組み合わせた物理名です。例えば、`MyStack` というスタックに論理名が `MyBucket` の Amazon S3 バケットがある場合、そのバケットに物理名 `MyStack-MyBucket-abcdefghijk1` を含む名前を付けます。

カスタム名をサポートしているリソースの場合は、リソースを迅速に識別するために、独自の物理名を割り当てることができます。たとえば、ログを保存する S3 バケットに `MyPerformanceLogs` という名前を指定できます。詳細については、「[Name タイプ](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>

同じ CloudFormation テンプレート内に定義されたリソースを識別できるプロパティを取得するには、`Ref` 関数を一般的に使用します。返される内容は、リソースのタイプによって異なります。ほとんどのリソースの場合、リソースの物理名が返されます。ただし、リソースタイプによっては、`AWS::EC2::EIP` リソースの IP アドレスや Amazon SNS トピックの Amazon リソースネーム (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` 関数は、2 つのパラメーターを受け取ります。1 つはリソースの論理名、もう 1 つは取得する属性の名前です。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` タイプの 1 のリソースが宣言されます。`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` 関数を使用して、`SecurityGroupIds` プロパティの一部として `InstanceSecurityGroup` リソースを参照します。また、テンプレートで宣言されていない既存のセキュリティグループ (`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` リソースは、バケットの `DomainName` 属性を取得するための `Fn::GetAtt` 関数を使用して、`MyBucket` リソースの DNS 名を指定します。`Fn::GetAtt` 関数では、2 つのパラメーターが配列として指定されています。複数のパラメーターを受け取る関数に対しては、配列を使用してパラメーターを指定します。

#### 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
```