

Questa è la AWS CDK v2 Developer Guide. Il vecchio CDK v1 è entrato in manutenzione il 1° giugno 2022 e ha terminato il supporto il 1° giugno 2023.

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à.

# Configurazione ed esecuzione della sintesi dello stack CDK
<a name="configure-synth"></a>

Prima di poter implementare uno stack AWS Cloud Development Kit (AWS CDK), è necessario sintetizzarlo. La *sintesi dello stack* è il processo di produzione di un AWS CloudFormation modello e di distribuzione degli artefatti da uno stack CDK. *Il modello e gli artefatti sono noti come assemblaggio cloud.* L'assemblaggio cloud è ciò su cui viene distribuito il provisioning delle risorse. AWS Per ulteriori informazioni su come funzionano le distribuzioni, consulta [Come funzionano le implementazioni AWS CDK](deploy.md#deploy-how).

## Come funzionano insieme la sintesi e il bootstrap
<a name="configure-synth-bootstrap"></a>

Affinché le app CDK vengano distribuite correttamente, i CloudFormation modelli prodotti durante la sintesi devono specificare correttamente le risorse create durante il bootstrap. Pertanto, il bootstrap e la sintesi devono integrarsi a vicenda affinché un'implementazione abbia successo:
+ Il bootstrap è un processo unico di configurazione di un AWS ambiente per le implementazioni CDK. AWS Configura AWS risorse specifiche nell'ambiente che vengono utilizzate dal CDK per le distribuzioni. *Queste sono comunemente chiamate risorse bootstrap.* Per istruzioni sul bootstrap, consulta [Bootstrap your environment for use](bootstrapping-env.md) with the CDK. AWS 
+ CloudFormation i modelli prodotti durante la sintesi includono informazioni sulle risorse di bootstrap da utilizzare. Durante la sintesi, la CLI CDK non sa esattamente come è stato avviato AWS l'ambiente. Invece, la CLI CDK CloudFormation produce modelli basati sul sintetizzatore configurato per ogni stack CDK. Affinché una distribuzione abbia successo, il sintetizzatore deve produrre CloudFormation modelli che facciano riferimento alle risorse di bootstrap corrette da utilizzare.

Il CDK è dotato di un sintetizzatore e di una configurazione di bootstrap predefiniti progettati per funzionare insieme. Se ne personalizzi una, devi applicare le personalizzazioni pertinenti all'altra.

## Come configurare la sintesi dello stack CDK
<a name="bootstrapping-synthesizers"></a>

Si configura la sintesi dello stack CDK utilizzando la `synthesizer` proprietà della propria istanza. [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.Stack.html) Questa proprietà specifica come verranno sintetizzati gli stack CDK. Fornisci un'istanza di una classe che implementa o. [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.IStackSynthesizer.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.IStackSynthesizer.html) I suoi metodi verranno richiamati ogni volta che una risorsa viene aggiunta allo stack o quando lo stack viene sintetizzato. Di seguito è riportato un esempio di base dell'utilizzo di questa proprietà all'interno dello stack:

**Example**  

```
new MyStack(this, 'MyStack', {
  // stack properties
  synthesizer: new DefaultStackSynthesizer({
    // synthesizer properties
  }),
});
```

```
new MyStack(this, 'MyStack', {
  // stack properties
  synthesizer: new DefaultStackSynthesizer({
    // synthesizer properties
  }),
});
```

```
MyStack(self, "MyStack",
    # stack properties
    synthesizer=DefaultStackSynthesizer(
        # synthesizer properties
))
```

```
new MyStack(app, "MyStack", StackProps.builder()
  // stack properties
  .synthesizer(DefaultStackSynthesizer.Builder.create()
    // synthesizer properties
    .build())
  .build();
)
```

```
new MyStack(app, "MyStack", new StackProps
// stack properties
{
    Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps
    {
        // synthesizer properties
    })
});
```

