<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Daria Globa on Medium]]></title>
        <description><![CDATA[Stories by Daria Globa on Medium]]></description>
        <link>https://medium.com/@dariyagloba?source=rss-ea1300ca4f58------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OXukj46xx96m2ash</url>
            <title>Stories by Daria Globa on Medium</title>
            <link>https://medium.com/@dariyagloba?source=rss-ea1300ca4f58------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:46:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dariyagloba/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[CDK Construct Scope Explained]]></title>
            <link>https://medium.com/@dariyagloba/cdk-construct-scope-explained-923540699f6f?source=rss-ea1300ca4f58------2</link>
            <guid isPermaLink="false">https://medium.com/p/923540699f6f</guid>
            <category><![CDATA[cdk]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[cloud-infrastructure]]></category>
            <category><![CDATA[infrastruture-as-code]]></category>
            <category><![CDATA[aws-cdk-tutorial]]></category>
            <dc:creator><![CDATA[Daria Globa]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 04:38:02 GMT</pubDate>
            <atom:updated>2024-03-13T04:38:02.514Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://docs.aws.amazon.com/cdk/v2/guide/home.html">AWS Cloud Development Kit</a> (CDK) is a framework that facilitates the definition of infrastructure as code, transforming it into AWS CloudFormation templates for cloud provisioning.</p><p>As infrastructure is coded, it is essential to ensure well-defined, efficient, and maintainable source code and templates structure. In this article, we focus on the latter aspect — template structure.</p><h3>AWS CloudFormation Template</h3><p>The <em>CloudFormation Template</em> is a file (e.g. .json) that contains the definition of cloud resources. These templates are employed to replicate the infrastructure configuration in various accounts and/or regions. Each template corresponds precisely to one <em>CloudFormation Stack</em>, serving as a logical grouping of related resources.</p><p>When defining infrastructure, it becomes apparent how certain components are related to each other. Visualizing these relations results in something like a graph, or more specifically… a <em>tree.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*d_HTQ6N52KtfYbhWQTbLyA.png" /><figcaption>By the way, the CloudFormation console suggests displaying resources as a tree :)</figcaption></figure><p>Working with templates might be exciting (perhaps), but in the long run, managing large JSONs becomes a challenge. This is where CDK comes into play, offering a solution for template management via code, where resources are referred to as <em>Constructs</em>.</p><h3>CDK Construct</h3><p>In CDK, every element of infrastructure — be it a CloudFormation Stack or an IAM policy— is a <a href="https://docs.aws.amazon.com/cdk/v2/guide/constructs.html"><em>Construct</em></a>. There are three types (levels) of CDK Constructs:</p><ul><li>L1 — can be called <em>Foundational — </em>represent a direct mapping of CloudFormation resources to CDK constructs. Such constructs have Cfn prefix in their names.</li><li>L2 — can be called <em>L1-wrappers —</em> are constructs that encapsulate L1 resources adding intuitive API and pre-configured parameters.</li><li>L3 — can be called <em>Custom Containers —</em> are sets of resources grouped for a specific purpose, for example, to represent a flow or task.</li></ul><h4>Construct Scope</h4><p>Let’s take a look at the definition of the class<strong> </strong><a href="https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html#class-construct"><em>Construct</em></a><strong> </strong>in the CDK library<strong>, </strong>focusing specifically on the way it gets initialized:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*lREk5NsB5UN9wvJY8Uyqyg.png" /><figcaption>&lt;a href=”<a href="https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html#class-construct">https://docs.aws.amazon.com/cdk/api/v2/docs/constructs.Construct.html#class-construct</a>&quot;&gt;Official documentation&lt;/a&gt;</figcaption></figure><p>The first parameter of the constructor — scope — is of type <em>Construct</em>, meaning that the value can be any Construct. It acts as a <em>container </em>for a given component.</p><blockquote>This is what makes <strong>Construct Scope</strong> so crucial — with it the definition of CloudFormation Templates becomes logical and well-structured.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*APeykOU-4Eas3ELdzs5WgA.png" /><figcaption><strong>CDK Constructs Encapsulation</strong></figcaption></figure><h3>Show, don’t tell!</h3><p>In order to see how Construct Scope works, let’s create a stack called AppStack. The stack defines an SQS Queue and a Lambda function consuming events from it.</p><p><strong>Step 1</strong>. Create AppStack with a queue and a consumer.</p><pre>// file app-stack.ts<br>import { Stack, StackProps } from &#39;aws-cdk-lib&#39;;<br>import * as sqs from &#39;aws-cdk-lib/aws-sqs&#39;;<br>import * as lambda from &#39;aws-cdk-lib/aws-lambda&#39;;<br>import * as lambdaEventSources from &#39;aws-cdk-lib/aws-lambda-event-sources&#39;;<br>import { Construct } from &#39;constructs&#39;;<br><br>export class AppStack extends Stack {<br>  constructor(scope: Construct, id: string, props: StackProps) {<br>    super(scope, id, props);<br><br>    // define SQS queue<br>    const sqsQueue = new sqs.Queue(this, &#39;DemoSqsQueue&#39;, {<br>      queueName: &#39;demo-sqs-queue&#39;,<br>    });<br><br>    // define Lambda function, consumer<br>    const lambdaFunction = new lambda.Function(this, &#39;DemoSqsConsumer&#39;, {<br>      code: lambda.Code.fromAsset(&#39;./src&#39;),<br>      handler: &#39;index.handler&#39;,<br>      functionName: &#39;DemoSqsConsumer&#39;,<br>      runtime: lambda.Runtime.NODEJS_18_X,<br>    });<br><br>    // define Lambda Event Source to tie up Lambda and SQS Queue<br>    const eventSource = new lambdaEventSources.SqsEventSource(sqsQueue);<br>    lambdaFunction.addEventSource(eventSource);<br>  }<br>}<br><br>// file app.ts<br>import { AppStack } from &#39;./app-stack&#39;;<br>import * as cdk from &#39;aws-cdk-lib&#39;;<br><br>export const app = new cdk.App();<br><br>new AppStack(app, &#39;AppStack&#39;, {});</pre><p><strong>Step 2.</strong> Deploy AppStack and take a look into the resource tree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*wU_aKTFmKRAdESvkaiPe6w.png" /><figcaption>AppStack resource tree with the only consumer. Note, all resources are in the scope of the stack</figcaption></figure><p>The resources tree includes DemoSqsQueueand DemoSqsConsumer, with both resources belonging to the scope of the stack. While the relationships of DemoSqsConsumer&#39;s components (ServiceRole and SqsEventSource) are clear, the connection between DemoSqsQueue and DemoSqsConsumer isn’t as evident.</p><p>At this point, the stack definition isn’t perfect, but still simple. However…</p><p>Consider a scenario where <em>another</em> Lambda consumer for the same queue is needed. Given the CDK’s emphasis on code reusability, the initial inclination might be to copy and paste the stack constructor’s code and redeploy the App.</p><p>This strategy results in cumbersome code and a messy resource tree (as illustrated below). Moreover, detecting relationships among DemoSqsQueue, DemoSqsConsumer and DemoSqsConsumer2 is hardly possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*a8__Qm-DU20qOqhnFOoyEw.png" /><figcaption>AppStack resource tree with two identical consumers. Note, all resources are in the scope of the stack</figcaption></figure><p><strong>Step 3. </strong>Introduce SqsConsumer construct.</p><p>CDK’s approach to Infrastructure as Code (IaC) allows to define a <em>custom</em> construct representing a queue consumer — SqsConsumer. The construct will encapsulate all required components (such as Lambda function and LambdaEventSource) within its scope.</p><pre>// file sqs-consumer.ts<br>import { Construct } from &#39;constructs&#39;;<br>import * as lambda from &#39;aws-cdk-lib/aws-lambda&#39;;<br>import * as lambdaEventSources from &#39;aws-cdk-lib/aws-lambda-event-sources&#39;;<br>import * as sqs from &#39;aws-cdk-lib/aws-sqs&#39;;<br><br>export type SqsConsumerProps = {<br>  sqsQueue: sqs.Queue;  // reference to SQS queue<br>  consumerName: string; // used as Lambda function name<br>};<br><br>export class SqsConsumer extends Construct {<br>  readonly lambdaFunction: lambda.Function;<br><br>  constructor(scope: Construct, id: string, props: SqsConsumerProps) {<br>    // NOTE: scope is a parent resource (e.g. AppStack) of the current instance  <br>    super(scope, id); <br><br>    // define Lambda function<br>    // NOTE: scope of the lambda resource is &#39;this&#39; construct<br>    this.lambdaFunction = new lambda.Function(this, &#39;Lambda&#39;, {<br>      code: lambda.Code.fromAsset(&#39;./src&#39;),<br>      handler: &#39;index.handler&#39;,<br>      functionName: props.consumerName,<br>      runtime: lambda.Runtime.NODEJS_18_X,<br>    });<br><br>    // define Lambda Event Source to tie up Lambda and SQS Queue<br>    const eventSource = new lambdaEventSources.SqsEventSource(props.sqsQueue);<br>    this.lambdaFunction.addEventSource(eventSource);<br>  }<br>}</pre><p>With the introduction of the new construct, the stack’s definition becomes more concise:</p><pre>// file app-stack.ts<br>import { Stack, StackProps } from &#39;aws-cdk-lib&#39;;<br>import * as sqs from &#39;aws-cdk-lib/aws-sqs&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import { SqsConsumer } from &#39;./sqs-consumer&#39;;<br><br>export class AppStack extends Stack {<br>  constructor(scope: Construct, id: string, props: StackProps) {<br>    super(scope, id, props);<br><br>    // define SQS queue<br>    const sqsQueue = new sqs.Queue(this, &#39;DemoSqsQueue&#39;, {<br>      queueName: &#39;demo-sqs-queue&#39;,<br>    });<br><br>    // define SqsConsumers<br>    new SqsConsumer(this, &#39;DemoConsumer1&#39;, { sqsQueue, consumerName: &#39;DemoSqsConsumer1&#39; });<br>    new SqsConsumer(this, &#39;DemoConsumer2&#39;, { sqsQueue, consumerName: &#39;DemoSqsConsumer2&#39; });<br>  }<br>}</pre><p>In this step, the definition of the SqsConsumer allows to reuse the code written <em>once</em> and define as many different event handlers as needed.</p><p>However, after deploying the stack, its structure remains the same and the relationships between the queue and its consumers remain unclear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*G4fzwXUB2SeKrmhc0veRBg.png" /></figure><p><strong>Step 4.</strong> Fix the scope of the SqsConsumers.</p><p>To enhance the clarity of AppStack&#39;s resource tree, it would be better to group the consumers and the queue. Two options are available for achieving this:</p><ol><li>Define <em>another</em> custom construct, e.g. Sqs, with a queue and a list of SqsConsumers. The scope of the resource might be this, signifying that the queue and the handlers belong to the scope of an Sqs instance.</li><li>Adjust the scope value of SqsConsumers in the current design: instead of placing the consumers within the scope of AppStack, the queue from the props can become the scope.</li></ol><p>Both approaches have their advantages and offer convenience. For now, the second option is chosen:</p><pre>// file sqs-consumer.ts<br>import { Construct } from &#39;constructs&#39;;<br>import * as lambda from &#39;aws-cdk-lib/aws-lambda&#39;;<br>import * as lambdaEventSources from &#39;aws-cdk-lib/aws-lambda-event-sources&#39;;<br>import * as sqs from &#39;aws-cdk-lib/aws-sqs&#39;;<br><br>export type SqsConsumerProps = {<br>  sqsQueue: sqs.Queue;<br>  consumerName: string;<br>};<br><br>export class SqsConsumer extends Construct {<br>  readonly lambdaFunction: lambda.Function;<br><br>  // NOTE: scope parameter is removed<br>  constructor(id: string, props: SqsConsumerProps) {<br>    // NOTE: instead of AppStack&#39;s scope, SQS queue becomes a scope<br>    super(props.sqsQueue, id);<br>    <br>    // no changes<br>    ...<br>  }<br>}</pre><p>After making adjustments, the AppStack definition becomes:</p><pre>import { Stack, StackProps } from &#39;aws-cdk-lib&#39;;<br>import * as sqs from &#39;aws-cdk-lib/aws-sqs&#39;;<br>import { Construct } from &#39;constructs&#39;;<br>import { SqsConsumer } from &#39;./sqs-consumer&#39;;<br><br>export class AppStack extends Stack {<br>  constructor(scope: Construct, id: string, props: StackProps) {<br>    super(scope, id, props);<br><br>    // define SQS queue<br>    const sqsQueue = new sqs.Queue(this, &#39;DemoSqsQueue&#39;, {<br>      queueName: &#39;demo-sqs-queue&#39;,<br>    });<br><br>    // define SqsConsumers<br>    // NOTE: first parameter of the constructor is not required anymore<br>    new SqsConsumer(&#39;DemoConsumer1&#39;, { sqsQueue, consumerName: &#39;DemoSqsConsumer1&#39; });<br>    new SqsConsumer(&#39;DemoConsumer2&#39;, { sqsQueue, consumerName: &#39;DemoSqsConsumer2&#39; });<br>  }<br>}</pre><p>And finally, after deploying the stack and examining the resource tree, it becomes evident that the stack contains an SQS queue and a set of consumers associated with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*JKU4psfFKiRPp2_SSERnbQ.png" /><figcaption>AppStack resource tree with an Sqs and its consumers</figcaption></figure><h3>Summary</h3><p>The CDK scope is a <em>tool</em> for grouping dependent and logically related resources. Application of this concept allows the construction of CloudFormation templates that are not only clear but also self-explanatory.</p><p>In the provided example, the stack complexity is relatively low, and the significance of scope usage might not be as apparent as it would be on larger stacks. Poorly managed resource scope can lead to templates with low readability, reusability, and maintainability.</p><p>Firstly, introducing the SqsConsumer construct has abstracted away the definition of interdependent Lambda function and LambdaEventSource. Secondly, the new construct has facilitated the creation of various SQS consumers. Finally, adjusting the scope has helped define the logical relationship between a queue and its consumers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=923540699f6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>