

CDK AWS v2 개발자 안내서입니다. 이전 CDK v1은 2022년 6월 1일에 유지 관리에 들어갔으며 2023년 6월 1일에 지원이 종료되었습니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# CDK 스택 합성 구성 및 수행
<a name="configure-synth"></a>

AWS Cloud Development Kit(AWS CDK) 스택을 배포하려면 먼저 스택을 합성해야 합니다. *스택 합성*은 CDK 스택에서 AWS CloudFormation 템플릿과 배포 아티팩트를 생성하는 프로세스입니다. 템플릿과 아티팩트를 *클라우드 어셈블리*라고 합니다. 클라우드 어셈블리는 AWS에서 리소스를 프로비저닝하기 위해 배포되는 것입니다. 배포 작동 방식에 대한 자세한 내용은 [AWS CDK 배포 작동 방식](deploy.md#deploy-how)을 참조하세요.

## 합성과 부트스트래핑이 함께 작동하는 방식
<a name="configure-synth-bootstrap"></a>

CDK 앱이 올바르게 배포되려면 합성 중 생성된 CloudFormation 템플릿이 부트스트래핑 중 생성된 리소스를 올바르게 지정해야 합니다. 따라서 배포가 성공하려면 부트스트래핑과 합성이 서로 보완되어야 합니다.
+ 부트스트래핑은 AWS CDK 배포를 위해 AWS 환경을 설정하는 일회성 프로세스이며 CDK에서 배포에 사용하는 환경의 특정 AWS 리소스를 구성합니다. 이를 보통 *부트스트랩 리소스*라고 합니다. 부트스트래핑에 대한 지침은 [AWS CDK와 함께 사용할 환경 부트스트래핑](bootstrapping-env.md)을 참조하세요.
+ 합성 중 생성된 CloudFormation 템플릿에는 사용할 부트스트랩 리소스에 대한 정보가 포함됩니다. 합성 중 CDK CLI는 AWS 환경이 부트스트래핑된 방식을 구체적으로 알지 못합니다. 대신 CDK CLI는 각 CDK 스택에 대해 구성하는 신디사이저를 기반으로 CloudFormation 템플릿을 생성합니다. 배포가 성공하려면 신디사이저가 사용할 올바른 부트스트랩 리소스를 참조하는 CloudFormation 템플릿을 생성해야 합니다.

CDK는 함께 작동하도록 설계된 기본 신디사이저 및 부트스트래핑 구성과 함께 제공됩니다. 하나를 사용자 지정하는 경우 다른 하나에 관련 사용자 지정을 적용해야 합니다.

## CDK 스택 합성을 구성하는 방법
<a name="bootstrapping-synthesizers"></a>

[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) 인스턴스의 `synthesizer` 속성을 사용하여 CDK 스택 합성을 구성합니다. 이 속성은 CDK 스택이 어떻게 합성될지 지정합니다. [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) 또는 [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)를 구현하는 클래스의 인스턴스를 제공합니다. 해당 메서드는 스택이 합성될 때 또는 자산이 스택에 추가될 때마다 간접적으로 호출됩니다. 다음은 스택 내에서 이 속성을 사용하는 기본 예입니다.

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

`App` 인스턴스의 `defaultStackSynthesizer` 속성을 사용하여 CDK 앱의 모든 CDK 스택에 대해 신디사이저를 구성할 수도 있습니다.

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

기본적으로 AWS CDK는 ` [`DefaultStackSynthesizer](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.DefaultStackSynthesizer.html) `를 사용합니다. 신디사이저를 구성하지 않으면 이 신디사이저가 사용됩니다.

부트스트랩 스택 또는 템플릿을 변경하는 등 부트스트랩을 수정하지 않으면 스택 합성을 수정할 필요가 없습니다. 신디사이저를 제공할 필요도 없습니다. CDK는 기본 `DefaultStackSynthesizer` 클래스를 사용하여 부트스트랩 스택과 제대로 상호 작용하도록 CDK 스택 합성을 구성합니다.

## CDK 스택을 합성하는 방법
<a name="configure-synth-stack"></a>

CDK 스택을 합성하려면 AWS Command Line Interface(AWS CDK CLI) `cdk synth` 명령을 사용합니다. 이 명령과 함께 사용할 수 있는 옵션을 포함하여 이 명령에 대한 자세한 내용은 [cdk synthesize](ref-cli-cmd-synth.md)를 참조하세요.

CDK 앱에 스택이 하나만 포함되어 있거나 모든 스택을 합성하려는 경우 CDK 스택 이름을 인수로 제공할 필요가 없습니다. 기본적으로 CDK CLI는 CDK 스택을 AWS CloudFormation 템플릿으로 합성합니다. 각 스택의 `json` 형식의 템플릿은 `cdk.out` 디렉터리에 저장됩니다. 앱에 스택이 하나만 포함되어 있으면 `yaml` 형식의 템플릿이 `stdout`에 출력됩니다. 다음은 예제입니다.

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

CDK 앱에 여러 스택이 포함된 경우 스택의 논리적 ID를 제공하여 단일 스택을 합성할 수 있습니다. 다음은 예제입니다.

```
$ cdk synth MyStackName
```

스택을 합성하지 않고 `cdk deploy`를 실행하면 CDK CLI가 배포 전에 자동으로 스택을 합성합니다.

## 기본적으로 합성이 작동하는 방식
<a name="how-synth-default"></a><a name="how-synth-default-logical-ids"></a>

 **AWS CloudFormation 템플릿에서 생성된 논리적 ID**   
CDK 스택을 합성하여 CloudFormation 템플릿을 생성하는 경우 다음 소스에서 `construct-pathconstruct-IDunique-hash` 형식으로 논리적 ID가 생성됩니다.  
+  **구문 경로** - CDK 앱의 구문에 대한 전체 경로입니다. 이 경로는 L1 구문의 ID(항상 `Resource` 또는 `Default`)와 해당 구문이 속한 최상위 스택의 ID를 제외합니다.
+  **구문 ID** - 구문을 인스턴스화할 때 두 번째 인수로 제공하는 ID입니다.
+  **고유 해시** - AWS CDK는 일관적 해싱 알고리즘을 사용하여 8자의 고유 해시를 생성합니다. 이 고유한 해시는 템플릿의 논리적 ID 값이 서로 고유한지 확인하는 데 도움이 됩니다. 이 해시 생성의 일관적 동작은 합성을 수행할 때마다 각 구문에 대해 생성된 논리적 ID 값이 동일하게 유지되도록 합니다. 해시 값은 구문의 ID 또는 경로와 같은 특정 구문 값을 수정하는 경우에만 변경됩니다.

  논리적 ID의 최대 길이는 255자입니다. 따라서 AWS CDK는 해당 한도 내로 유지하기 위해 필요한 경우 구문 경로와 구문 ID를 잘라냅니다.

  다음은 Amazon Simple Storage Service(Amazon S3) 버킷을 정의하는 구문의 예입니다. 여기서는 구문의 ID로 `myBucket`을 전달합니다.  
**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\# ]

  ```
  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
  }
  
  // ...
  ```

------

  `cdk synth`를 실행하면 `myBucketunique-hash` 형식의 논리적 ID가 생성됩니다. 다음은 생성된 AWS CloudFormation 템플릿에서 이 리소스의 예입니다.

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

  다음은 Amazon S3 버킷을 정의하는 `Bar`라는 사용자 지정 구문의 예입니다. `Bar` 구문은 경로에 사용자 지정 구문 `Foo`를 포함합니다.  
**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 ]

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

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

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

------

  `cdk synth`를 실행하면 `FooBarBucketunique-hash` 형식의 논리적 ID가 생성됩니다. 다음은 생성된 AWS CloudFormation 템플릿에서 이 리소스의 예입니다.

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

## CDK 스택 합성 사용자 지정
<a name="bootstrapping-custom-synth"></a>

기본 CDK 합성 동작이 필요에 맞지 않는 경우 CDK 합성을 사용자 지정할 수 있습니다. 이렇게 하려면 `DefaultStackSynthesizer`를 수정하거나, 사용 가능한 다른 기본 제공 신디사이저를 사용하거나, 신디사이저를 직접 생성합니다. 지침은 [CDK 스택 합성 사용자 지정](customize-synth.md)을 참조하세요.