```
func main() {
  app := awscdk.NewApp(nil)

  NewMyStack(app, "MyStack", &MyStackProps{
    StackProps: awscdk.StackProps{
      Synthesizer: awscdk.NewDefaultStackSynthesizer(&awscdk.DefaultStackSynthesizerProps{
        // synthesizer properties
      }),
    },
  })

  app.Synth(nil)
}
```

Puoi anche configurare un sintetizzatore per tutti gli stack CDK nell'app CDK utilizzando la proprietà dell'istanza: `defaultStackSynthesizer` `App`

**Example**  

```
import { App, Stack, DefaultStackSynthesizer } from 'aws-cdk-lib';

const app = new App({
  // Configure for all stacks in this app
  defaultStackSynthesizer: new DefaultStackSynthesizer({
    /* ... */
  }),
});
```

```
const { App, Stack, DefaultStackSynthesizer } = require('aws-cdk-lib');

const app = new App({
  // Configure for all stacks in this app
  defaultStackSynthesizer: new DefaultStackSynthesizer({
    /* ... */
  }),
});
```

```
from aws_cdk import App, Stack, DefaultStackSynthesizer

app = App(
    default_stack_synthesizer=DefaultStackSynthesizer(
        # Configure for all stacks in this app
        # ...
    )
)
```

```
import software.amazon.awscdk.App;
import software.amazon.awscdk.Stack;
import software.amazon.awscdk.DefaultStackSynthesizer;

public class Main {
    public static void main(final String[] args) {
        App app = new App(AppProps.builder()
            // Configure for all stacks in this app
            .defaultStackSynthesizer(DefaultStackSynthesizer.Builder.create().build())
            .build()
        );
    }
}
```

```
using Amazon.CDK;
using Amazon.CDK.Synthesizers;

namespace MyNamespace
{
    sealed class Program
    {
        public static void Main(string[] args)
        {
            var app = new App(new AppProps
            {
                // Configure for all stacks in this app
                DefaultStackSynthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps
                {
                    // ...
                })
            });
        }
    }
}
```

```
package main

import (
    "github.com/aws/aws-cdk-go/awscdk/v2"
    "github.com/aws/constructs-go/constructs/v10"
    "github.com/aws/jsii-runtime-go"
)

func main() {
    defer jsii.Close()

    app := awscdk.NewApp(&awscdk.AppProps{
        // Configure for all stacks in this app
        DefaultStackSynthesizer: awscdk.NewDefaultStackSynthesizer(&awscdk.DefaultStackSynthesizerProps{
            // ...
        }),
    })
}
```

Per impostazione predefinita, il CDK utilizza. AWS ` [`DefaultStackSynthesizer](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.DefaultStackSynthesizer.html) ` Se non configuri un sintetizzatore, verrà utilizzato questo sintetizzatore.

Se non modificate il bootstrap, ad esempio apportando modifiche allo stack o al modello di bootstrap, non è necessario modificare la sintesi dello stack. Non è nemmeno necessario fornire un sintetizzatore. Il CDK utilizzerà la `DefaultStackSynthesizer` classe predefinita per configurare la sintesi dello stack CDK per interagire correttamente con lo stack bootstrap.

## Come sintetizzare uno stack CDK
<a name="configure-synth-stack"></a>

Per sintetizzare uno stack CDK, utilizzate il comando CDK Command Line Interface ( AWS AWS CDK CLI). `cdk synth` [Per ulteriori informazioni su questo comando, incluse le opzioni che è possibile utilizzare con questo comando, vedete cdk synthesize.](ref-cli-cmd-synth.md)

Se l'app CDK contiene un singolo stack o per sintetizzare tutti gli stack, non è necessario fornire il nome dello stack CDK come argomento. Per impostazione predefinita, la CLI CDK sintetizza gli stack CDK in modelli. AWS CloudFormation Un modello `json` formattato per ogni stack viene salvato nella directory. `cdk.out` Se l'app contiene un singolo stack, viene stampato un modello `yaml` formattato su. `stdout` Di seguito è riportato un esempio:

```
$ cdk synth
Resources:
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Analytics: v2:deflate64:H4sIAAAAAAAA/unique-identifier
    Metadata:
      aws:cdk:path: CdkAppStack/CDKMetadata/Default
    Condition: CDKMetadataAvailable
    ...
