구성 라이브러리에서 구문 사용자 AWS 지정하기 - AWS Cloud Development Kit (AWS CDK) v2

AWS CDK v2 개발자 안내서입니다. 구형 CDK v1은 2022년 6월 1일에 유지 보수에 들어갔고 2023년 6월 1일에 지원이 종료되었습니다.

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

구성 라이브러리에서 구문 사용자 AWS 지정하기

이스케이프 해치, 원시 오버라이드, 사용자 지정 리소스를 통해 AWS 구성 라이브러리의 구성을 사용자 정의할 수 있습니다.

이스케이프 해치를 사용하세요.

AWS 구성 라이브러리는 다양한 추상화 수준의 구문을 제공합니다.

최상위 수준에서 보면 AWS CDK 애플리케이션과 그 안에 포함된 스택 자체가 전체 클라우드 인프라 또는 그 중 상당 부분을 추상화한 것입니다. 이를 파라미터화하여 다양한 환경이나 다양한 요구 사항에 맞게 배포할 수 있습니다.

추상화는 클라우드 애플리케이션을 설계하고 구현하기 위한 강력한 도구입니다. 를 AWS CDK 사용하면 추상화를 사용하여 구축할 수 있을 뿐만 아니라 새로운 추상화를 만들 수도 있습니다. 기존 오픈 소스 L2 및 L3 구문을 지침으로 사용하여 조직의 모범 사례와 의견을 반영하는 자체 L2 및 L3 구문을 구축할 수 있습니다.

완벽한 추상화는 없으며, 아무리 좋은 추상화라도 가능한 모든 사용 사례를 포괄할 수는 없습니다. 개발 중에 필요에 거의 맞는 구조를 찾을 수 있으며, 크든 작든 커스터마이징이 필요할 수도 있습니다.

이러한 이유로 에서는 구성 모델을 분리할 수 있는 방법을 AWS CDK 제공합니다. 여기에는 하위 수준의 추상화로 이동하거나 완전히 다른 모델로 이동하는 것도 포함됩니다. 이스케이프 해치를 사용하면 AWS CDK 패러다임에서 벗어나 필요에 맞게 사용자 정의할 수 있습니다. 그런 다음 변경 내용을 새 구조로 래핑하여 근본적인 복잡성을 추상화하고 다른 API 개발자에게 깔끔함을 제공할 수 있습니다.

다음은 이스케이프 해치를 사용할 수 있는 상황의 예시입니다.

  • 를 통해 AWS 서비스 기능을 사용할 수 AWS CloudFormation있지만 이에 대한 L2 구조는 없습니다.

  • 를 통해 AWS AWS CloudFormation서비스 기능을 사용할 수 있으며 서비스에 대한 L2 구문이 있지만 이러한 구조에는 아직 기능이 표시되지 않습니다. L2 구조는 CDK 팀에서 큐레이션하므로 새 기능에 바로 사용할 수 없을 수도 있습니다.

  • 이 기능은 아직 전혀 사용할 수 없습니다. AWS CloudFormation

    를 통해 AWS CloudFormation기능을 사용할 수 있는지 확인하려면 AWS 리소스 및 속성 유형 참조를 참조하십시오.

L1 구문을 위한 이스케이프 해치 개발

서비스에 L2 구문을 사용할 수 없는 경우 자동으로 생성된 L1 구문을 사용할 수 있습니다. 이러한 리소스는 로 Cfn 시작하는 이름으로 식별할 수 있습니다 (예: 또는). CfnBucket CfnRole AWS CloudFormation 동등한 리소스를 사용할 때와 똑같이 인스턴스화합니다.

예를 들어, 분석이 활성화된 상태에서 하위 수준 Amazon S3 버킷 L1을 인스턴스화하려면 다음과 같이 작성합니다.

