

Ceci est le guide du développeur du AWS CDK v2. L'ancien CDK v1 est entré en maintenance le 1er juin 2022 et a pris fin le 1er juin 2023.

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Configuration et exécution de la synthèse de piles CDK
<a name="configure-synth"></a>

Avant de pouvoir déployer une pile AWS Cloud Development Kit (AWS CDK), celle-ci doit d'abord être synthétisée. La *synthèse de pile* est le processus de production d'un AWS CloudFormation modèle et d'artefacts de déploiement à partir d'une pile CDK. Le modèle et les artefacts sont appelés *assemblage cloud*. L'assemblage du cloud est ce qui est déployé pour provisionner vos ressources AWS. Pour plus d'informations sur le fonctionnement des déploiements, consultez [Comment fonctionnent les déploiements AWS CDK](deploy.md#deploy-how).

## Comment la synthèse et le bootstrapping fonctionnent ensemble
<a name="configure-synth-bootstrap"></a>

Pour que vos applications CDK soient correctement déployées, les CloudFormation modèles produits lors de la synthèse doivent spécifier correctement les ressources créées lors du démarrage. Par conséquent, le bootstrap et la synthèse doivent se compléter pour qu'un déploiement soit réussi :
+ Le bootstrapping est un processus ponctuel de configuration d'un AWS environnement pour les déploiements de AWS CDK. Il configure les AWS ressources spécifiques de votre environnement qui sont utilisées par le CDK pour les déploiements. Ces ressources sont communément appelées *ressources bootstrap*. Pour obtenir des instructions sur le bootstrap, voir [Bootstrap your environment for use with](bootstrapping-env.md) the CDK. AWS 
+ CloudFormation les modèles produits lors de la synthèse incluent des informations sur les ressources bootstrap à utiliser. Pendant la synthèse, la CLI CDK ne sait pas précisément comment votre AWS environnement a été amorcé. Au lieu de cela, la CLI CDK produit des CloudFormation modèles basés sur le synthétiseur que vous configurez pour chaque pile CDK. Pour qu'un déploiement soit réussi, le synthétiseur doit produire des CloudFormation modèles qui font référence aux bonnes ressources bootstrap à utiliser.

Le CDK est livré avec un synthétiseur par défaut et une configuration d'amorçage conçus pour fonctionner ensemble. Si vous personnalisez l'un, vous devez appliquer les personnalisations pertinentes à l'autre.

## Comment configurer la synthèse de piles CDK
<a name="bootstrapping-synthesizers"></a>

Vous configurez la synthèse de pile CDK à l'aide de la `synthesizer` propriété de votre [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)instance. Cette propriété indique comment vos piles CDK seront synthétisées. Vous fournissez une instance d'une classe qui implémente [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)ou [https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.IReusableStackSynthesizer.html](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.IReusableStackSynthesizer.html). Ses méthodes seront invoquées chaque fois qu'un actif est ajouté à la pile ou lorsque la pile est synthétisée. Voici un exemple de base de l'utilisation de cette propriété dans votre pile :

**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)
}
```

Vous pouvez également configurer un synthétiseur pour toutes les piles CDK de votre application CDK à l'aide de la `defaultStackSynthesizer` propriété de votre instance : `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{
            // ...
        }),
    })
}
```

Par défaut, le AWS CDK utilise` [`DefaultStackSynthesizer](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.DefaultStackSynthesizer.html) `. Si vous ne configurez pas de synthétiseur, celui-ci sera utilisé.

Si vous ne modifiez pas le bootstrap, par exemple en apportant des modifications à la pile ou au modèle de bootstrap, vous n'avez pas à modifier la synthèse de pile. Vous n'avez même pas besoin de fournir un synthétiseur. Le CDK utilisera la `DefaultStackSynthesizer` classe par défaut pour configurer la synthèse de pile CDK afin d'interagir correctement avec votre pile bootstrap.

## Comment synthétiser une pile de CDK
<a name="configure-synth-stack"></a>

Pour synthétiser une pile CDK, utilisez la commande AWS CDK Command Line Interface (CDK AWS CLI). `cdk synth` Pour plus d'informations sur cette commande, y compris les options que vous pouvez utiliser avec cette commande, voir [cdk synthesize](ref-cli-cmd-synth.md).

Si votre application CDK contient une seule pile, ou si vous souhaitez synthétiser toutes les piles, vous n'avez pas besoin de fournir le nom de la pile CDK comme argument. Par défaut, la CLI CDK synthétisera vos piles de CDK en modèles. AWS CloudFormation Un modèle `json` formaté pour chaque pile est enregistré `cdk.out` dans le répertoire. Si votre application contient une seule pile, un modèle `yaml` formaté est imprimé sur. `stdout` Voici un exemple :

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

Si votre application CDK contient plusieurs piles, vous pouvez fournir l'ID logique d'une pile pour synthétiser une seule pile. Voici un exemple :

```
$ cdk synth MyStackName
```

Si vous ne synthétisez pas une pile et ne l'exécutez pas`cdk deploy`, la CLI CDK synthétisera automatiquement votre pile avant le déploiement.

## Comment fonctionne la synthèse par défaut
<a name="how-synth-default"></a><a name="how-synth-default-logical-ids"></a>

 **Logique générée IDs dans votre AWS CloudFormation modèle**   
Lorsque vous synthétisez une pile CDK pour produire un CloudFormation modèle, des logiques IDs sont générées à partir des sources suivantes, formatées comme suit : `construct-pathconstruct-IDunique-hash`  
+  Chemin de **construction : chemin** complet menant à la construction dans votre application CDK. Ce chemin exclut l'ID de la construction L1, qui est toujours `Resource` ou`Default`, et l'ID de la pile de niveau supérieur dont elle fait partie.
+  **ID de construction** — L'ID que vous fournissez comme deuxième argument lors de l'instanciation de votre construction.
+  **Hachage unique — Le AWS CDK génère un hachage** unique à 8 caractères à l'aide d'un algorithme de hachage déterministe. Ce hachage unique permet de garantir que les valeurs d'identification logiques de votre modèle sont uniques les unes par rapport aux autres. Le comportement déterministe de cette génération de hachage garantit que la valeur d'identifiant logique générée pour chaque construction reste la même à chaque fois que vous effectuez une synthèse. La valeur de hachage ne changera que si vous modifiez des valeurs de construction spécifiques telles que l'ID de votre construction ou son chemin.

   IDs Les logiques ont une longueur maximale de 255 caractères. Par conséquent, le AWS CDK tronquera le chemin de construction et l'ID de construction si nécessaire pour respecter cette limite.

  Voici un exemple de construction qui définit un compartiment Amazon Simple Storage Service (Amazon S3). Ici, nous passons `myBucket` comme identifiant pour notre construction :  
**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
  }
  
  // ...
  ```

------

  Lorsque nous exécutons`cdk synth`, un identifiant logique au format de `myBucketunique-hash` est généré. Voici un exemple de cette ressource dans le AWS CloudFormation modèle généré :

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

  Voici un exemple de construction personnalisée nommée `Bar` qui définit un compartiment Amazon S3. La `Bar` construction inclut la construction personnalisée `Foo` dans son chemin :  
**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 ]

  Dans `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();
      }
  }
  ```

  Dans `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");
      }
  }
  ```

  Dans `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)
  }
  ```

------

  Lorsque nous exécutons`cdk synth`, un identifiant logique au format de `FooBarBucketunique-hash` est généré. Voici un exemple de cette ressource dans le AWS CloudFormation modèle généré :

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

## Personnalisez la synthèse de la pile CDK
<a name="bootstrapping-custom-synth"></a>

Si le comportement de synthèse CDK par défaut ne répond pas à vos besoins, vous pouvez personnaliser la synthèse CDK. Pour ce faire, vous devez modifier`DefaultStackSynthesizer`, utiliser d'autres synthétiseurs intégrés disponibles ou créer votre propre synthétiseur. Pour obtenir des instructions, voir [Personnaliser la synthèse de la pile CDK](customize-synth.md).