```

Se l'app CDK contiene più stack, puoi fornire l'ID logico di uno stack per sintetizzare un singolo stack. Di seguito è riportato un esempio:

```
$ cdk synth MyStackName
```

Se non sintetizzi uno stack e non lo esegui`cdk deploy`, la CLI CDK sintetizzerà automaticamente lo stack prima della distribuzione.

## Come funziona la sintesi di default
<a name="how-synth-default"></a><a name="how-synth-default-logical-ids"></a>

 **Logico generato IDs nel tuo AWS CloudFormation modello**   
Quando sintetizzi uno stack CDK per produrre un CloudFormation modello, i dati logici IDs vengono generati dalle seguenti fonti, formattate come: `construct-pathconstruct-IDunique-hash`  
+  Percorso di **costruzione: l'intero percorso** verso la costruzione nell'app CDK. Questo percorso esclude l'ID del costrutto L1, che è sempre `Resource` o`Default`, e l'ID dello stack di primo livello di cui fa parte.
+  ID **del costrutto: l'ID** fornito come secondo argomento durante l'istanziazione del costrutto.
+  **Hash unico**: il AWS CDK genera un hash univoco di 8 caratteri utilizzando un algoritmo di hashing deterministico. Questo hash unico aiuta a garantire che i valori degli ID logici nel modello siano unici l'uno dall'altro. Il comportamento deterministico di questa generazione di hash assicura che il valore dell'ID logico generato per ogni costrutto rimanga lo stesso ogni volta che si esegue la sintesi. Il valore hash cambierà solo se modifichi valori di costrutto specifici come l'ID del costrutto o il suo percorso.

   IDs I logici hanno una lunghezza massima di 255 caratteri. Pertanto, il AWS CDK troncherà il percorso di costruzione e l'ID del costrutto, se necessario, per rispettare tale limite.

  Di seguito è riportato un esempio di costrutto che definisce un bucket Amazon Simple Storage Service (Amazon S3). Qui, passiamo `myBucket` come ID per il nostro costrutto:  
**Example**  

------
#### [ TypeScript ]

  ```
  import * as cdk from 'aws-cdk-lib';
  import { Construct} from 'constructs';
  import * as s3 from 'aws-cdk-lib/aws-s3';
  
  export class MyCdkAppStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
      super(scope, id, props);
  
      // Define the S3 bucket
      new s3.Bucket(this, 'myBucket', {
        versioned: true,
        removalPolicy: cdk.RemovalPolicy.DESTROY,
      });
    }
  }
  ```

------
#### [ JavaScript ]

  ```
  const cdk = require('aws-cdk-lib');
  const s3 = require('aws-cdk-lib/aws-s3');
  
  class MyCdkAppStack extends cdk.Stack {
  
    constructor(scope, id, props) {
      super(scope, id, props);
  
      new s3.Bucket(this, 'myBucket', {
        versioned: true,
        removalPolicy: cdk.RemovalPolicy.DESTROY,
      });
    }
  }
  
  module.exports = { MyCdkAppStack }
  ```

------
#### [ Python ]

  ```
  import aws_cdk as cdk
  from constructs import Construct
  from aws_cdk import Stack
  from aws_cdk import aws_s3 as s3
  
  class MyCdkAppStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) - None:
      super().__init__(scope, construct_id, **kwargs)
  
      s3.Bucket(self, 'MyBucket',
        versioned=True,
        removal_policy=cdk.RemovalPolicy.DESTROY
      )
  ```

------
#### [ Java ]

  ```
  package com.myorg;
  
  import software.constructs.Construct;
  import software.amazon.awscdk.Stack;
  import software.amazon.awscdk.StackProps;
  import software.amazon.awscdk.services.s3.Bucket;
  import software.amazon.awscdk.services.s3.BucketProps;
  import software.amazon.awscdk.RemovalPolicy;
  
  public class MyCdkAppStack extends Stack {
      public MyCdkAppStack(final Construct scope, final String id) {
          this(scope, id, null);
      }
  
      public MyCdkAppStack(final Construct scope, final String id, final StackProps props) {
          super(scope, id, props);
  
          Bucket.Builder.create(this, "myBucket")
              .versioned(true)
              .removalPolicy(RemovalPolicy.DESTROY)
              .build();
      }
  }
  ```

------
#### [ C\$1 ]

  ```
  using Amazon.CDK;
  using Constructs;
  using Amazon.CDK.AWS.S3;
  
  namespace MyCdkApp
  {
      public class MyCdkAppStack : Stack
      {
          public MyCdkAppStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
          {
              new Bucket(this, "myBucket", new BucketProps
              {
                  Versioned = true,
                  RemovalPolicy = RemovalPolicy.DESTROY
              });
          }
      }
  }
  ```

------
#### [ Go ]

  ```
  package main
  
  import (
      "github.com/aws/aws-cdk-go/awscdk/v2"
      "github.com/aws/aws-cdk-go/awscdk/v2/awss3"
      "github.com/aws/constructs-go/constructs/v10"
      "github.com/aws/jsii-runtime-go"
  )
  
  type MyCdkAppStackProps struct {
      awscdk.StackProps
  }
  
  func NewMyCdkAppStack(scope constructs.Construct, id string, props *MyCdkAppStackProps) awscdk.Stack {
      var sprops awscdk.StackProps
      if props != nil {
          sprops = props.StackProps
      }
      stack := awscdk.NewStack(scope, id, sprops)
  
      awss3.NewBucket(stack, jsii.String("myBucket"), awss3.BucketProps{
        Versioned: jsii.Bool(true),
        RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
      })
  
      return stack
  }
  
  // ...
  ```

------

  Quando eseguiamo`cdk synth`, `myBucketunique-hash` viene generato un ID logico nel formato di. Di seguito è riportato un esempio di questa risorsa nel AWS CloudFormation modello generato:

  ```
  Resources:
    myBucket5AF9C99B:
      Type: AWS::S3::Bucket
      Properties:
        VersioningConfiguration:
          Status: Enabled
      UpdateReplacePolicy: Delete
      DeletionPolicy: Delete
      Metadata:
        aws:cdk:path: S3BucketAppStack/myBucket/Resource
  ```

  Di seguito è riportato un esempio di costrutto personalizzato denominato `Bar` che definisce un bucket Amazon S3. Il `Bar` costrutto include il costrutto `Foo` personalizzato nel suo percorso:  
**Example**  

------
#### [ TypeScript ]

  ```
  import * as cdk from 'aws-cdk-lib';
  import { Construct } from 'constructs';
  import * as s3 from 'aws-cdk-lib/aws-s3';
  
  // Define the Bar construct
  export class Bar extends Construct {
    constructor(scope: Construct, id: string) {
      super(scope, id);
  
      // Define an S3 bucket inside of Bar
      new s3.Bucket(this, 'Bucket', {
         versioned: true,
         removalPolicy: cdk.RemovalPolicy.DESTROY,
        } );
    }
  }
  
  // Define the Foo construct
  export class Foo extends Construct {
    constructor(scope: Construct, id: string) {
      super(scope, id);
  
      // Create an instance of Bar inside Foo
      new Bar(this, 'Bar');
    }
  }
  
  // Define the CDK stack
  export class MyCustomAppStack extends cdk.Stack {
    constructor(scope: Construct, id: string, props?: cdk.StackProps) {
      super(scope, id, props);
  
      // Instantiate Foo construct in the stack
      new Foo(this, 'Foo');
    }
  }
  ```

------
#### [ JavaScript ]

  ```
  const cdk = require('aws-cdk-lib');
  const s3 = require('aws-cdk-lib/aws-s3');
  const { Construct } = require('constructs');
  
  // Define the Bar construct
  class Bar extends Construct {
    constructor(scope, id) {
      super(scope, id);
  
      // Define an S3 bucket inside of Bar
      new s3.Bucket(this, 'Bucket', {
        versioned: true,
        removalPolicy: cdk.RemovalPolicy.DESTROY,
      });
    }
  }
  
  // Define the Foo construct
  class Foo extends Construct {
    constructor(scope, id) {
      super(scope, id);
  
      // Create an instance of Bar inside Foo
      new Bar(this, 'Bar');
    }
  }
  
  // Define the CDK stack
  class MyCustomAppStack extends cdk.Stack {
    constructor(scope, id, props) {
      super(scope, id, props);
  
      // Instantiate Foo construct in the stack
      new Foo(this, 'Foo');
    }
  }
  
  module.exports = { MyCustomAppStack }
  ```

------
#### [ Python ]

  ```
  import aws_cdk as cdk
  from constructs import Construct
  from aws_cdk import (
      Stack,
      aws_s3 as s3,
      RemovalPolicy,
  )
  
  # Define the Bar construct
  class Bar(Construct):
      def __init__(self, scope: Construct, id: str) - None:
          super().__init__(scope, id)
  
          # Define an S3 bucket inside of Bar
          s3.Bucket(self, 'Bucket',
              versioned=True,
              removal_policy=RemovalPolicy.DESTROY
          )
  
  # Define the Foo construct
  class Foo(Construct):
      def __init__(self, scope: Construct, id: str) - None:
          super().__init__(scope, id)
  
          # Create an instance of Bar inside Foo
          Bar(self, 'Bar')
  
  # Define the CDK stack
  class MyCustomAppStack(Stack):
      def __init__(self, scope: Construct, id: str, **kwargs) - None:
          super().__init__(scope, id, **kwargs)
  
          # Instantiate Foo construct in the stack
          Foo(self, 'Foo')
  ```

------
#### [ Java ]

  In `my-custom-app/src/main/java/com/myorg/Bar.java`:

  ```
  package com.myorg;
  
  import software.constructs.Construct;
  import software.amazon.awscdk.services.s3.Bucket;
  import software.amazon.awscdk.services.s3.BucketProps;
  import software.amazon.awscdk.RemovalPolicy;
  
  public class Bar extends Construct {
      public Bar(final Construct scope, final String id) {
          super(scope, id);
  
          // Define an S3 bucket inside Bar
          Bucket.Builder.create(this, "Bucket")
              .versioned(true)
              .removalPolicy(RemovalPolicy.DESTROY)
              .build();
      }
  }
  ```

  In `my-custom-app/src/main/java/com/myorg/Foo.java`:

  ```
  package com.myorg;
  
  import software.constructs.Construct;
  
  public class Foo extends Construct {
      public Foo(final Construct scope, final String id) {
          super(scope, id);
  
          // Create an instance of Bar inside Foo
          new Bar(this, "Bar");
      }
  }
  ```

  In `my-custom-app/src/main/java/com/myorg/MyCustomAppStack.java`:

  ```
  package com.myorg;
  
  import software.constructs.Construct;
  import software.amazon.awscdk.Stack;
  import software.amazon.awscdk.StackProps;
  
  public class MyCustomAppStack extends Stack {
      public MyCustomAppStack(final Construct scope, final String id, final StackProps props) {
          super(scope, id, props);
  
          // Instantiate Foo construct in the stack
          new Foo(this, "Foo");
      }
  
      // Overload constructor in case StackProps is not provided
      public MyCustomAppStack(final Construct scope, final String id) {
          this(scope, id, null);
      }
  }
  ```

------
#### [ C\$1 ]

  ```
  using Amazon.CDK;
  using Constructs;
  using Amazon.CDK.AWS.S3;
  
  namespace MyCustomApp
  {
      // Define the Bar construct
      public class Bar : Construct
      {
          public Bar(Construct scope, string id) : base(scope, id)
          {
              // Define an S3 bucket inside Bar
              new Bucket(this, "Bucket", new BucketProps
              {
                  Versioned = true,
                  RemovalPolicy = RemovalPolicy.DESTROY
              });
          }
      }
  
      // Define the Foo construct
      public class Foo : Construct
      {
          public Foo(Construct scope, string id) : base(scope, id)
          {
              // Create an instance of Bar inside Foo
              new Bar(this, "Bar");
          }
      }
  
      // Define the CDK Stack
      public class MyCustomAppStack : Stack
      {
          public MyCustomAppStack(Construct scope, string id, StackProps props = null) : base(scope, id, props)
          {
              // Instantiate Foo construct in the stack
              new Foo(this, "Foo");
          }
      }
  }
  ```

------
#### [ Go ]

  ```
  package main
  
  import (
  	"github.com/aws/aws-cdk-go/awscdk/v2"
  	"github.com/aws/aws-cdk-go/awscdk/v2/awss3"
  	"github.com/aws/constructs-go/constructs/v10"
  	"github.com/aws/jsii-runtime-go"
  )
  
  // Define the Bar construct
  type Bar struct {
  	constructs.Construct
  }
  
  func NewBar(scope constructs.Construct, id string) constructs.Construct {
  	bar := constructs.NewConstruct(scope, id)
  
  	// Define an S3 bucket inside Bar
  	awss3.NewBucket(bar, jsii.String("Bucket"), awss3.BucketProps{
  		Versioned:     jsii.Bool(true),
  		RemovalPolicy: awscdk.RemovalPolicy_DESTROY,
  	})
  
  	return bar
  }
  
  // Define the Foo construct
  type Foo struct {
  	constructs.Construct
  }
  
  func NewFoo(scope constructs.Construct, id string) constructs.Construct {
  	foo := constructs.NewConstruct(scope, id)
  
  	// Create an instance of Bar inside Foo
  	NewBar(foo, "Bar")
  
  	return foo
  }
  
  // Define the CDK Stack
  type MyCustomAppStackProps struct {
  	awscdk.StackProps
  }
  
  func NewMyCustomAppStack(scope constructs.Construct, id string, props *MyCustomAppStackProps) awscdk.Stack {
  	stack := awscdk.NewStack(scope, id, props.StackProps)
  
  	// Instantiate Foo construct in the stack
  	NewFoo(stack, "Foo")
  
  	return stack
  }
  
  // Define the CDK App
  func main() {
  	app := awscdk.NewApp(nil)
  
  	NewMyCustomAppStack(app, "MyCustomAppStack", MyCustomAppStackProps{
  		StackProps: awscdk.StackProps{},
  	})
  
  	app.Synth(nil)
  }
  ```

------

  Quando eseguiamo`cdk synth`, `FooBarBucketunique-hash` viene generato un ID logico nel formato di. Di seguito è riportato un esempio di questa risorsa nel AWS CloudFormation modello generato:

  ```
  Resources:
    FooBarBucketBA3ED1FA:
      Type: AWS::S3::Bucket
      Properties:
        VersioningConfiguration:
          Status: Enabled
      UpdateReplacePolicy: Delete
      DeletionPolicy: Delete
      # ...
  ```

## Personalizza la sintesi dello stack CDK
<a name="bootstrapping-custom-synth"></a>

Se il comportamento di sintesi CDK predefinito non soddisfa le tue esigenze, puoi personalizzare la sintesi CDK. Per fare ciò, modificate`DefaultStackSynthesizer`, utilizzate altri sintetizzatori incorporati disponibili o create il vostro sintetizzatore. Per istruzioni, consulta [Personalizzare](customize-synth.md) la sintesi dello stack CDK.