TypeScript
new s3.CfnBucket(this, 'MyBucket', { analyticsConfigurations: [ { id: 'Config', // ... } ] });
JavaScript
new s3.CfnBucket(this, 'MyBucket', { analyticsConfigurations: [ { id: 'Config' // ... } ] });
Python
s3.CfnBucket(self, "MyBucket", analytics_configurations: [ dict(id="Config", # ... ) ] )
Java
CfnBucket.Builder.create(this, "MyBucket") .analyticsConfigurations(Arrays.asList(java.util.Map.of( // Java 9 or later "id", "Config", // ... ))).build();
C#
new CfnBucket(this, 'MyBucket', new CfnBucketProps { AnalyticsConfigurations = new Dictionary<string, string> { ["id"] = "Config", // ... } });

드물게 해당 클래스가 없는 리소스를 정의하려는 경우가 있을 수 있습니다. CfnXxx 리소스 사양에 아직 게시되지 않은 새 AWS CloudFormation 리소스 유형일 수 있습니다. 이런 경우에는 를 cdk.CfnResource 직접 인스턴스화하고 리소스 유형과 속성을 지정할 수 있습니다. 방법은 다음 예제와 같습니다.

TypeScript
new cdk.CfnResource(this, 'MyBucket', { type: 'AWS::S3::Bucket', properties: { // Note the PascalCase here! These are CloudFormation identifiers. AnalyticsConfigurations: [ { Id: 'Config', // ... } ] } });
JavaScript
new cdk.CfnResource(this, 'MyBucket', { type: 'AWS::S3::Bucket', properties: { // Note the PascalCase here! These are CloudFormation identifiers. AnalyticsConfigurations: [ { Id: 'Config' // ... } ] } });
Python
cdk.CfnResource(self, 'MyBucket', type="AWS::S3::Bucket", properties=dict( # Note the PascalCase here! These are CloudFormation identifiers. "AnalyticsConfigurations": [ { "Id": "Config", # ... } ] } )
Java
CfnResource.Builder.create(this, "MyBucket") .type("AWS::S3::Bucket") .properties(java.util.Map.of( // Map.of requires Java 9 or later // Note the PascalCase here! These are CloudFormation identifiers "AnalyticsConfigurations", Arrays.asList( java.util.Map.of("Id", "Config", // ... )))) .build();
C#
new CfnResource(this, "MyBucket", new CfnResourceProps { Type = "AWS::S3::Bucket", Properties = new Dictionary<string, object> { // Note the PascalCase here! These are CloudFormation identifiers ["AnalyticsConfigurations"] = new Dictionary<string, string>[] { new Dictionary<string, string> { ["Id"] = "Config" } } } });

L2 구문을 위한 이스케이프 해치를 개발하세요.

L2 구문에 기능이 없거나 문제를 해결하려는 경우 L2 구문으로 캡슐화된 L1 구문을 수정할 수 있습니다.

모든 L2 구문은 그 안에 해당하는 L1 구문을 포함합니다. 예를 들어, 상위 수준 Bucket 구문은 하위 수준 구문을 래핑합니다. CfnBucket 는 AWS CloudFormation 리소스에 직접 CfnBucket 대응되므로 이를 통해 사용할 수 있는 모든 기능이 노출됩니다. AWS CloudFormation

L1 구문에 액세스하는 기본 방법은 construct.node.defaultChild (Python:default_child) 를 사용하고 필요한 경우 올바른 유형으로 캐스팅한 다음 속성을 수정하는 것입니다. 다시 Bucket a를 예로 들어 보겠습니다.

TypeScript
// Get the CloudFormation resource const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; // Change its properties cfnBucket.analyticsConfiguration = [ { id: 'Config', // ... } ];
JavaScript
// Get the CloudFormation resource const cfnBucket = bucket.node.defaultChild; // Change its properties cfnBucket.analyticsConfiguration = [ { id: 'Config' // ... } ];
Python
# Get the CloudFormation resource cfn_bucket = bucket.node.default_child # Change its properties cfn_bucket.analytics_configuration = [ { "id": "Config", # ... } ]
Java
// Get the CloudFormation resource CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); cfnBucket.setAnalyticsConfigurations( Arrays.asList(java.util.Map.of( // Java 9 or later "Id", "Config", // ... ));
C#
// Get the CloudFormation resource var cfnBucket = (CfnBucket)bucket.Node.DefaultChild; cfnBucket.AnalyticsConfigurations = new List<object> { new Dictionary<string, string> { ["Id"] = "Config", // ... } };

이 객체를 사용하여 Metadata 및 와 같은 AWS CloudFormation 옵션을 변경할 수도 UpdatePolicy 있습니다.

TypeScript
cfnBucket.cfnOptions.metadata = { MetadataKey: 'MetadataValue' };
JavaScript
cfnBucket.cfnOptions.metadata = { MetadataKey: 'MetadataValue' };
Python
cfn_bucket.cfn_options.metadata = { "MetadataKey": "MetadataValue" }
Java
cfnBucket.getCfnOptions().setMetadata(java.util.Map.of( // Java 9+ "MetadataKey", "Metadatavalue"));
C#
cfnBucket.CfnOptions.Metadata = new Dictionary<string, object> { ["MetadataKey"] = "Metadatavalue" };

언이스케이프 해치를 사용하세요.

AWS CDK 또한 추상화 수준을 높일 수 있는 기능을 제공하는데, 이를 “이스케이프 해제” 해치라고 할 수 있습니다. 예를 들어 L1 구문이 있는 경우 새 L2 구문 (Bucket이 경우) 을 만들어 L1 구문을 래핑할 수 있습니다. CfnBucket

이 방법은 L1 리소스를 만들지만 L2 리소스가 필요한 구문과 함께 사용하려는 경우에 편리합니다. L1 구조에서는 사용할 수 .grantXxxxx() 없는 편리한 메서드를 사용하려는 경우에도 유용합니다.

L2 클래스의 정적 메서드 .fromCfnXxxxx() (예: Bucket.fromCfnBucket() Amazon S3 버킷) 를 사용하여 더 높은 추상화 수준으로 이동합니다. L1 리소스가 유일한 파라미터입니다.

TypeScript
b1 = new s3.CfnBucket(this, "buck09", { ... }); b2 = s3.Bucket.fromCfnBucket(b1);
JavaScript
b1 = new s3.CfnBucket(this, "buck09", { ...} ); b2 = s3.Bucket.fromCfnBucket(b1);
Python
b1 = s3.CfnBucket(self, "buck09", ...) b2 = s3.from_cfn_bucket(b1)
Java
CfnBucket b1 = CfnBucket.Builder.create(this, "buck09") // .... .build(); IBucket b2 = Bucket.fromCfnBucket(b1);
C#
var b1 = new CfnBucket(this, "buck09", new CfnBucketProps { ... }); var v2 = Bucket.FromCfnBucket(b1);

L1 구조에서 생성된 L2 구문은 L1 리소스를 참조하는 프록시 객체로서, 리소스 이름 또는 조회에서 생성되는 것과 유사합니다. ARNs 이러한 구문을 수정해도 최종 합성 AWS CloudFormation 템플릿에는 영향을 주지 않습니다 (하지만 L1 리소스가 있으므로 대신 수정할 수 있음). 프록시 오브젝트에 대한 자세한 내용은 을 참조하십시오. 계정의 리소스 참조 AWS

혼동을 피하려면 동일한 L1 구문을 참조하는 L2 구문을 여러 개 만들지 마십시오. 예를 들어 이전 섹션의 Bucket 방법을 사용하여 CfnBucket a에서 를 추출하는 경우 이를 사용하여 a를 Bucket.fromCfnBucket() 호출하여 두 번째 Bucket 인스턴스를 만들면 안 됩니다. CfnBucket 실제로는 예상대로 작동하지만 (하나만 AWS::S3::Bucket 합성됨) 코드를 유지 관리하기가 더 어려워집니다.

원시 오버라이드를 사용하세요.

L1 구문에 누락된 속성이 있는 경우 원시 재정의를 사용하여 모든 입력을 우회할 수 있습니다. 이렇게 하면 합성된 속성을 삭제할 수도 있습니다.

다음 예제와 같이 addOverride 메서드 (Python:add_override) 메서드 중 하나를 사용합니다.

TypeScript
// Get the CloudFormation resource const cfnBucket = bucket.node.defaultChild as s3.CfnBucket; // Use dot notation to address inside the resource template fragment cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); // use index (0 here) to address an element of a list cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); cfnBucket.addDeletionOverride('Properties.Tags.0'); // addPropertyOverride is a convenience function for paths starting with "Properties." cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); cfnBucket.addPropertyDeletionOverride('Tags.0');
JavaScript
// Get the CloudFormation resource const cfnBucket = bucket.node.defaultChild ; // Use dot notation to address inside the resource template fragment cfnBucket.addOverride('Properties.VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addDeletionOverride('Properties.VersioningConfiguration.Status'); // use index (0 here) to address an element of a list cfnBucket.addOverride('Properties.Tags.0.Value', 'NewValue'); cfnBucket.addDeletionOverride('Properties.Tags.0'); // addPropertyOverride is a convenience function for paths starting with "Properties." cfnBucket.addPropertyOverride('VersioningConfiguration.Status', 'NewStatus'); cfnBucket.addPropertyDeletionOverride('VersioningConfiguration.Status'); cfnBucket.addPropertyOverride('Tags.0.Value', 'NewValue'); cfnBucket.addPropertyDeletionOverride('Tags.0');
Python
# Get the CloudFormation resource cfn_bucket = bucket.node.default_child # Use dot notation to address inside the resource template fragment cfn_bucket.add_override("Properties.VersioningConfiguration.Status", "NewStatus") cfn_bucket.add_deletion_override("Properties.VersioningConfiguration.Status") # use index (0 here) to address an element of a list cfn_bucket.add_override("Properties.Tags.0.Value", "NewValue") cfn_bucket.add_deletion_override("Properties.Tags.0") # addPropertyOverride is a convenience function for paths starting with "Properties." cfn_bucket.add_property_override("VersioningConfiguration.Status", "NewStatus") cfn_bucket.add_property_deletion_override("VersioningConfiguration.Status") cfn_bucket.add_property_override("Tags.0.Value", "NewValue") cfn_bucket.add_property_deletion_override("Tags.0")
Java
// Get the CloudFormation resource CfnBucket cfnBucket = (CfnBucket)bucket.getNode().getDefaultChild(); // Use dot notation to address inside the resource template fragment cfnBucket.addOverride("Properties.VersioningConfiguration.Status", "NewStatus"); cfnBucket.addDeletionOverride("Properties.VersioningConfiguration.Status"); // use index (0 here) to address an element of a list cfnBucket.addOverride("Properties.Tags.0.Value", "NewValue"); cfnBucket.addDeletionOverride("Properties.Tags.0"); // addPropertyOverride is a convenience function for paths starting with "Properties." cfnBucket.addPropertyOverride("VersioningConfiguration.Status", "NewStatus"); cfnBucket.addPropertyDeletionOverride("VersioningConfiguration.Status"); cfnBucket.addPropertyOverride("Tags.0.Value", "NewValue"); cfnBucket.addPropertyDeletionOverride("Tags.0");
C#
// Get the CloudFormation resource var cfnBucket = (CfnBucket)bucket.node.defaultChild; // Use dot notation to address inside the resource template fragment cfnBucket.AddOverride("Properties.VersioningConfiguration.Status", "NewStatus"); cfnBucket.AddDeletionOverride("Properties.VersioningConfiguration.Status"); // use index (0 here) to address an element of a list cfnBucket.AddOverride("Properties.Tags.0.Value", "NewValue"); cfnBucket.AddDeletionOverride("Properties.Tags.0"); // addPropertyOverride is a convenience function for paths starting with "Properties." cfnBucket.AddPropertyOverride("VersioningConfiguration.Status", "NewStatus"); cfnBucket.AddPropertyDeletionOverride("VersioningConfiguration.Status"); cfnBucket.AddPropertyOverride("Tags.0.Value", "NewValue"); cfnBucket.AddPropertyDeletionOverride("Tags.0");

사용자 지정 리소스 사용

이 기능을 사용할 수 없고 직접 API 통화를 AWS CloudFormation통해서만 사용할 수 있는 경우 필요한 전화를 걸 수 있는 AWS CloudFormation 사용자 지정 리소스를 작성해야 합니다. API 를 사용하여 사용자 지정 리소스를 작성하고 이를 일반 구성 인터페이스로 래핑할 수 있습니다. AWS CDK 구문을 사용하는 소비자의 입장에서 보면 그 경험이 자연스러워 보일 것입니다.

사용자 지정 리소스를 구축하려면 CREATE 리소스의UPDATE,, 수명 주기 이벤트에 응답하는 Lambda 함수를 작성해야 합니다. DELETE 사용자 지정 리소스에서 API 호출을 한 번만 해야 하는 경우 사용을 고려해 보십시오. AwsCustomResource 이렇게 하면 AWS CloudFormation 배포 중에 임의의 SDK 호출을 수행할 수 있습니다. 그렇지 않으면 필요한 작업을 수행하도록 Lambda 함수를 직접 작성해야 합니다.

주제가 너무 광범위해서 여기서 완전히 다룰 수 없지만 다음 링크를 통해 시작할 수 있습니다.