

Questa è la nuova *Guida di riferimento ai modelli CloudFormation *. Aggiorna i segnalibri e i link. Per informazioni su come iniziare CloudFormation, consulta la [Guida AWS CloudFormation per l'utente](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html).

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

# `Fn::ForEach`
<a name="intrinsic-function-reference-foreach"></a>

La funzione intrinseca `Fn::ForEach` prende una raccolta e un frammento e applica gli elementi della raccolta all’identificatore nel frammento fornito. `Fn::ForEach` può contenere altre funzioni intrinseche, inclusa `Fn::ForEach` stessa, ed essere utilizzata nelle sezioni `Conditions`, `Outputs` e `Resources` (incluse le proprietà delle risorse). Non può essere utilizzata in nessuna delle seguenti sezioni: `AWSTemplateFormatVersion`, `Description`, `Metadata`, `Transform`, `Parameters`, `Mappings`, `Rules` o `Hooks`.

Se utilizzi la funzione intrinseca `Fn::ForEach` nel modello, devi anche utilizzare [Trasformazione `AWS::LanguageExtensions`](transform-aws-languageextensions.md).

L’utilizzo della funzione intrinseca `Fn::ForEach` non modifica le quote, che si applicano al modello risultante. Le quote includono la dimensione massima di un modello e il numero massimo di risorse in un modello. Per ulteriori informazioni, consulta [Comprendere le CloudFormation quote](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html) nella *Guida per l'AWS CloudFormation utente*.

## Dichiarazione
<a name="intrinsic-function-reference-foreach-declaration"></a>

### JSON
<a name="intrinsic-function-reference-foreach-declaration.json"></a>

```
"Fn::ForEach::LoopLogicalName": [
  "Identifier",
  ["Value1","Value2"], // Collection
  {"OutputKey": {OutputValue}}
]
```

### YAML
<a name="intrinsic-function-reference-foreach-declaration.yaml"></a>

```
'Fn::ForEach::LoopLogicalName':
    - Identifier
    - - Value1 # Collection
      - Value2
    - 'OutputKey':
        OutputValue
```

## Parameters
<a name="intrinsic-function-reference-foreach-parameters"></a>

*Nome logico del loop*  
Un ID logico per il loop. Il nome deve essere univoco all’interno del modello e non può essere in conflitto con alcun valore di ID logico nella sezione `Resources` del modello. Questo nome non è presente nell’output trasformato. Viene utilizzato come riferimento interno all'interno del CloudFormation modello stesso.

*Identificatore*  
Un identificatore per il segnaposto che viene sostituito nei parametri `OutputKey` e `OutputValue`. Tutte le istanze di `${Identifier}` o `&{Identifier}` nei parametri `OutputKey` e `OutputValue` verranno sostituite con i valori del parametro `Collection`.

*Raccolta*  
La raccolta di valori su cui iterare. Può essere una matrice in questo parametro oppure può essere un [`Ref`](intrinsic-function-reference-ref.md) su un `CommaDelimitedList`. Quando utilizzi `&{Identifier}`, è possibile che i caratteri non alfanumerici vengano trasferiti in `Collection`.

*Chiave di output*  
La chiave nel modello trasformato `${Identifier}` o `&{Identifier}` deve essere inclusa nel parametro `OutputKey`. Ad esempio, se `Fn::ForEach` viene utilizzato nella sezione `Resources` del modello, questo è l’ID logico di ogni risorsa.  
La sintassi `&{}` consente l’utilizzo dei caratteri non alfanumerici di `Collection` nel parametro `OutputKey`. Per un esempio, consulta [Passare caratteri non alfanumerici all’interno di `Collection` per `Fn::ForEach`](intrinsic-function-reference-foreach-example-resource.md#intrinsic-function-reference-foreach-example-non-alphanumeric).

*Valore di output*  
Il valore che viene replicato nel modello trasformato per ogni elemento del parametro `Collection`. Ad esempio, se `Fn::ForEach` viene utilizzato nella sezione `Resources` del modello, questo è il frammento del modello che viene ripetuto per configurare ogni risorsa.

## Valore restituito
<a name="intrinsic-function-reference-foreach-return-value"></a>

Un oggetto espanso che contiene il frammento dell’oggetto ripetuto una volta per ogni elemento della raccolta, in cui l’identificatore nel frammento viene sostituito con l’elemento della raccolta.

## Funzioni supportate
<a name="intrinsic-function-reference-foreach-nested-functions"></a>

È possibile utilizzare le funzioni seguenti in una funzione `Fn::ForEach`.
+ Funzioni di condizione:
  + [`Fn::And`](intrinsic-function-reference-conditions.md#intrinsic-function-reference-conditions-and)
  + [`Fn::Equals`](intrinsic-function-reference-conditions.md#intrinsic-function-reference-conditions-equals)
  + [`Fn::If`](intrinsic-function-reference-conditions.md#intrinsic-function-reference-conditions-if)
  + [`Fn::Not`](intrinsic-function-reference-conditions.md#intrinsic-function-reference-conditions-not)
  + [`Fn::Or`](intrinsic-function-reference-conditions.md#intrinsic-function-reference-conditions-or)
+ [`Fn::Base64`](intrinsic-function-reference-base64.md)
+ [`Fn::FindInMap`](intrinsic-function-reference-findinmap.md)
+ [`Fn::GetAtt`](intrinsic-function-reference-getatt.md)
+ [`Fn::GetAZs`](intrinsic-function-reference-getavailabilityzones.md)
+ [`Fn::ImportValue`](intrinsic-function-reference-importvalue.md)
+ [`Fn::Join`](intrinsic-function-reference-join.md)
+ [`Fn::Length`](intrinsic-function-reference-length.md)
+ [`Fn::Transform`](intrinsic-function-reference-transform.md)
+ [`Fn::Select`](intrinsic-function-reference-select.md)
+ [`Fn::Sub`](intrinsic-function-reference-sub.md)
+ [`Fn::ToJsonString`](intrinsic-function-reference-ToJsonString.md)
+ [`Ref`](intrinsic-function-reference-ref.md)

## Esempi
<a name="intrinsic-function-reference-foreach-example-pointer"></a>

Puoi trovare esempi delle sezioni `Conditions`, `Outputs` e `Resources` in [Esempi](intrinsic-function-reference-foreach-examples.md).

# Esempi
<a name="intrinsic-function-reference-foreach-examples"></a>

**Topics**
+ [Esempi di `Fn::ForEach` nella sezione `Resources`](intrinsic-function-reference-foreach-example-resource.md)
+ [Esempi di `Fn::ForEach` nella sezione `Outputs`](intrinsic-function-reference-foreach-example-outputs.md)
+ [Esempi di `Fn::ForEach` nella sezione `Conditions`](intrinsic-function-reference-foreach-example-conditions.md)

# Esempi di `Fn::ForEach` nella sezione `Resources`
<a name="intrinsic-function-reference-foreach-example-resource"></a>

Questi esempi dimostrano l’utilizzo della funzione intrinseca `Fn::ForEach` nella sezione `Resources`. Per ulteriori informazioni su questa sezione, consulta [Resources](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resources-section-structure.html) nella *Guida per l’utente di AWS CloudFormation *.

**Topics**
+ [Replica di una risorsa Amazon SNS](#intrinsic-function-reference-foreach-example-replicate-resource)
+ [Replica di una risorsa Amazon DynamoDB](#intrinsic-function-reference-foreach-example-replicate-ddb-resource)
+ [Replica di risorse multiple](#intrinsic-function-reference-foreach-example-replicate-multiple-resources)
+ [Replica di più risorse utilizzando loop `Fn::ForEach` nidificati](#intrinsic-function-reference-foreach-example-nested-loop-resources)
+ [Proprietà replicate di riferimento per una risorsa Amazon EC2](#intrinsic-function-reference-foreach-example-reference-replicated-resource)
+ [Proprietà replicate per una risorsa Amazon EC2](#intrinsic-function-reference-foreach-example-replicate-resource-properties)
+ [Passare caratteri non alfanumerici all’interno di `Collection` per `Fn::ForEach`](#intrinsic-function-reference-foreach-example-non-alphanumeric)

## Replica di una risorsa Amazon SNS
<a name="intrinsic-function-reference-foreach-example-replicate-resource"></a>

Questo frammento di esempio restituisce un elenco di quattro argomenti di Amazon SNS, con l’ID logico corrispondente agli elementi della raccolta (`Success`, `Failure`, `Timeout`, `Unknown`), con un `TopicName` e `FifoTopic` corrispondenti impostati su `true`.

**Nota**  
Per i modelli che devono funzionare sia con argomenti FIFO che con argomenti standard, puoi utilizzare la proprietà `DisplayName` invece di `TopicName`. Ciò consente di CloudFormation generare automaticamente i nomi degli argomenti con il `.fifo` suffisso appropriato quando `FifoTopic` è`true`. Basta sostituire `TopicName` con `DisplayName: !Ref TopicName` nella sezione `Properties`.

### JSON
<a name="intrinsic-function-reference-foreach-example-replicate-resource.json"></a>

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Transform": "AWS::LanguageExtensions",
    "Resources": {
        "Fn::ForEach::Topics": [
            "TopicName",
            ["Success", "Failure", "Timeout", "Unknown"],
            {
                "SnsTopic${TopicName}": {
                    "Type": "AWS::SNS::Topic",
                    "Properties": {
                        "TopicName": {"Fn::Sub": "${TopicName}.fifo"},
                        "FifoTopic": true
                    }
                }
            }
        ]
    }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-replicate-resource.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  'Fn::ForEach::Topics':
    - TopicName
    - [Success, Failure, Timeout, Unknown]
    - 'SnsTopic${TopicName}':
        Type: AWS::SNS::Topic
        Properties:
          TopicName: !Sub '${TopicName}.fifo'
          FifoTopic: true
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Resources:
  SnsTopicSuccess:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: Success.fifo
      FifoTopic: true
  SnsTopicFailure:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: Failure.fifo
      FifoTopic: true
  SnsTopicTimeout:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: Timeout.fifo
      FifoTopic: true
  SnsTopicUnknown:
    Type: AWS::SNS::Topic
    Properties:
      TopicName: Unknown.fifo
      FifoTopic: true
```

## Replica di una risorsa Amazon DynamoDB
<a name="intrinsic-function-reference-foreach-example-replicate-ddb-resource"></a>

Questo frammento di esempio crea quattro risorse [AWS::DynamoDB::Table](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-dynamodb-table.html) con nomi come `Points`, `Score` e così via.

### JSON
<a name="intrinsic-function-reference-foreach-example-replicate-ddb-resource.json"></a>

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Transform": "AWS::LanguageExtensions",
    "Resources": {
        "Fn::ForEach::Tables": [
            "TableName",
            ["Points", "Score", "Name", "Leaderboard"],
            {
                "DynamoDB${TableName}": {
                    "Type": "AWS::DynamoDB::Table",
                    "Properties": {
                        "TableName": {
                            "Ref": "TableName"
                        },
                        "AttributeDefinitions": [
                            {
                                "AttributeName": "id",
                                "AttributeType": "S"
                            }
                        ],
                        "KeySchema": [
                            {
                                "AttributeName": "id",
                                "KeyType": "HASH"
                            }
                        ],
                        "ProvisionedThroughput": {
                            "ReadCapacityUnits": "5",
                            "WriteCapacityUnits": "5"
                        }
                    }
                }
            }
        ]
    }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-replicate-ddb-resource.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  'Fn::ForEach::Tables':
    - TableName
    - [Points, Score, Name, Leaderboard]
    - 'DynamoDB${TableName}':
        Type: AWS::DynamoDB::Table
        Properties:
          TableName: !Ref TableName
          AttributeDefinitions:
            - AttributeName: id
              AttributeType: S
          KeySchema:
            - AttributeName: id
              KeyType: HASH
          ProvisionedThroughput:
            ReadCapacityUnits: '5'
            WriteCapacityUnits: '5'
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  DynamoDBPoints:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: Points
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: '5'
        WriteCapacityUnits: '5'
  DynamoDBScore:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: Score
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: '5'
        WriteCapacityUnits: '5'
  DynamoDBName:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: Name
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: '5'
        WriteCapacityUnits: '5'
  DynamoDBLeaderboard:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: Leaderboard
      AttributeDefinitions:
        - AttributeName: id
          AttributeType: S
      KeySchema:
        - AttributeName: id
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: '5'
        WriteCapacityUnits: '5'
```

## Replica di risorse multiple
<a name="intrinsic-function-reference-foreach-example-replicate-multiple-resources"></a>

Questo esempio crea più istanze di [AWS::EC2::NatGateway](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-natgateway.html)e [AWS: :EC2: :EIP](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-eip.html) utilizzando una convenzione di denominazione di. `"{ResourceType}${Identifier}"` È possibile dichiarare più tipi di risorse in un unico loop `Fn::ForEach` in modo da sfruttare un singolo identificatore.

I valori univoci per ogni elemento della raccolta sono definiti nella sezione `Mappings`, in cui la funzione intrinseca [`Fn::FindInMap`](intrinsic-function-reference-findinmap.md) viene utilizzata per fare riferimento al valore corrispondente. Se `Fn::FindInMap` non è in grado di trovare l’identificatore corrispondente, la proprietà `Condition` non verrà impostata su `!Ref AWS:::NoValue`.

### JSON
<a name="intrinsic-function-reference-foreach-example-replicate-multiple-resources.json"></a>

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::LanguageExtensions",
  "Conditions": {
    "TwoNatGateways": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-east-1"]},
    "ThreeNatGateways": {"Fn::Equals": [{"Ref": "AWS::Region"}, "us-west-2"]}
  },
  "Mappings": {
    "NatGateway": {
      "Condition": {
        "B": "TwoNatGateways",
        "C": "ThreeNatGateways"
      }
    }
  },
  "Resources": {
    "VPC": {
      "Type": "AWS::EC2::VPC",
      "Properties": {"CidrBlock": "10.0.0.0/16"}
    },
    "PublicSubnetA": {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "VpcId": {"Ref": "VPC"},
        "CidrBlock": "10.0.1.0/24",
        "AvailabilityZone": {"Fn::Select": [0, {"Fn::GetAZs": ""}]}
      }
    },
    "PublicSubnetB": {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "VpcId": {"Ref": "VPC"},
        "CidrBlock": "10.0.2.0/24",
        "AvailabilityZone": {"Fn::Select": [1, {"Fn::GetAZs": ""}]}
      }
    },
    "PublicSubnetC": {
      "Type": "AWS::EC2::Subnet",
      "Properties": {
        "VpcId": {"Ref": "VPC"},
        "CidrBlock": "10.0.3.0/24",
        "AvailabilityZone": {"Fn::Select": [2, {"Fn::GetAZs": ""}]}
      }
    },
    "Fn::ForEach::NatGatewayAndEIP": [
      "Identifier",
      [ "A", "B", "C" ],
      {
        "NatGateway${Identifier}": {
          "Type": "AWS::EC2::NatGateway",
          "Properties": {
            "AllocationId": {"Fn::GetAtt": [{"Fn::Sub": "NatGatewayAttachment${Identifier}"}, "AllocationId"]},
            "SubnetId": {"Ref": {"Fn::Sub": "PublicSubnet${Identifier}"}}
          },
          "Condition": {"Fn::FindInMap": ["NatGateway", "Condition", {"Ref": "Identifier"}, {"DefaultValue": {"Ref": "AWS::NoValue"}}]}
        },
        "NatGatewayAttachment${Identifier}": {
          "Type": "AWS::EC2::EIP",
          "Properties": {
            "Domain": "vpc"
          },
          "Condition": {"Fn::FindInMap": ["NatGateway", "Condition", {"Ref": "Identifier"}, {"DefaultValue": {"Ref": "AWS::NoValue"}}]}
        }
      }
    ]
  }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-replicate-multiple-resources.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Conditions:
  TwoNatGateways: !Equals [!Ref "AWS::Region", "us-east-1"]
  ThreeNatGateways: !Equals [!Ref "AWS::Region", "us-west-2"]
Mappings:
  NatGateway:
    Condition:
      B: TwoNatGateways
      C: ThreeNatGateways
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
  PublicSubnetA:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.1.0/24
      AvailabilityZone: !Select [0, !GetAZs ""]
  PublicSubnetB:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.2.0/24
      AvailabilityZone: !Select [1, !GetAZs ""]
  PublicSubnetC:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.3.0/24
      AvailabilityZone: !Select [2, !GetAZs ""]
  Fn::ForEach::NatGatewayAndEIP:
    - Identifier
    - - A
      - B
      - C
    - NatGateway${Identifier}:
        Type: AWS::EC2::NatGateway
        Properties:
          AllocationId: !GetAtt
            - !Sub NatGatewayAttachment${Identifier}
            - AllocationId
          SubnetId: !Ref
            Fn::Sub: PublicSubnet${Identifier}
        Condition: !FindInMap
          - NatGateway
          - Condition
          - !Ref Identifier
          - DefaultValue: !Ref AWS::NoValue
      NatGatewayAttachment${Identifier}:
        Type: AWS::EC2::EIP
        Properties:
          Domain: vpc
        Condition: !FindInMap
          - NatGateway
          - Condition
          - !Ref Identifier
          - DefaultValue: !Ref AWS::NoValue
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Conditions:
  TwoNatGateways: !Equals [!Ref "AWS::Region", "us-east-1"]
  ThreeNatGateways: !Equals [!Ref "AWS::Region", "us-west-2"]
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
  PublicSubnetA:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.1.0/24
      AvailabilityZone: !Select [0, !GetAZs ""]
  PublicSubnetB:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.2.0/24
      AvailabilityZone: !Select [1, !GetAZs ""]
  PublicSubnetC:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.3.0/24
      AvailabilityZone: !Select [2, !GetAZs ""]
  NatGatewayA:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt
        - NatGatewayAttachmentA
        - AllocationId
      SubnetId: !Ref PublicSubnetA
  NatGatewayB:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt
        - NatGatewayAttachmentB
        - AllocationId
      SubnetId: !Ref PublicSubnetB
    Condition: TwoNatGateways
  NatGatewayC:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt
        - NatGatewayAttachmentC
        - AllocationId
      SubnetId: !Ref PublicSubnetC
    Condition: ThreeNatGateways
  NatGatewayAttachmentA:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
  NatGatewayAttachmentB:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
    Condition: TwoNatGateways
  NatGatewayAttachmentC:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
    Condition: ThreeNatGateways
```

## Replica di più risorse utilizzando loop `Fn::ForEach` nidificati
<a name="intrinsic-function-reference-foreach-example-nested-loop-resources"></a>

Questo esempio utilizza i loop `Fn::ForEach` nidificati per mappare tre risorse ([AWS::EC2::NetworkAcl](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-natgateway.html), [AWS::EC2::Subnet](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-subnet.html) e [AWS::EC2::SubnetNetworkAclAssociation](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-subnetnetworkaclassociation.html)) l'una con l'altra.

### JSON
<a name="intrinsic-function-reference-foreach-example-nested-loop-resources.json"></a>

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::LanguageExtensions",
  "Resources": {
    "VPC": {
      "Type": "AWS::EC2::VPC",
      "Properties": {
        "CidrBlock": "10.0.0.0/16",
        "EnableDnsSupport": "true",
        "EnableDnsHostnames": "true"
      }
    },
    "Fn::ForEach::SubnetResources": [
      "Prefix",
      [
        "Transit",
        "Public"
      ],
      {
        "Nacl${Prefix}Subnet": {
          "Type": "AWS::EC2::NetworkAcl",
          "Properties": {
            "VpcId": {
              "Ref": "VPC"
            }
          }
        },
        "Fn::ForEach::LoopInner": [
          "Suffix",
          [
            "A",
            "B",
            "C"
          ],
          {
            "${Prefix}Subnet${Suffix}": {
              "Type": "AWS::EC2::Subnet",
              "Properties": {
                "VpcId": {
                  "Ref": "VPC"
                }
              }
            },
            "Nacl${Prefix}Subnet${Suffix}Association": {
              "Type": "AWS::EC2::SubnetNetworkAclAssociation",
              "Properties": {
                "SubnetId": {
                  "Ref": {
                    "Fn::Sub": "${Prefix}Subnet${Suffix}"
                  }
                },
                "NetworkAclId": {
                  "Ref": {
                    "Fn::Sub": "Nacl${Prefix}Subnet"
                  }
                }
              }
            }
          }
        ]
      }
    ]
  }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-nested-loop-resources.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
  'Fn::ForEach::SubnetResources':
  - Prefix
  - [Transit, Public]
  - 'Nacl${Prefix}Subnet':
      Type: AWS::EC2::NetworkAcl
      Properties:
        VpcId: !Ref 'VPC'
    'Fn::ForEach::LoopInner':
    - Suffix
    - [A, B, C]
    - '${Prefix}Subnet${Suffix}':
        Type: AWS::EC2::Subnet
        Properties:
          VpcId: !Ref 'VPC'
      'Nacl${Prefix}Subnet${Suffix}Association':
        Type: AWS::EC2::SubnetNetworkAclAssociation
        Properties:
          SubnetId: !Ref
            'Fn::Sub': '${Prefix}Subnet${Suffix}'
          NetworkAclId: !Ref
            'Fn::Sub': 'Nacl${Prefix}Subnet'
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
  NaclTransitSubnet:
    Type: AWS::EC2::NetworkAcl
    Properties:
      VpcId: !Ref VPC
  TransitSubnetA:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
  NaclTransitSubnetAAssociation:
    Type: AWS::EC2::SubnetNetworkAclAssociation
    Properties:
      SubnetId: !Ref TransitSubnetA
      NetworkAclId: !Ref NaclTransitSubnet
  TransitSubnetB:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
  NaclTransitSubnetBAssociation:
    Type: AWS::EC2::SubnetNetworkAclAssociation
    Properties:
      SubnetId: !Ref TransitSubnetB
      NetworkAclId: !Ref NaclTransitSubnet
  TransitSubnetC:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
  NaclTransitSubnetCAssociation:
    Type: AWS::EC2::SubnetNetworkAclAssociation
    Properties:
      SubnetId: !Ref TransitSubnetC
      NetworkAclId: !Ref NaclTransitSubnet
  NaclPublicSubnet:
    Type: AWS::EC2::NetworkAcl
    Properties:
      VpcId: !Ref VPC
  PublicSubnetA:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
  NaclPublicSubnetAAssociation:
    Type: AWS::EC2::SubnetNetworkAclAssociation
    Properties:
      SubnetId: !Ref PublicSubnetA
      NetworkAclId: !Ref NaclPublicSubnet
  PublicSubnetB:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
  NaclPublicSubnetBAssociation:
    Type: AWS::EC2::SubnetNetworkAclAssociation
    Properties:
      SubnetId: !Ref PublicSubnetB
      NetworkAclId: !Ref NaclPublicSubnet
  PublicSubnetC:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
  NaclPublicSubnetCAssociation:
    Type: AWS::EC2::SubnetNetworkAclAssociation
    Properties:
      SubnetId: !Ref PublicSubnetC
      NetworkAclId: !Ref NaclPublicSubnet
```

## Proprietà replicate di riferimento per una risorsa Amazon EC2
<a name="intrinsic-function-reference-foreach-example-reference-replicated-resource"></a>

Questo esempio utilizza la funzione intrinseca `Fn::ForEach` per fare riferimento alle risorse [AWS::EC2::Instance](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-instance.html) replicate.

### JSON
<a name="intrinsic-function-reference-foreach-example-reference-replicated-resource.json"></a>

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::LanguageExtensions",
  "Mappings": {
    "Instances": {
      "InstanceType": {
        "B": "m5.4xlarge",
        "C": "c5.2xlarge"
      },
      "ImageId": {"A": "ami-id1"}
    }
  },
  "Resources": {
    "Fn::ForEach::Instances": [
      "Identifier",
      [
        "A",
        "B",
        "C"
      ],
      {
        "Instance${Identifier}": {
          "Type": "AWS::EC2::Instance",
          "Properties": {
            "InstanceType": {"Fn::FindInMap": ["Instances", "InstanceType", {"Ref": "Identifier"}, {"DefaultValue": "m5.xlarge"}]},
            "ImageId": {"Fn::FindInMap": ["Instances", "ImageId", {"Ref": "Identifier"}, {"DefaultValue": "ami-id-default"}]}
          }
        }
      }
    ]
  },
  "Outputs": {
    "SecondInstanceId": {
      "Description": "Instance Id for InstanceB",
      "Value": {"Ref": "InstanceB"}
    },
    "SecondPrivateIp": {
      "Description": "Private IP for InstanceB",
      "Value": {
        "Fn::GetAtt": [
          "InstanceB",
          "PrivateIp"
        ]
      }
    }
  }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-reference-replicated-resource.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Mappings:
  Instances:
    InstanceType:
      B: m5.4xlarge
      C: c5.2xlarge
    ImageId:
      A: ami-id1
Resources:
  'Fn::ForEach::Instances':
  - Identifier
  - [A, B, C]
  - 'Instance${Identifier}':
      Type: AWS::EC2::Instance
      Properties:
        InstanceType: !FindInMap [Instances, InstanceType, !Ref 'Identifier', {DefaultValue: m5.xlarge}]
        ImageId: !FindInMap [Instances, ImageId, !Ref 'Identifier', {DefaultValue: ami-id-default}]
Outputs:
  SecondInstanceId:
    Description: Instance Id for InstanceB
    Value: !Ref 'InstanceB'
  SecondPrivateIp:
    Description: Private IP for InstanceB
    Value: !GetAtt [InstanceB, PrivateIp]
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  InstanceA:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: m5.xlarge
      ImageId: ami-id1
  InstanceB:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: m5.4xlarge
      ImageId: ami-id-default
  InstanceC:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: c5.2xlarge
      ImageId: ami-id-default
Outputs:
  SecondInstanceId:
    Description: Instance Id for InstanceB
    Value: !Ref InstanceB
  SecondPrivateIp:
    Description: Private IP for InstanceB
    Value: !GetAtt [InstanceB, PrivateIp]
```

## Proprietà replicate per una risorsa Amazon EC2
<a name="intrinsic-function-reference-foreach-example-replicate-resource-properties"></a>

Questo esempio utilizza la funzione intrinseca `Fn::ForEach` per ripetere alcune proprietà come `ImageId`, `InstanceType` e `AvailabilityZone` su una risorsa [AWS::EC2::Instance](https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-instance.html).

### JSON
<a name="intrinsic-function-reference-foreach-example-replicate-resource-properties.json"></a>

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::LanguageExtensions",
  "Mappings": {
    "InstanceA": {
      "Properties": {
        "ImageId": "ami-id1",
        "InstanceType": "m5.xlarge"
      }
    },
    "InstanceB": {
      "Properties": {
        "ImageId": "ami-id2"
      }
    },
    "InstanceC": {
      "Properties": {
        "ImageId": "ami-id3",
        "InstanceType": "m5.2xlarge",
        "AvailabilityZone": "us-east-1a"
      }
    }
  },
  "Resources": {
    "Fn::ForEach::Instances": [
      "InstanceLogicalId",
      [ "InstanceA", "InstanceB", "InstanceC" ],
      {
        "${InstanceLogicalId}": {
          "Type": "AWS::EC2::Instance",
          "Properties": {
            "DisableApiTermination": true,
            "UserData": {
              "Fn::Base64": {
                "Fn::Join": [
                  "",
                  [
                    "#!/bin/bash\n",
                    "yum update -y\n",
                    "yum install -y httpd.x86_64\n",
                    "systemctl start httpd.service\n",
                    "systemctl enable httpd.service\n",
                    "echo \"Hello World from $(hostname -f)\" > /var/www/html/index.html\n"
                  ]
                ]
              }
            },
            "Fn::ForEach::Properties": [
              "PropertyName",
              [ "ImageId", "InstanceType", "AvailabilityZone" ],
              {
                "${PropertyName}": {
                  "Fn::FindInMap": [
                    { "Ref": "InstanceLogicalId" },
                    "Properties",
                    { "Ref": "PropertyName"},
                    {
                      "DefaultValue": { "Ref": "AWS::NoValue" }
                    }
                  ]
                }
              }
            ]
          }
        }
      }
    ]
  }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-replicate-resource-properties.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Mappings:
  InstanceA:
    Properties:
      ImageId: ami-id1
      InstanceType: m5.xlarge
  InstanceB:
    Properties:
      ImageId: ami-id2
  InstanceC:
    Properties:
      ImageId: ami-id3
      InstanceType: m5.2xlarge
      AvailabilityZone: us-east-1a
Resources:
  'Fn::ForEach::Instances':
  - InstanceLogicalId
  - [InstanceA, InstanceB, InstanceC]
  - '${InstanceLogicalId}':
      Type: AWS::EC2::Instance
      Properties:
        DisableApiTermination: true
        UserData:
          Fn::Base64: !Sub |
            #!/bin/bash
            yum update -y
            yum install -y httpd.x86_64
            systemctl start httpd.service
            systemctl enable httpd.service
            echo "Hello World from $(hostname -f)" > /var/www/html/index.html
        'Fn::ForEach::Properties':
          - PropertyName
          - [ImageId, InstanceType, AvailabilityZone]
          - '${PropertyName}':
             'Fn::FindInMap':
               - Ref: 'InstanceLogicalId'
               - Properties
               - Ref: 'PropertyName'
               - {DefaultValue: !Ref 'AWS::NoValue'}
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  InstanceA:
    Type: AWS::EC2::Instance
    Properties:
      DisableApiTermination: true
      UserData:
        Fn::Base64: 
          !Sub |
            #!/bin/bash
            yum update -y
            yum install -y httpd.x86_64
            systemctl start httpd.service
            systemctl enable httpd.service
            echo "Hello World from $(hostname -f)" > /var/www/html/index.html
      ImageId: ami-id1
      InstanceType: m5.xlarge
  InstanceB:
    Type: AWS::EC2::Instance
    Properties:
      DisableApiTermination: true
      UserData:
        Fn::Base64: 
          !Sub |
            #!/bin/bash
            yum update -y
            yum install -y httpd.x86_64
            systemctl start httpd.service
            systemctl enable httpd.service
            echo "Hello World from $(hostname -f)" > /var/www/html/index.html
      ImageId: ami-id2
  InstanceC:
    Type: AWS::EC2::Instance
    Properties:
      DisableApiTermination: true
      UserData:
        Fn::Base64: 
          !Sub |
            #!/bin/bash
            yum update -y
            yum install -y httpd.x86_64
            systemctl start httpd.service
            systemctl enable httpd.service
            echo "Hello World from $(hostname -f)" > /var/www/html/index.html
      ImageId: ami-id3
      InstanceType: m5.2xlarge
      AvailabilityZone: us-east-1a
```

## Passare caratteri non alfanumerici all’interno di `Collection` per `Fn::ForEach`
<a name="intrinsic-function-reference-foreach-example-non-alphanumeric"></a>

Questo esempio utilizza la sintassi `&{}`, che consente il passaggio dei caratteri non alfanumerici (`.` e `/`) negli indirizzi IP all’interno di `Collection`.

### JSON
<a name="intrinsic-function-reference-foreach-example-non-alphanumeric-json.json"></a>

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Transform": "AWS::LanguageExtensions",
    "Parameters": {
        "IpAddresses": {
            "Type": "CommaDelimitedList",
            "Default": "10.0.2.0/24,10.0.3.0/24,10.0.4.0/24"
        }
    },
    "Resources": {
        "VPC": {
            "Type": "AWS::EC2::VPC",
            "Properties": {
                "CidrBlock": "10.0.0.0/16",
                "EnableDnsSupport": "true",
                "EnableDnsHostnames": "true"
            }
        },
        "Fn::ForEach::Subnets": [
            "CIDR",
            {
                "Ref": "IpAddresses"
            },
            {
                "Subnet&{CIDR}": {
                    "Type": "AWS::EC2::Subnet",
                    "Properties": {
                        "VpcId": {
                            "Ref": "VPC"
                        },
                        "CidrBlock": {
                            "Ref": "CIDR"
                        }
                    }
                }
            }
        ]
    }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-non-alphanumeric-yaml.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Parameters:
  IpAddresses:
    Type: CommaDelimitedList
    Default: '10.0.2.0/24,10.0.3.0/24,10.0.4.0/24'
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
  'Fn::ForEach::Subnets':
    - CIDR
    - !Ref IpAddresses
    - 'Subnet&{CIDR}':
        Type: AWS::EC2::Subnet
        Properties:
          VpcId: !Ref VPC
          CidrBlock: !Ref CIDR
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Parameters:
  IpAddresses:
    Type: CommaDelimitedList
    Default: '10.0.2.0/24,10.0.3.0/24,10.0.4.0/24'
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsSupport: 'true'
      EnableDnsHostnames: 'true'
  Subnet1002024:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.2.0/24
  Subnet1003024:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.3.0/24
  Subnet1004024:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      CidrBlock: 10.0.4.0/24
```

# Esempi di `Fn::ForEach` nella sezione `Outputs`
<a name="intrinsic-function-reference-foreach-example-outputs"></a>

Questi esempi dimostrano l’utilizzo della funzione intrinseca `Fn::ForEach` nella sezione `Outputs`. Per ulteriori informazioni su questa sezione, consulta [Outputs](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html) nella *Guida per l’utente di AWS CloudFormation *.

**Topics**
+ [Risorse `AWS::S3::Bucket` replicate di riferimento](#intrinsic-function-reference-foreach-example-replicate-outputs)
+ [Risorse `AWS::EC2::Instance` replicate di riferimento](#intrinsic-function-reference-foreach-example-replicate-conditions)

## Risorse `AWS::S3::Bucket` replicate di riferimento
<a name="intrinsic-function-reference-foreach-example-replicate-outputs"></a>

Questo esempio utilizza loop `Fn::ForEach` nidificati nella sezione `Outputs` per ridurre la lunghezza del modello.

### JSON
<a name="intrinsic-function-reference-foreach-example-replicate-outputs.json"></a>

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::LanguageExtensions",
  "Resources": {
    "Fn::ForEach::Buckets": [
      "Identifier",
      [ "A", "B", "C" ],
      {
        "S3Bucket${Identifier}": {
          "Type": "AWS::S3::Bucket",
          "Properties": {
            "AccessControl": "PublicRead",
            "MetricsConfigurations": [
              {
                "Id": {"Fn::Sub": "EntireBucket${Identifier}"}
              }
            ],
            "WebsiteConfiguration": {
              "IndexDocument": "index.html",
              "ErrorDocument": "error.html",
              "RoutingRules": [
                {
                  "RoutingRuleCondition": {
                    "HttpErrorCodeReturnedEquals": "404",
                    "KeyPrefixEquals": "out1/"
                  },
                  "RedirectRule": {
                    "HostName": "ec2-11-22-333-44.compute-1.amazonaws.com",
                    "ReplaceKeyPrefixWith": "report-404/"
                  }
                }
              ]
            }
          },
          "DeletionPolicy": "Retain",
          "UpdateReplacePolicy": "Retain"
        }
      }
    ]
  },
  "Outputs": {
    "Fn::ForEach::BucketOutputs": [
      "Identifier",
      [ "A", "B", "C" ],
      {
        "Fn::ForEach::GetAttLoop": [
          "Property",
          [ "Arn", "DomainName", "WebsiteURL" ],
          {
            "S3Bucket${Identifier}${Property}": {
              "Value": {"Fn::GetAtt": [{"Fn::Sub": "S3Bucket${Identifier}"}, {"Ref": "Property"}]}
            }
          }
        ]
      }
    ]
  }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-outputs.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  'Fn::ForEach::Buckets':
    - Identifier
    - [A, B, C]
    - 'S3Bucket${Identifier}':
        Type: AWS::S3::Bucket
        Properties:
          AccessControl: PublicRead
          MetricsConfigurations:
            - Id: !Sub 'EntireBucket${Identifier}'
          WebsiteConfiguration:
            IndexDocument: index.html
            ErrorDocument: error.html
            RoutingRules:
              - RoutingRuleCondition:
                  HttpErrorCodeReturnedEquals: '404'
                  KeyPrefixEquals: out1/
                RedirectRule:
                  HostName: ec2-11-22-333-44.compute-1.amazonaws.com
                  ReplaceKeyPrefixWith: report-404/
        DeletionPolicy: Retain
        UpdateReplacePolicy: Retain
Outputs:
  'Fn::ForEach::BucketOutputs':
    - Identifier
    - [A, B, C]
    - 'Fn::ForEach::GetAttLoop':
        - Property
        - [Arn, DomainName, WebsiteURL]
        - 'S3Bucket${Identifier}${Property}':
            Value: !GetAtt [!Sub 'S3Bucket${Identifier}', !Ref Property]
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  S3BucketA:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      MetricsConfigurations:
        - Id: EntireBucketA
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: error.html
        RoutingRules:
          - RoutingRuleCondition:
              HttpErrorCodeReturnedEquals: '404'
              KeyPrefixEquals: out1/
            RedirectRule:
              HostName: ec2-11-22-333-44.compute-1.amazonaws.com
              ReplaceKeyPrefixWith: report-404/
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
  S3BucketB:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      MetricsConfigurations:
        - Id: EntireBucketB
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: error.html
        RoutingRules:
          - RoutingRuleCondition:
              HttpErrorCodeReturnedEquals: '404'
              KeyPrefixEquals: out1/
            RedirectRule:
              HostName: ec2-11-22-333-44.compute-1.amazonaws.com
              ReplaceKeyPrefixWith: report-404/
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
  S3BucketC:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: PublicRead
      MetricsConfigurations:
        - Id: EntireBucketC
      WebsiteConfiguration:
        IndexDocument: index.html
        ErrorDocument: error.html
        RoutingRules:
          - RoutingRuleCondition:
              HttpErrorCodeReturnedEquals: '404'
              KeyPrefixEquals: out1/
            RedirectRule:
              HostName: ec2-11-22-333-44.compute-1.amazonaws.com
              ReplaceKeyPrefixWith: report-404/
    DeletionPolicy: Retain
    UpdateReplacePolicy: Retain
Outputs:
  S3BucketAArn:
    Value: !GetAtt [S3BucketA, Arn]
  S3BucketADomainName:
    Value: !GetAtt [S3BucketA, DomainName]
  S3BucketAWebsiteURL:
    Value: !GetAtt [S3BucketA, WebsiteURL]
  S3BucketBArn:
    Value: !GetAtt [S3BucketB, Arn]
  S3BucketBDomainName:
    Value: !GetAtt [S3BucketB, DomainName]
  S3BucketBWebsiteURL:
    Value: !GetAtt [S3BucketB, WebsiteURL]
  S3BucketCArn:
    Value: !GetAtt [S3BucketC, Arn]
  S3BucketCDomainName:
    Value: !GetAtt [S3BucketC, DomainName]
  S3BucketCWebsiteURL:
    Value: !GetAtt [S3BucketC, WebsiteURL]
```

## Risorse `AWS::EC2::Instance` replicate di riferimento
<a name="intrinsic-function-reference-foreach-example-replicate-conditions"></a>

Questo esempio fa riferimento alle risorse replicate nella `Resources` sezione utilizzando la logica IDs generata. 

### JSON
<a name="intrinsic-function-reference-foreach-example-replicate-conditions.json"></a>

```
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::LanguageExtensions",
  "Mappings": {
    "Instances": {
      "InstanceType": {
        "B": "m5.4xlarge",
        "C": "c5.2xlarge"
      },
      "ImageId": {"A": "ami-id1"}
    }
  },
  "Resources": {
    "Fn::ForEach::Instances": [
      "Identifier",
      [ "A", "B", "C" ],
      {
        "Instance${Identifier}": {
          "Type": "AWS::EC2::Instance",
          "Properties": {
            "InstanceType": {"Fn::FindInMap": ["Instances", "InstanceType", {"Ref": "Identifier"}, {"DefaultValue": "m5.xlarge"}]},
            "ImageId": {"Fn::FindInMap": ["Instances", "ImageId", {"Ref": "Identifier"}, {"DefaultValue": "ami-id-default"}]}
          }
        }
      }
    ]
  },
  "Outputs": {
    "SecondInstanceId": {
      "Description": "Instance Id for InstanceB",
      "Value": {"Ref": "InstanceB"}
    },
    "SecondPrivateIp": {
      "Description": "Private IP for InstanceB",
      "Value": {
        "Fn::GetAtt": [
          "InstanceB",
          "PrivateIp"
        ]
      }
    }
  }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-replicate-conditions.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Mappings:
  Instances:
    InstanceType:
      B: m5.4xlarge
      C: c5.2xlarge
    ImageId:
      A: ami-id1
Resources:
  'Fn::ForEach::Instances':
    - Identifier
    - [A, B, C]
    - 'Instance${Identifier}':
        Type: AWS::EC2::Instance
        Properties:
          InstanceType: !FindInMap [Instances, InstanceType, !Ref Identifier, DefaultValue: m5.xlarge]
          ImageId: !FindInMap [Instances, ImageId, !Ref Identifier, DefaultValue: ami-id-default]
Outputs:
  SecondInstanceId:
    Description: Instance Id for InstanceB
    Value: !Ref InstanceB
  SecondPrivateIp:
    Description: Private IP for InstanceB
    Value: !GetAtt [InstanceB, PrivateIp]
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Resources:
  InstanceA:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: m5.xlarge
      ImageId: ami-id1
  InstanceB:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: m5.4xlarge
      ImageId: ami-id-default
  InstanceC:
    Type: AWS::EC2::Instance
    Properties:
      InstanceType: c5.2xlarge
      ImageId: ami-id-default
Outputs:
  SecondInstanceId:
    Description: Instance Id for InstanceB
    Value: !Ref InstanceB
  SecondPrivateIp:
    Description: Private IP for InstanceB
    Value: !GetAtt [InstanceB, PrivateIp]
```

# Esempi di `Fn::ForEach` nella sezione `Conditions`
<a name="intrinsic-function-reference-foreach-example-conditions"></a>

Questi esempi dimostrano l’utilizzo della funzione intrinseca `Fn::ForEach` nella sezione `Conditions`. Per ulteriori informazioni su questa sezione, consulta [Conditions](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html) nella *Guida per l’utente di AWS CloudFormation *.

**Importante**  
`Conditions` deve essere la seconda proprietà elencata o successiva. La creazione dello stack avrà esito negativo se `Conditions` è la prima proprietà elencata nel parametro del frammento di modello di `Fn::ForEach`.

```
Resources:
  'Fn::ForEach::Topics':
    - LogicalId
    - !Ref TopicList
    - '${LogicalId}':
        Condition: !Sub 'TopicCondition${LogicalId}'
        Type: AWS::SNS::Topic
        Properties:
          TopicName: !Sub 'My${LogicalId}'
```

`Conditions` deve essere aggiunta come seconda chiave (o successiva) affinché lo stack venga creato correttamente: 

```
Resources:
  'Fn::ForEach::Topics':
    - LogicalId
    - !Ref TopicList
    - '${LogicalId}':
        Type: AWS::SNS::Topic
        Condition: !Sub 'TopicCondition${LogicalId}'
        Properties:
          TopicName: !Sub 'My${LogicalId}'
```

**Topics**
+ [Replica di una singola condizione](#intrinsic-function-reference-foreach-example-replicated-single-condition)

## Replica di una singola condizione
<a name="intrinsic-function-reference-foreach-example-replicated-single-condition"></a>

Questo esempio utilizza la funzione intrinseca `Fn::ForEach` nella sezione `Conditions` per replicare più condizioni simili con proprietà diverse.

### JSON
<a name="intrinsic-function-reference-foreach-example-conditions.json"></a>

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Transform": "AWS::LanguageExtensions",
    "Parameters": {
        "ParamA": {
            "Type": "String",
            "AllowedValues": [
                "true",
                "false"
            ]
        },
        "ParamB": {
            "Type": "String",
            "AllowedValues": [
                "true",
                "false"
            ]
        },
        "ParamC": {
            "Type": "String",
            "AllowedValues": [
                "true",
                "false"
            ]
        },
        "ParamD": {
            "Type": "String",
            "AllowedValues": [
                "true",
                "false"
            ]
        }
    },
    "Conditions": {
        "Fn::ForEach::CheckTrue": [
            "Identifier",
            ["A", "B", "C", "D"],
            {
                "IsParam${Identifier}Enabled": {
                    "Fn::Equals": [
                        {"Ref": {"Fn::Sub": "Param${Identifier}"}},
                        "true"
                    ]
                }
            }
        ]
    },
    "Resources": {
        "WaitConditionHandle": {
            "Type": "AWS::CloudFormation::WaitConditionHandle"
        }
    }
}
```

### YAML
<a name="intrinsic-function-reference-foreach-example-conditions.yaml"></a>

```
AWSTemplateFormatVersion: 2010-09-09
Transform: AWS::LanguageExtensions
Parameters:
  ParamA:
    Type: String
    AllowedValues:
      - 'true'
      - 'false'
  ParamB:
    Type: String
    AllowedValues:
      - 'true'
      - 'false'
  ParamC:
    Type: String
    AllowedValues:
      - 'true'
      - 'false'
  ParamD:
    Type: String
    AllowedValues:
      - 'true'
      - 'false'
Conditions:
  'Fn::ForEach::CheckTrue':
    - Identifier
    - [A, B, C, D]
    - 'IsParam${Identifier}Enabled': !Equals 
        - !Ref 
          'Fn::Sub': 'Param${Identifier}'
        - 'true'
Resources:
  WaitConditionHandle:
    Type: AWS::CloudFormation::WaitConditionHandle
```

Il modello trasformato sarà equivalente al modello seguente:

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  ParamA:
    Type: String
    AllowedValues:
      - 'true'
      - 'false'
  ParamB:
    Type: String
    AllowedValues:
      - 'true'
      - 'false'
  ParamC:
    Type: String
    AllowedValues:
      - 'true'
      - 'false'
  ParamD:
    Type: String
    AllowedValues:
      - 'true'
      - 'false'
Conditions:
  IsParamAEnabled: !Equals 
    - !Ref ParamA
    - 'true'
  IsParamBEnabled: !Equals 
    - !Ref ParamB
    - 'true'
  IsParamCEnabled: !Equals 
    - !Ref ParamC
    - 'true'
  IsParamDEnabled: !Equals 
    - !Ref ParamD
    - 'true'
Resources:
  WaitConditionHandle:
    Type: AWS::CloudFormation::WaitConditionHandle
```