Seleziona le tue preferenze relative ai cookie

Utilizziamo cookie essenziali e strumenti simili necessari per fornire il nostro sito e i nostri servizi. Utilizziamo i cookie prestazionali per raccogliere statistiche anonime in modo da poter capire come i clienti utilizzano il nostro sito e apportare miglioramenti. I cookie essenziali non possono essere disattivati, ma puoi fare clic su \"Personalizza\" o \"Rifiuta\" per rifiutare i cookie prestazionali.

Se sei d'accordo, AWS e le terze parti approvate utilizzeranno i cookie anche per fornire utili funzionalità del sito, ricordare le tue preferenze e visualizzare contenuti pertinenti, inclusa la pubblicità pertinente. Per continuare senza accettare questi cookie, fai clic su \"Continua\" o \"Rifiuta\". Per effettuare scelte più dettagliate o saperne di più, fai clic su \"Personalizza\".

Configurazione ed esecuzione della sintesi dello stack CDK

Modalità Focus
Configurazione ed esecuzione della sintesi dello stack CDK - AWS Cloud Development Kit (AWS CDK) v2

Questa è la guida per sviluppatori AWS CDK v2. 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à.

Questa è la guida per sviluppatori AWS CDK v2. 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à.

Prima di poter distribuire uno AWS Cloud Development Kit (AWS CDK) stack, è necessario prima 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 implementazioni, consulta. Come funzionano le AWS CDK implementazioni

Come funzionano insieme la sintesi e il bootstrap

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 ambiente per le distribuzioni. AWS AWS CDK Configura AWS risorse specifiche nell'ambiente che vengono utilizzate dal CDK per le distribuzioni. Queste sono comunemente chiamate risorse bootstrap. Per istruzioni sul bootstrap, vedere. Avvia il tuo ambiente per utilizzarlo con AWS CDK

  • CloudFormation i modelli prodotti durante la sintesi includono informazioni sulle risorse di bootstrap da utilizzare. Durante la sintesi, il CDK CLI non sa esattamente come sia stato avviato il vostro AWS ambiente. Invece, il CDK CLI produce CloudFormation modelli basati sul sintetizzatore configurato per ogni stack CDK. Affinché un'implementazione 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

Configurate la sintesi dello stack CDK utilizzando la synthesizer proprietà della vostra istanza. Stack Questa proprietà specifica come verranno sintetizzati gli stack CDK. Fornisci un'istanza di una classe che implementa o. IStackSynthesizer IReusableStackSynthesizer 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:

TypeScript
new MyStack(this, 'MyStack', { // stack properties synthesizer: new DefaultStackSynthesizer({ // synthesizer properties }), });
JavaScript
new MyStack(this, 'MyStack', { // stack properties synthesizer: new DefaultStackSynthesizer({ // synthesizer properties }), });
Python
MyStack(self, "MyStack", # stack properties synthesizer=DefaultStackSynthesizer( # synthesizer properties ))
Java

new MyStack(app, "MyStack", StackProps.builder() // stack properties .synthesizer(DefaultStackSynthesizer.Builder.create() // synthesizer properties .build()) .build();
C#
new MyStack(app, "MyStack", new StackProps // stack properties { Synthesizer = new DefaultStackSynthesizer(new DefaultStackSynthesizerProps { // synthesizer properties }) });
Go
func main() { app := awscdk.NewApp(nil) NewMyStack(app, "MyStack", &MyStackProps{ StackProps: awscdk.StackProps{ Synthesizer: awscdk.NewDefaultStackSynthesizer(&awscdk.DefaultStackSynthesizerProps{ // synthesizer properties }), }, }) app.Synth(nil) }
new MyStack(this, 'MyStack', { // stack properties synthesizer: new DefaultStackSynthesizer({ // synthesizer properties }), });

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

TypeScript

import { App, Stack, DefaultStackSynthesizer } from 'aws-cdk-lib'; const app = new App({ // Configure for all stacks in this app defaultStackSynthesizer: new DefaultStackSynthesizer({ /* ... */ }), });
JavaScript

const { App, Stack, DefaultStackSynthesizer } = require('aws-cdk-lib'); const app = new App({ // Configure for all stacks in this app defaultStackSynthesizer: new DefaultStackSynthesizer({ /* ... */ }), });
Python

from aws_cdk import App, Stack, DefaultStackSynthesizer app = App( default_stack_synthesizer=DefaultStackSynthesizer( # Configure for all stacks in this app # ... ) )
Java

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() ); } }
C#

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 { // ... }) }); } } }
Go

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{ // ... }), }) }

import { App, Stack, DefaultStackSynthesizer } from 'aws-cdk-lib'; const app = new App({ // Configure for all stacks in this app defaultStackSynthesizer: new DefaultStackSynthesizer({ /* ... */ }), });

Per impostazione predefinita, gli usi. AWS CDK DefaultStackSynthesizer 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

Per sintetizzare uno stack CDK, utilizzate l'interfaccia a riga di comando ( AWS CDK AWS CDK CLIcomando). cdk synth Per ulteriori informazioni su questo comando, incluse le opzioni che è possibile utilizzare con questo comando, vederecdk synthesize.

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, il CDK CLI sintetizzerà 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 ed esegui, il CDK cdk deploy CLI sintetizzerà automaticamente lo stack prima della distribuzione.

Come funziona la sintesi di default

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-path><construct-ID><unique-hash>

  • Percorso di costruzione: l'intero percorso verso la costruzione nell'app CDK. Questo percorso esclude l'ID del costrutto L1, che è sempre Resource oDefault, 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: 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, AWS CDK troncheranno il percorso di costruzione e l'ID del costrutto, se necessario, per mantenere 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:

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#
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 } // ...
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, }); } }

Quando eseguiamocdk 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:

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#
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) }

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'); } }

Quando eseguiamocdk 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

Se il comportamento di sintesi CDK predefinito non soddisfa le tue esigenze, puoi personalizzare la sintesi CDK. Per fare ciò, modificateDefaultStackSynthesizer, utilizzate altri sintetizzatori incorporati disponibili o create il vostro sintetizzatore. Per istruzioni, consultare Personalizza la sintesi dello stack CDK.

PrivacyCondizioni del sitoPreferenze cookie
© 2025, Amazon Web Services, Inc. o società affiliate. Tutti i diritti riservati.