<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Mikaeel Khalid</title>
    <description>The latest articles on Forem by Mikaeel Khalid (@mikaeelkhalid).</description>
    <link>https://forem.com/mikaeelkhalid</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1184385%2Fe0f9ad80-890d-4e68-9801-4e6b4d53a1ae.png</url>
      <title>Forem: Mikaeel Khalid</title>
      <link>https://forem.com/mikaeelkhalid</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/mikaeelkhalid"/>
    <language>en</language>
    <item>
      <title>What is Context and its Significance in AWS CDK</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Fri, 15 Dec 2023 15:29:47 +0000</pubDate>
      <link>https://forem.com/aws-builders/what-is-context-and-its-significance-in-aws-cdk-4d6e</link>
      <guid>https://forem.com/aws-builders/what-is-context-and-its-significance-in-aws-cdk-4d6e</guid>
      <description>&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjy43kughpfcl2uk5stji.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjy43kughpfcl2uk5stji.jpeg" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Amazon Web Services Cloud Development Kit (AWS CDK) is a powerful infrastructure-as-code (IaC) framework that allows developers to define cloud infrastructure using familiar programming languages. One essential concept within AWS CDK that plays a crucial role in configuring and customizing your infrastructure is "context." In this blog post, we will delve into the significance of context in AWS CDK and how it contributes to the flexibility and scalability of your cloud applications.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Context in AWS CDK&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;In AWS CDK, context refers to the external input provided during the synthesis phase of your application. This external input can be environmental variables, resource-specific configurations, or any changing parameter based on the deployment environment. Context allows you to dynamically adjust certain values in your CDK application without modifying the source code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Using Context at the App Level
&lt;/h3&gt;

&lt;p&gt;In this example we will &lt;strong&gt;set the context at our CDK App level&lt;/strong&gt; :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Stack, StackProps, App } from 'aws-cdk-lib';export class MyCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); console.log('accessing context here ', this.node.tryGetContext('fromApp')); }}const app = new App({ // setting context in our cdk.App context: { fromApp: {name: 'Mikaeel', country: 'BE'}, },});const myStack = new MyCdkStack(app, 'my-cdk-stack', { stackName: `my-cdk-stack`, env: { region: process.env.CDK_DEFAULT_REGION, account: process.env.CDK_DEFAULT_ACCOUNT, },});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's synthesize our stack and look at the output:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk synth
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We can see the output from the &lt;code&gt;console.log&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ name: 'Mikaeel', country: 'BE' }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Context Managed by CDK
&lt;/h3&gt;

&lt;p&gt;Now take a quick look at how CDK uses context to cache certain values that belong to our deployment environment.&lt;/p&gt;

&lt;p&gt;If we open the &lt;code&gt;cdk.context.json&lt;/code&gt; file in the root directory of our CDK project, we can see that it's empty.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's add a simple &lt;code&gt;console.log&lt;/code&gt; call and print the availability zones that belong to the region our stack is configured for:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Stack, StackProps, App } from 'aws-cdk-lib';export class MyCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); console.log('context passed in App here ', this.node.tryGetContext('fromApp')); // printing the availability zones console.log(Stack.of(this).availabilityZones); }}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now synthesize our stack with:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk synth
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If we now open the &lt;code&gt;cdk.context.json&lt;/code&gt; file in the root of our project we'll see that CDK has cached the availability zones that correspond to our stack's region:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ "availability-zones:account=123456789:region=us-east-1": ["us-east-1a", "us-east-1b", "us-east-1c", "us-east-1d", "us-east-1e"]}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;cdk.context.json&lt;/code&gt; file is where CDK caches values related to our deployment environment.&lt;/p&gt;

&lt;p&gt;There is also a &lt;strong&gt;cdk.json&lt;/strong&gt; file in the root directory of a CDK project.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;cdk.json&lt;/code&gt; file looks similar to the following:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ "app": "npx ts-node --prefer-ts-exts bin/aws-cdk-group-chat-app.ts", "context": { "@aws-cdk/aws-lambda:recognizeLayerVersion": true, "@aws-cdk/core:checkSecretUsage": true, "@aws-cdk/core:target-partitions": ["aws", "aws-cn"] }}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Where the &lt;code&gt;app&lt;/code&gt; key indicates to the CDK CLI how to run our CDK code, which is mostly a compilation step that compiles the typescript code to javascript.&lt;/p&gt;

&lt;p&gt;Then we have the &lt;code&gt;context&lt;/code&gt; key, which is composed of feature flags.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;These feature flags enable us to opt in or out of breaking changes. Their names start with the name of the package that introduces the breaking change i.e:&lt;/strong&gt; &lt;code&gt;@aws-cdk/aws-lambda&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;💡&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;If we want to roll back to the previous behavior of AWS CDK what certain feature is concerned, we have to set the feature flag to&lt;/strong&gt; &lt;code&gt;false&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We can also use the &lt;code&gt;cdk.json&lt;/code&gt; file to pass in context into our CDK app, let's add another property to it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{ "app": "npx ts-node --prefer-ts-exts bin/aws-cdk-group-chat-app.ts", "context": { "@aws-cdk/aws-lambda:recognizeLayerVersion": true, "@aws-cdk/core:checkSecretUsage": true, "@aws-cdk/core:target-partitions": ["aws", "aws-cn"], // adding a bucket property as context "bucket": { "region": "us-east-1", "name": "my-s3-bucket" } }}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now let's access the bucket context in our CDK stack:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Stack, StackProps, App } from 'aws-cdk-lib';export class MyCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); console.log('from cdk.json ', this.node.tryGetContext('bucket')); }}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Let's synth our cdk stack:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk synth
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The output from the &lt;code&gt;console.log&lt;/code&gt; will look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; { "region": "us-east-1", "name": "my-s3-bucket" }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Setting Context using the CDK CLI
&lt;/h3&gt;

&lt;p&gt;The next option used for setting context in our CDK app is to use the &lt;a href="https://docs.aws.amazon.com/cdk/v2/guide/cli.html" rel="noopener noreferrer"&gt;&lt;strong&gt;CDK CLI&lt;/strong&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We can set context key-value pairs during synthesis.&lt;/p&gt;

&lt;p&gt;First, we'll access context values that we haven't yet set:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Stack, StackProps, App } from 'aws-cdk-lib';export class MyCdkStack extends Stack { constructor(scope: App, id: string, props?: StackProps) { super(scope, id, props); console.log('bucketName ', this.node.tryGetContext('bucketName')); console.log('region ', this.node.tryGetContext('region')); }}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now we'll synth the CDK application passing in the context values using the CLI:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk synth \ --context bucketName=myBucket \ --context region=us-east-1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The output from our &lt;code&gt;console.log&lt;/code&gt; statements will look like this.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;bucketName myBucketregion us-east-1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;💡&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;We can only pass&lt;/strong&gt; &lt;code&gt;string&lt;/code&gt; &lt;strong&gt;values when we set the context using the CDK CLI. If we have to pass an object, we have to pass it as a&lt;/strong&gt; &lt;code&gt;string&lt;/code&gt; &lt;strong&gt;and parse it in our application code.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If we have multiple CDK stacks and want to set different context values using the CDK CLI, we can prefix the key-value pairs with the &lt;strong&gt;stack name&lt;/strong&gt; , i.e.:&lt;/p&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk synth \ --context stack-name1:bucketName=myBucket \ --context stack-name2:bucketName=yourBucket&lt;br&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Conclusion&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Context is a combination of key-value pairs we can set and make available in our CDK application.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Context is similar to &lt;strong&gt;environment variables&lt;/strong&gt; , in that both are accessible in synthesis time, as opposed to &lt;strong&gt;CDK parameters&lt;/strong&gt; , which are only set at deployment time.&lt;/p&gt;

&lt;p&gt;The most common ways to set context are:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;At the CDK App level using the &lt;code&gt;context&lt;/code&gt; property&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In our &lt;code&gt;cdk.json&lt;/code&gt; file adding key-value pairs to the &lt;code&gt;context&lt;/code&gt; object&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Using the CDK CLI with the &lt;code&gt;--context&lt;/code&gt; flag&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In our CDK applications, we can access the context values with a call to&lt;code&gt;this.node.tryGetContext('keyName')&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;💡&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;I believe it's good to set the context at the&lt;/strong&gt; &lt;code&gt;CDK App level&lt;/code&gt; &lt;strong&gt;, it's globally available, it's intuitive and we can set context values of any type.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Setting context using the &lt;code&gt;cdk.json&lt;/code&gt; file is too implicit and hidden.&lt;/p&gt;

&lt;p&gt;An alternative is using the CDK CLI, however, the CLI only allows us to pass in string values, so the most intuitive way is setting context at the &lt;code&gt;cdk.App&lt;/code&gt; level.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>awscdk</category>
      <category>iac</category>
      <category>context</category>
    </item>
    <item>
      <title>Automating AWS CodePipeline Notifications to Discord Using Lambda and Terraform</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Mon, 11 Dec 2023 16:44:25 +0000</pubDate>
      <link>https://forem.com/aws-builders/automating-aws-codepipeline-notifications-to-discord-using-lambda-and-terraform-36ic</link>
      <guid>https://forem.com/aws-builders/automating-aws-codepipeline-notifications-to-discord-using-lambda-and-terraform-36ic</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vRe8Y6rj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c0xp7lexjpx5m0cqslkh.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vRe8Y6rj--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c0xp7lexjpx5m0cqslkh.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In DevOps, continuous integration and delivery (CI/CD) pipelines are integral for efficient software development. AWS CodePipeline facilitates the orchestration of these pipelines, but keeping track of pipeline executions in real time can be challenging. This blog post will guide you through the process of automating notifications to a Discord channel using AWS Lambda whenever there is an update to a CodePipeline execution. The solution leverages serverless computing, AWS Lambda, and Infrastructure as Code (IaC) with Terraform for seamless deployment.&lt;/p&gt;

&lt;p&gt;💡 The &lt;strong&gt;GitHub&lt;/strong&gt; link to the complete code can be found at the end of the blog.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Kuoq2NCZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yjav6mtavi9ryiif8dhl.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Kuoq2NCZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yjav6mtavi9ryiif8dhl.jpg" alt="Image description" width="800" height="534"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Overview
&lt;/h2&gt;

&lt;p&gt;AWS CodePipeline is a fully managed CI/CD service, that streamlines the process of building, testing, and deploying code changes. However, being aware of pipeline status changes in real-time is crucial for efficient collaboration and issue resolution.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Setting Up Discord Integration
&lt;/h2&gt;

&lt;p&gt;Before diving into the technical details, you need to set up Discord integration. This involves creating a Discord webhook, which will be the communication link for posting messages to your desired Discord channel.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. AWS Lambda for CodePipeline Notifications
&lt;/h2&gt;

&lt;h3&gt;
  
  
  3.1 Understanding the Lambda Function Structure
&lt;/h3&gt;

&lt;p&gt;The heart of this solution is an AWS Lambda function written in Node.js. This function responds to CodePipeline state changes triggered by EventBridge, a serverless event bus. The Lambda function fetches details about the pipeline execution and formats a message to be posted in Discord.&lt;/p&gt;

&lt;h3&gt;
  
  
  3.2 Utilizing CodePipeline Helper Functions
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;codepipeline-helper.js&lt;/code&gt; file contains helper functions for interacting with AWS CodePipeline. It establishes a connection to CodePipeline, fetches pipeline execution details, and retrieves the current state of the pipeline.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// codepipeline-helper.js
require('dotenv').config();
const AWS = require('aws-sdk');

AWS.config.update({ region: process.env.REGION });
const codepipeline = new AWS.CodePipeline(process.env.REGION);
const PIPELINE_HISTORY = 'https://###REGION###.console.aws.amazon.com/codepipeline/home?region=###REGION####/view/###PIPELINE###/history';

module.exports.getPipelineExecutionDetails = (executionId, pipeline) =&amp;gt; {
  const promises = [];
  promises.push(getPipelineExecution(executionId, pipeline));
  promises.push(getPipelineState(pipeline));

  return Promise.all(promises).then(([execution, state]) =&amp;gt; {
    return {
      execution: execution,
      state: state,
      executionHistoryUrl: PIPELINE_HISTORY.replace(new RegExp('###REGION###', 'g'), process.env.REGION).replace(
        new RegExp('###PIPELINE###', 'g'),
        pipeline
      ),
    };
  });
};

// ... other functions like getPipelineExecution and getPipelineState
// The GitHub link to the complete code can be found at the end of the blog.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  3.3 Crafting Discord Messages with Discord Helper
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;discord-helper.js&lt;/code&gt; file is responsible for creating Discord messages based on the CodePipeline execution details. It extracts relevant information such as commit details, and stage statuses, and creates a formatted message ready for Discord.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// discord-helper.js
const CodePipelineHelper = require('./codepipeline-helper');
const Constants = require('./constants');
const AppName = process.env.DISCORD_CHANNEL ? process.env.DISCORD_CHANNEL : 'Github';

module.exports.createDiscordMessage = (codepipelineEventDetails) =&amp;gt; {
  return CodePipelineHelper.getPipelineExecutionDetails(
    codepipelineEventDetails['execution-id'],
    codepipelineEventDetails.pipeline
  ).then((pipelineDetails) =&amp;gt; {
    // get git info from github directly??? this might require authorization
    const gitCommitInfo = pipelineDetails.execution.pipelineExecution.artifactRevisions[0];

    // ... other code for creating Discord message
  });
};

// ... getColorByState function and other related functions
// The GitHub link to the complete code can be found at the end of the blog.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4. Terraform Infrastructure as Code (IaC)
&lt;/h2&gt;

&lt;p&gt;Terraform is employed to manage AWS resources in a declarative manner. The infrastructure is defined in the &lt;code&gt;main.tf&lt;/code&gt; file, specifying IAM roles, policies, Lambda functions, and EventBridge rules.&lt;/p&gt;

&lt;h3&gt;
  
  
  4.1 IAM Role and Policies
&lt;/h3&gt;

&lt;p&gt;IAM roles and policies are defined to grant necessary permissions to the Lambda function, allowing it to interact with CloudWatch Logs and CodePipeline.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# main.tf
resource "aws_iam_role" "lambda_role" {
  name = "${var.LAMBDA_APP_NAME}-codepipeline-discord-lambda-role"

  assume_role_policy = &amp;lt;&amp;lt;EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy" "lambda_role_policy" {
  name = "${var.LAMBDA_APP_NAME}-discord-codepipeline-lambda-role-policy"
  role = aws_iam_role.lambda_role.id

  policy = &amp;lt;&amp;lt;EOF
{
  "Version" : "2012-10-17",
  "Statement" : [{
      "Sid": "WriteLogsToCloudWatch",
      "Effect" : "Allow",
      "Action" : [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource" : "arn:aws:logs:*:*:*"
    }, {
      "Sid": "AllowAccesstoPipeline",
      "Effect" : "Allow",
      "Action" : [
        "codepipeline:GetPipeline",
        "codepipeline:GetPipelineState",
        "codepipeline:GetPipelineExecution",
        "codepipeline:ListPipelineExecutions",
        "codepipeline:ListActionTypes",
        "codepipeline:ListPipelines"
      ],
      "Resource" : "*"
    }
  ]
}
EOF
}

# The GitHub link to the complete code can be found at the end of the blog.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.2 Deploying Lambda Function with Terraform
&lt;/h3&gt;

&lt;p&gt;The Lambda function, defined in the &lt;code&gt;aws_lambda_function&lt;/code&gt; resource block is deployed with the associated IAM role and policies.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# main.tf
resource "aws_lambda_function" "lambda" {
  filename = data.archive_file.lambda_zip.output_path
  source_code_hash = data.archive_file.lambda_zip.output_base64sha256
  description = "Posts a message to Discord channel '${var.DISCORD_CHANNEL}' every time there is an update to codepipeline execution."
  function_name = "${var.LAMBDA_APP_NAME}-discord-codepipeline-lambda"
  role = aws_iam_role.lambda_role.arn
  handler = "handler.handle"
  runtime = "nodejs14.x"
  timeout = var.LAMBDA_TIMEOUT
  memory_size = var.LAMBDA_MEMORY_SIZE

  environment {
    variables = {
      "DISCORD_WEBHOOK_URL" = var.DISCORD_WEBHOOK_URL
      "DISCORD_CHANNEL" = var.DISCORD_CHANNEL
      "RELEVANT_STAGES" = var.RELEVANT_STAGES
      "REGION" = var.REGION
    }
  }
}

# ... other resources like aws_lambda_alias, aws_cloudwatch_event_rule, etc.
# The GitHub link to the complete code can be found at the end of the blog.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  4.3 EventBridge Rule for CodePipeline State Changes
&lt;/h3&gt;

&lt;p&gt;An EventBridge rule is established to capture state changes in all CodePipelines. This rule triggers the Lambda function whenever a relevant event occurs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# main.tf
resource "aws_cloudwatch_event_rule" "pipeline_state_update" {
  name = "${var.LAMBDA_APP_NAME}-discord-codepipeline-rule"
  description = "capture state changes in all CodePipelines"

  event_pattern = &amp;lt;&amp;lt;PATTERN
  {
    "detail-type": [
        "CodePipeline Pipeline Execution State Change"
    ],
    "source": [
        "aws.codepipeline"
    ]
 }
PATTERN
}

resource "aws_lambda_permission" "allow_cloudwatch" {
  statement_id = "AllowExecutionFromCloudWatch"
  action = "lambda:InvokeFunction"
  function_name = aws_lambda_function.lambda.function_name
  principal = "events.amazonaws.com"
  source_arn = aws_cloudwatch_event_rule.pipeline_state_update.arn
  qualifier = aws_lambda_alias.lambda_alias.name
}

resource "aws_cloudwatch_event_target" "lambda_trigger" {
  rule = aws_cloudwatch_event_rule.pipeline_state_update.name
  arn = aws_lambda_alias.lambda_alias.arn
}

# The GitHub link to the complete code can be found at the end of the blog.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  5. Customization and Configuration
&lt;/h2&gt;

&lt;p&gt;This solution is designed to be adaptable to specific team needs. You can customize relevant stages to monitor, configure Lambda function parameters, and extend functionality as required.&lt;/p&gt;

&lt;h3&gt;
  
  
  5.1 Adapting Relevant Stages
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;constants.js&lt;/code&gt;, you can adjust the relevant stages based on your pipeline structure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// constants.js
const relevantStages = process.env.RELEVANT_STAGES || 'BUILD,DEPLOY';

module.exports.ACTION_LEVEL_STATES = {
  FAILED: 'FAILED',
  CANCELED: 'CANCELED',
  STARTED: 'STARTED',
  SUCCEEDED: 'SUCCEEDED',
};

module.exports.STAGES = {
  SOURCE: 'SOURCE',
  BUILD: 'BUILD',
  DEPLOY: 'DEPLOY',
};

module.exports.DISCORD_COLORS = {
  INFO: 3447003,
  WARNING: 15158332,
  SUCCESS: 3066993,
  ERROR: 10038562,
};

module.exports.RELEVANT_STAGES = relevantStages
  .split(',')
  .map((stage) =&amp;gt; module.exports.STAGES[stage.toUpperCase()])
  .filter((stage) =&amp;gt; stage != null);

// The GitHub link to the complete code can be found at the end of the blog.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5.2 Configuring Lambda Function Parameters
&lt;/h3&gt;

&lt;p&gt;In &lt;code&gt;variables.tf&lt;/code&gt;, you can configure parameters such as the Discord webhook URL, channel, AWS region, and more.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# variables.tf
variable "LAMBDA_APP_NAME" {
  description = "lambda function name."
  default = "cicd-channel"
}

variable "DISCORD_WEBHOOK_URL" {
  description = "webhook URL provided by Discord."
  default = "https://mikaeels.com" // replace with webhook URL provided by Discord
}

variable "DISCORD_CHANNEL" {
  description = "discord channel where messages are going to be posted."
  default = "#cicd"
}

variable "REGION" {
  description = "AWS deployment region."
  default = "eu-west-2"
}

variable "RELEVANT_STAGES" {
  description = "stages for which you want to get notified (ie. 'SOURCE,BUILD,DEPLOY'). Defaults to all)"
  default = "SOURCE,BUILD,DEPLOY"
}

variable "LAMBDA_MEMORY_SIZE" {
  default = "128"
}

variable "LAMBDA_TIMEOUT" {
  default = "10"
}

# The GitHub link to the complete code can be found at the end of the blog.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  5.3 Extending Functionality
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;discord-helper.js&lt;/code&gt; file can be extended to include additional details or integrations based on your requirements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// discord-helper.js
const CodePipelineHelper = require('./codepipeline-helper');
const Constants = require('./constants');
const AppName = process.env.DISCORD_CHANNEL ? process.env.DISCORD_CHANNEL : 'Github';

module.exports.createDiscordMessage = (codepipelineEventDetails) =&amp;gt; {
  return CodePipelineHelper.getPipelineExecutionDetails(
    codepipelineEventDetails['execution-id'],
    codepipelineEventDetails.pipeline
  ).then((pipelineDetails) =&amp;gt; {
    // get git info from github directly??? this might require authorization
    const gitCommitInfo = pipelineDetails.execution.pipelineExecution.artifactRevisions[0];

    // create discord fields per each stage
    const executionStages = pipelineDetails.state.stageStates.filter(
      (x) =&amp;gt; x.latestExecution.pipelineExecutionId === codepipelineEventDetails['execution-id']
    );

    const fields = executionStages.map((stage) =&amp;gt; {
      const actionState = stage.actionStates[0];
      switch (stage.stageName.toUpperCase()) {
        case Constants.STAGES.SOURCE:
          return {
            name: `Commit`,
            value: `[\`${gitCommitInfo.revisionId.substring(0, 10)}\`](${gitCommitInfo.revisionUrl}) - ${
              gitCommitInfo.revisionSummary
            }`,
            inline: false,
          };
        case Constants.STAGES.DEPLOY:
        case Constants.STAGES.BUILD:
          return {
            name: `${actionState.actionName}`,
            value: actionState.latestExecution.externalExecutionUrl
              ? `[${actionState.latestExecution.status}](${actionState.latestExecution.externalExecutionUrl})`
              : actionState.latestExecution.status,
            inline: true,
          };
        default:
          console.log(`Unknown stage: ${stage.stageName}`);
      }
    });

    const discordMessage = {
      username: `${AppName}`,
      avatar_url: 'https://gravatar.com/avatar/1fd3410d57f8b729ec89a431054cbf41?s=400&amp;amp;d=robohash&amp;amp;r=x',
      content: `Code Pipeline status updated: [${codepipelineEventDetails.pipeline}](${pipelineDetails.executionHistoryUrl})`,
      embeds: [
        {
          color: getColorByState(pipelineDetails.execution.pipelineExecution.status),
          fields: fields,
          footer: {
            text: 'With from CodePipeline 🚀',
          },
        },
      ],
      timestamp: new Date().toISOString,
    };

    return discordMessage;
  });
};

// states for action events in codepipeline
function getColorByState(state) {
  switch (state.toUpperCase()) {
    case Constants.ACTION_LEVEL_STATES.FAILED:
      return Constants.DISCORD_COLORS.ERROR;
    case Constants.ACTION_LEVEL_STATES.SUCCEEDED:
      return Constants.DISCORD_COLORS.SUCCESS;
    case Constants.ACTION_LEVEL_STATES.CANCELED:
      return Constants.DISCORD_COLORS.WARNING;
    case Constants.ACTION_LEVEL_STATES.STARTED:
    default:
      return Constants.DISCORD_COLORS.INFO;
  }
}

// The GitHub link to the complete code can be found at the end of the blog.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  6. Deployment
&lt;/h2&gt;

&lt;p&gt;Terraform is utilized to deploy the entire infrastructure to AWS.&lt;/p&gt;

&lt;p&gt;Initialize the Terraform environment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;terraform init

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Plan the deployment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;terraform plan

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Apply the configuration.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;terraform apply

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  7. Conclusion
&lt;/h2&gt;

&lt;p&gt;In conclusion, this comprehensive guide empowers you to automate CodePipeline notifications to Discord using AWS Lambda and Terraform. Following the provided references and step-by-step instructions can enhance collaboration, improve visibility, and respond promptly to changes in your CI/CD workflows. The combination of serverless computing, IaC, and effective Discord integration ensures a streamlined and efficient DevOps experience.&lt;/p&gt;

&lt;p&gt;Here's the &lt;strong&gt;GitHub&lt;/strong&gt; repo link to the complete code. 👇&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/mikaeelkhalid/aws-codepipeline-discord-notifier-terraform"&gt;https://github.com/mikaeelkhalid/aws-codepipeline-discord-notifier-terraform&lt;/a&gt;&lt;/p&gt;

</description>
      <category>aws</category>
      <category>terraform</category>
      <category>lambda</category>
      <category>discord</category>
    </item>
    <item>
      <title>Creating a CI/CD Pipeline for AWS Elastic Beanstalk with AWS CDK</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Sun, 29 Oct 2023 21:03:39 +0000</pubDate>
      <link>https://forem.com/aws-builders/creating-a-cicd-pipeline-for-aws-elastic-beanstalk-with-aws-cdk-2ag4</link>
      <guid>https://forem.com/aws-builders/creating-a-cicd-pipeline-for-aws-elastic-beanstalk-with-aws-cdk-2ag4</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--bLaJ0vWu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4d7aqu5oob3i8hrudnis.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--bLaJ0vWu--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4d7aqu5oob3i8hrudnis.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this blog, I will provide a comprehensive guide on how to set up a Continuous Integration/Continuous Deployment (CI/CD) pipeline for an AWS Elastic Beanstalk application using the AWS Cloud Development Kit (CDK). I will break down the code into smaller sections, explaining each part's purpose.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Project Structure and Setup&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The project is structured into three primary files:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;stacks/eb-codepipeline-stack.ts&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;config/config.yaml&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;bin/main.ts&lt;/code&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This organized structure makes it easier to manage the deployment process and its configurations.&lt;/p&gt;

&lt;p&gt;💡 The project &lt;strong&gt;GitHub&lt;/strong&gt; repo link can be found at the end of the blog.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;stacks/eb-codepipeline-stack.ts&lt;/code&gt;: This file contains the code to define the AWS infrastructure for your Elastic Beanstalk application and the CI/CD pipeline using AWS CDK.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;config/config.yaml&lt;/code&gt;: This file stores the configuration values for different environments, such as development (dev) and production (prod).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;bin/main.ts&lt;/code&gt;: This is the entry point for the CDK app, where we create the app and instantiate the CDK stack based on the environment specified.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now, let's dive into the details of the code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2: Elastic Beanstalk Configuration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;eb-codepipeline-stack.ts&lt;/code&gt; file, we start by configuring the Elastic Beanstalk environment. This is where your web application will be hosted. Let's break down the code:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 2.1: Asset Configuration&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const webAppZipArchive = new Asset(this, 'expressjs-app-zip', {
  path: `${__dirname}/../express-app`,
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we create an asset named 'expressjs-app-zip' from your application code, which is stored in the &lt;code&gt;'express-app'&lt;/code&gt; directory.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 2.2: Application Creation&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const app = new CfnApplication(this, 'eb-application', {
  applicationName: appName,
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We define the Elastic Beanstalk application by providing it with a name.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 2.3: Application Version Configuration&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const appVersionProps = new CfnApplicationVersion(this, 'eb-app-version', {
  applicationName: appName,
  sourceBundle: {
    s3Bucket: webAppZipArchive.s3BucketName,
    s3Key: webAppZipArchive.s3ObjectKey,
  },
});

appVersionProps.addDependency(app); // here we want to create app before its version

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we're creating a version of your Elastic Beanstalk application, capturing the code from an S3 bucket and associating it with the application named &lt;code&gt;'appName'&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;appVersionProps.addDependency(app)&lt;/code&gt; line ensures that the Elastic Beanstalk Application is created before its associated Application Version.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 2.4: Create instance profile&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; const instanceRole = new Role(
      this,
      `${appName}-aws-elasticbeanstalk-ec2-role`,
      {
        assumedBy: new ServicePrincipal('ec2.amazonaws.com'),
      }
    );

    const managedPolicy = ManagedPolicy.fromAwsManagedPolicyName(
      'AWSElasticBeanstalkWebTier'
    );

    instanceRole.addManagedPolicy(managedPolicy);

    const instanceProfileName = `${appName}-instance-profile`;

    const instanceProfile = new CfnInstanceProfile(this, instanceProfileName, {
      instanceProfileName: instanceProfileName,
      roles: [instanceRole.roleName],
    });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we're creating an instance profile for the Elastic Beanstalk application with an AWS-managed policy &lt;code&gt;'AWSElasticBeanstalkWebTier'&lt;/code&gt; to ensure it has proper permissions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 2.5: Create Option Setting properties&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const optionSettingProperties: CfnEnvironment.OptionSettingProperty[] = [
      {
        namespace: 'aws:autoscaling:launchconfiguration',
        optionName: 'IamInstanceProfile',
        value: instanceProfileName,
      },
      {
        namespace: 'aws:autoscaling:asg',
        optionName: 'MinSize',
        value: minSize || DEFAULT_SIZE,
      },
      {
        namespace: 'aws:autoscaling:asg',
        optionName: 'MaxSize',
        value: maxSize || DEFAULT_SIZE,
      },
      {
        namespace: 'aws:ec2:instances',
        optionName: 'InstanceTypes',
        value: instanceTypes || DEFAULT_INSTANCE_TYPE,
      },
    ];

// here we're adding ssl properties if ARN defined
if (sslCertificateArn) {
      optionSettingProperties.push(
        {
          namespace: 'aws:elasticbeanstalk:environment',
          optionName: 'LoadBalancerType',
          value: 'application',
        },
        {
          namespace: 'aws:elbv2:listener:443',
          optionName: 'ListenerEnabled',
          value: 'true',
        },
        {
          namespace: 'aws:elbv2:listener:443',
          optionName: 'SSLCertificateArns',
          value: sslCertificateArn,
        },
        {
          namespace: 'aws:elbv2:listener:443',
          optionName: 'Protocol',
          value: 'HTTPS',
        }
      );
    }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we're setting an Option Setting Properties for the Elastic Beanstalk application environment.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 2.6: Create ElasticBeanstalk Environment&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const ebEnvironment = new CfnEnvironment(this, 'eb-environment', {
      environmentName: envName,
      applicationName: appName,
      solutionStackName: '64bit Amazon Linux 2 v5.8.0 running Node.js 18',
      optionSettings: optionSettingProperties,
      versionLabel: appVersionProps.ref,
    });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we're creating an Elastic Beanstalk environment for hosting an application, specifying its name, associated application, runtime stack, and various configurations like instance types and SSL certificates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 2.7: Output ElasticBeanstalk Environment (ALB) endpoint URL&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;new CfnOutput(this, 'eb-url-endpoint', {
      value: ebEnvironment.attrEndpointUrl,
      description: 'URL endpoint for the elasticbeanstalk',
    });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code sets up an application version, pointing to the asset created earlier, which represents your application code.&lt;/p&gt;

&lt;p&gt;The code also includes creating an instance profile, defining environment options, handling SSL certificates if provided, and outputting URL.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: CodePipeline Configuration&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Moving on to the CI/CD pipeline configuration. This code sets up a CodePipeline with Source, Build, and Deployment stages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 3.1: Source Stage Configuration&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sourceOutput = new Artifact();
const sourceAction = new GitHubSourceAction({
  actionName: 'GitHub', // we're using github here, can be codecommit, bitbucket etc
  owner: githubRepoOwner,
  repo: githubRepoName,
  branch: branch,
  oauthToken: SecretValue.secretsManager(githubAccessTokenName),
  output: sourceOutput,
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we configure the source stage. It uses a GitHub repository as the source, which can be triggered based on the specified branch.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 3.2: Build Stage Configuration&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const buildOutput = new Artifact();
const buildProject = new Project(this, 'codebuild-project', {
  buildSpec: BuildSpec.fromObject({
    version: '0.2',
    phases: {
      install: {
        commands: ['npm install'],
      },
      build: {
        commands: ['npm run build'],
      },
    },
    artifacts: {
      files: ['**/*'],
    },
  }),
  environment: {
    buildImage: LinuxBuildImage.STANDARD_5_0,
  },
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this section, we set up the Build stage. It defines a CodeBuild project with build specifications, including installing dependencies and building the application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Section 3.3: Deployment Stage Configuration&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const deployAction = new ElasticBeanstalkDeployAction({
  actionName: 'ElasticBeanstalk',
  applicationName: appName,
  environmentName: envName || 'eb-nodejs-app-environment',
  input: projectType === 'ts' ? buildOutput : sourceOutput,
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The deployment stage is configured to deploy the application to Elastic Beanstalk. It depends on whether your project is TypeScript or JavaScript.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Pipeline (CodePipeline) Creation&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Finally, we create the pipeline by specifying the order of stages based on the project type:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const jsProject = [
  { stageName: 'Source', actions: [sourceAction] },
  { stageName: 'Deploy', actions: [deployAction] },
];

const tsProject = [
  { stageName: 'Source', actions: [sourceAction] },
  { stageName: 'Build', actions: [buildAction] },
  { stageName: 'Deploy', actions: [deployAction] },
];

const stages = projectType === 'ts' ? tsProject : jsProject;

const codePipeline = new Pipeline(this, 'codepipeline', {
  pipelineName: pipelineName,
  artifactBucket: getPipelineBucket,
  stages,
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we define the pipeline stages based on the project type. If it's TypeScript, it includes the Build stage; otherwise, it skips it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Configuration in&lt;/strong&gt; &lt;code&gt;config/config.yaml&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;config.yaml&lt;/code&gt; file contains configuration values for your AWS CDK setup, specifically for different environments, such as dev (development) and prod (production). Here's a more detailed breakdown of the &lt;code&gt;config.yaml&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;environmentType: # define the type of environment (e.g., "dev" or "prod").
githubRepoName: # provide the name of the GitHub repository for your source code (Nodjes).
githubRepoOwner: # specify the owner of the GitHub repository.
githubAccessTokenName: # name of the secret in AWS Secrets Manager storing your GitHub access token.
projectType: ts # specify the project type as either "ts" (TypeScript) or "js" (JavaScript).

dev: # configuration specific to the development environment.
  stackName: # define the name of the CDK stack for the dev environment.
  branch: # specify the branch to trigger the pipeline for the dev environment.
  pipelineBucket: # name of the S3 bucket to store artifacts for the dev environment (make sure you create one before deploying)
  pipelineConfig:
    name: # specify a name for the pipeline configuration in the dev environment.
  minSize: 1 # minimum size for the Elastic Beanstalk environment in the dev environment.
  maxSize: 1 # maximum size for the Elastic Beanstalk environment in the dev environment.
  instanceTypes: t2.micro # Define the instance type for the Elastic Beanstalk environment in the dev environment.
  ebEnvName: # specify the name of the Elastic Beanstalk environment in the dev environment.
  ebAppName: # specify the name of the Elastic Beanstalk application in the dev environment.

# similarly, you can configure the "prod" environment with the same set of parameters.

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the &lt;code&gt;config.yaml&lt;/code&gt; file, you can define configuration values for both development and production environments. These values are essential for customizing your AWS CDK application to suit different stages of your deployment pipeline. Make sure to adjust these settings according to your project requirements for each environment.&lt;/p&gt;

&lt;p&gt;This configuration file plays a crucial role in the flexibility and customization of your CDK setup, allowing you to maintain separate configurations for different environments.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 6: App Synthesis and Deployment&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In the &lt;code&gt;main.ts&lt;/code&gt; file, we create a CDK app and instantiate the CDK stack based on the environment, either dev or prod:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (devProps?.stackName?.length) {
  const devStackName = devProps.stackName;
  new EbCodePipelineStack(app, devStackName, devProps);
} else {
  const prodStackName = prodProps?.stackName;
  new EbCodePipelineStack(app, prodStackName, prodProps);
}

app.synth();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This code initializes the CDK app and the stack based on the chosen environment, allowing you to create a CI/CD pipeline for your Elastic Beanstalk application.&lt;/p&gt;

&lt;p&gt;In conclusion, this blog post detailed the code used to create a CI/CD pipeline for AWS Elastic Beanstalk using AWS CDK. We walked through setting up Elastic Beanstalk, configuring the pipeline, and explained each section of the code to help you understand how to deploy your application with ease.&lt;/p&gt;

&lt;p&gt;Here's the &lt;strong&gt;GitHub&lt;/strong&gt; repo link to the code. 👇&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/mikaeelkhalid/deploy-elasticbeanstalk-codepipeline-cdk"&gt;https://github.com/mikaeelkhalid/deploy-elasticbeanstalk-codepipeline-cdk&lt;/a&gt;&lt;/p&gt;

</description>
      <category>aws</category>
      <category>elasticbeanstalk</category>
      <category>cicd</category>
      <category>cdk</category>
    </item>
    <item>
      <title>Use AWS CodeCommit to mirror Azure repo using an Azure Pipeline</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Tue, 17 Oct 2023 14:20:46 +0000</pubDate>
      <link>https://forem.com/aws-builders/use-aws-codecommit-to-mirror-azure-repo-using-an-azure-pipeline-2999</link>
      <guid>https://forem.com/aws-builders/use-aws-codecommit-to-mirror-azure-repo-using-an-azure-pipeline-2999</guid>
      <description>&lt;p&gt;In this blog post, I'll guide you through seamlessly syncing your Git repositories from Azure DevOps to AWS CodeCommit using the power of an Azure DevOps pipeline. This automated setup ensures that your source repository in Azure DevOps and its replica in AWS stay in perfect harmony. Whenever updates are pushed to the source repository, our pipeline springs into action, efficiently cloning the repository and pushing the changes to its AWS CodeCommit replica.&lt;/p&gt;

&lt;h2&gt;
  
  
  High-level architecture of the Pipeline
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vsjjigBs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn.hashnode.com/res/hashnode/image/upload/v1697546881185/b68aa777-692a-4a14-91d2-fb92d0d0c5a6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vsjjigBs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn.hashnode.com/res/hashnode/image/upload/v1697546881185/b68aa777-692a-4a14-91d2-fb92d0d0c5a6.png" alt="" width="800" height="506"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To set up repository replication in the AWS Cloud, I'll walk you through the following steps in this blog post:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Establish a CodeCommit repository.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Generate a policy, user, and secure HTTPS Git credentials using AWS Identity and Access Management (IAM).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Craft a pipeline within Azure DevOps.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before diving into the process, it's essential to ensure you have the following prerequisites in place:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;An active AWS account.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;An existing Azure DevOps repository.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Creating a repository in CodeCommit
&lt;/h2&gt;

&lt;p&gt;To prepare your CodeCommit replica repository and obtain its URL and ARN, follow these step-by-step instructions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Begin by creating a new CodeCommit repository in your preferred AWS region. Pick a distinctive name that reminds you it's a replica or backup repository, for instance, "&lt;code&gt;my-repo&lt;/code&gt;" Please note that you should refrain from manually pushing any changes to this replica repository, as it could lead to conflicts when your pipeline syncs change from the source repository. Treat it as a read-only repository and ensure that all development changes are pushed to your source repository.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Navigate to the AWS CodeCommit console.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Select &lt;strong&gt;Repositories&lt;/strong&gt; from the list of options.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Locate your newly created repository and click on &lt;strong&gt;View Repository&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Click on &lt;strong&gt;Clone URL&lt;/strong&gt; then select &lt;strong&gt;Clone HTTPS&lt;/strong&gt; This action will copy the repository's URL. Save this URL by pasting it into a plain-text editor for future reference.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the navigation pane, under &lt;strong&gt;Repositories&lt;/strong&gt; , choose &lt;strong&gt;Settings&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Copy the value of the &lt;strong&gt;Repository ARN&lt;/strong&gt; and save it by pasting it into a plain-text editor.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You now have the URL and ARN for your CodeCommit replica repository, which will be essential for setting up the &lt;strong&gt;IAM Role&lt;/strong&gt; and synchronization &lt;strong&gt;pipeline&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating a policy, user, and Git credentials in IAM
&lt;/h2&gt;

&lt;p&gt;The pipeline needs permissions and credentials to push commits to your CodeCommit repository. In this example, you create an IAM policy, IAM user, and HTTPS Git credentials for the pipeline to give it access to your repository in AWS. You grant the least privilege to the IAM user so the pipeline can only push to your replica repository.&lt;/p&gt;

&lt;p&gt;To create the IAM policy, complete the following steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;On the IAM console, choose &lt;strong&gt;Policies&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Create Policy&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;JSON&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enter a policy that grants permission to push commits to your repository. You can use a policy that similar to the following. For the &lt;strong&gt;Resource&lt;/strong&gt; element, specify the &lt;strong&gt;ARN&lt;/strong&gt; of your CodeCommit repository:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; {
     "Version": "2012-10-17",
     "Statement": [
         {
             "Effect": "Allow",
             "Action": "codecommit:GitPush",
             "Resource": "arn:aws:codecommit:eu-west-2:&amp;lt;account-id&amp;gt;:my-repo"
         }
     ]
 }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Review policy&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;For &lt;strong&gt;Name&lt;/strong&gt; , enter a name for your policy (for example, &lt;code&gt;codecommit-azure-repo-policy&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose to &lt;strong&gt;Create policy&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Create an IAM user
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;On the IAM console, choose &lt;strong&gt;Users&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Add user&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enter a &lt;strong&gt;User name&lt;/strong&gt; (for example, &lt;code&gt;codecommit-azure-devops-pipeline-user&lt;/code&gt;).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Select &lt;strong&gt;Programmatic access&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Next: Permissions&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Select &lt;strong&gt;Attach existing policies directly&lt;/strong&gt; and select the IAM policy you created "&lt;code&gt;codecommit-azure-repo-policy&lt;/code&gt;".&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Next: Tags&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Next: Review&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Create user&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When presented with security credentials, choose &lt;strong&gt;Close&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose your new user by clicking on the user name link.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Security Credentials&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Under &lt;strong&gt;Access keys&lt;/strong&gt; , remove the existing access key.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Under &lt;strong&gt;HTTPS Git credentials for AWS CodeCommit&lt;/strong&gt; , choose &lt;strong&gt;Generate credentials&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Download credentials&lt;/strong&gt; to save the &lt;strong&gt;username&lt;/strong&gt; and &lt;strong&gt;password&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Close&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Creating a pipeline in Azure DevOps
&lt;/h2&gt;

&lt;p&gt;In order to execute the pipeline discussed in this blog post, which mirrors your source repository and synchronizes it with your CodeCommit repository, you'll need to obtain the following essential details: the URL of your source repository and HTTPS Git credentials. Here's how to do it:&lt;/p&gt;

&lt;p&gt;To identify the URL of your source repository and generate the necessary HTTPS Git credentials, please follow the steps below:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Go to the &lt;strong&gt;Repos&lt;/strong&gt; page within Azure DevOps and choose your repository.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Clone&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;HTTPS&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Copy and save the URL by pasting it into a plain-text editor.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Generate Git Credentials&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Copy the username and password and save them by pasting them into a plain-text editor.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now that you have the URL and HTTPS Git credentials, create a pipeline.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Go to the &lt;strong&gt;Pipeline&lt;/strong&gt; page within Azure DevOps.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Create Pipeline&lt;/strong&gt; (or &lt;strong&gt;New Pipeline&lt;/strong&gt; ).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Azure Repos Git&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose your repository.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Starter pipeline&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enter or copy the following YAML code to replace the default pipeline YAML:&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; # This pipeline will automatically mirror an Azure DevOps repository in AWS CodeCommit

 # Trigger on all branches
 trigger:
 - '*'

 # Use latest Ubuntu image
 pool:
   vmImage: 'ubuntu-latest'

 # Pipeline
 steps:
 - checkout: none
 - script: |

       # Install urlencode function to encode reserved characters in passwords
       sudo apt-get install gridsite-clients

       # Create local mirror of Azure DevOps repository
       git clone --mirror https://${AZURE_GIT_USERNAME}:$(urlencode ${AZURE_GIT_PASSWORD})@${AZURE_REPO_URL} my-mirror-repo

       # Sync AWS CodeCommit repository
       cd my-mirror-repo
       git push --mirror https://${AWS_GIT_USERNAME}:$(urlencode ${AWS_GIT_PASSWORD})@${AWS_REPO_URL}

   displayName: 'Sync repository with AWS CodeCommit'
   env:
     AZURE_REPO_URL: $(AZURE_REPO_URL)
     AZURE_GIT_USERNAME: $(AZURE_GIT_USERNAME)
     AZURE_GIT_PASSWORD: $(AZURE_GIT_PASSWORD)
     AWS_REPO_URL: $(AWS_REPO_URL)
     AWS_GIT_USERNAME: $(AWS_GIT_USERNAME)
     AWS_GIT_PASSWORD: $(AWS_GIT_PASSWORD)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Variables&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;New Variable&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Enter the variable &lt;strong&gt;Name&lt;/strong&gt; and &lt;strong&gt;Value&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Select &lt;strong&gt;Keep this value secret&lt;/strong&gt; when adding any user name or password variable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;OK&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Repeat for each variable.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Save&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;Save and Run&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Test the Pipeline
&lt;/h2&gt;

&lt;p&gt;Upon saving the pipeline, it commits the pipeline's YAML file (&lt;code&gt;azure-pipelines.yml&lt;/code&gt;) to the root of your primary branch in the source repository. Subsequently, the pipeline will be triggered to run automatically. To confirm the successful execution of the pipeline, follow these steps:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Azure DevOps Pipelines:&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;AWS CodeCommit Console:&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;By following these steps, you can easily confirm that your pipeline ran without issues and that your replica repository in AWS CodeCommit is up-to-date and synchronized with your source repository.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt; : The pipeline runs whenever a new commit is pushed to the source repository. All updates are mirrored in the replica CodeCommit repository, including commits, branches, and references.&lt;/p&gt;

&lt;h2&gt;
  
  
  Cleaning up
&lt;/h2&gt;

&lt;p&gt;When youve completed all steps and are finished testing, follow these steps to delete resources to avoid incurring costs:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;On the CodeCommit console, choose &lt;strong&gt;Repositories&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose your repository and choose &lt;strong&gt;Delete Repository&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;On the IAM console, choose &lt;strong&gt;Users&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose your pipeline user and choose &lt;strong&gt;Delete User&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;On the navigation pane, choose &lt;strong&gt;Policies&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose your CodeCommit Git push policy and choose &lt;strong&gt;Policy Actions&lt;/strong&gt; and &lt;strong&gt;Delete&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Go to the &lt;strong&gt;Pipeline&lt;/strong&gt; page within Azure DevOps and choose your pipeline.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Choose &lt;strong&gt;More Actions&lt;/strong&gt; and choose &lt;strong&gt;Delete&lt;/strong&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;This post showed how you can use an Azure DevOps pipeline to mirror an Azure repository in AWS CodeCommit. It provided detailed instructions on setting up your replica repository in AWS CodeCommit, creating a least privilege access IAM policy and user credentials for the pipeline in IAM, and creating the pipeline in Azure DevOps.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Building an AWS AppSync Serverless Application using AWS CDK</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Wed, 02 Aug 2023 10:16:52 +0000</pubDate>
      <link>https://forem.com/aws-builders/building-an-aws-appsync-serverless-application-using-aws-cdk-69j</link>
      <guid>https://forem.com/aws-builders/building-an-aws-appsync-serverless-application-using-aws-cdk-69j</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--GC832WnH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cpfngzu0ixq4h9g696i.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--GC832WnH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2cpfngzu0ixq4h9g696i.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this blog post, we will explore how to build a serverless application using AWS AppSync and AWS Cloud Development Kit (CDK). We will create a simple note-taking application with Create and Read functionality, powered by AWS AppSync, AWS Lambda, and DynamoDB.&lt;/p&gt;

&lt;h3&gt;
  
  
  Introduction to AWS AppSync:
&lt;/h3&gt;

&lt;p&gt;AWS AppSync is a fully managed service that makes it easy to develop GraphQL APIs by handling the heavy lifting of securely connecting to data sources like DynamoDB, Lambda, and more. It allows you to build real-time and offline-capable applications with a flexible and powerful API.&lt;/p&gt;

&lt;h3&gt;
  
  
  AWS CDK Overview:
&lt;/h3&gt;

&lt;p&gt;AWS Cloud Development Kit (CDK) is an open-source software development framework to define cloud infrastructure in code and provision it through AWS CloudFormation. It enables developers to build and manage AWS infrastructure using familiar programming languages like TypeScript, JavaScript, Python, Java, and C#. With CDK, you can easily create, configure, and deploy AWS resources.&lt;/p&gt;

&lt;h3&gt;
  
  
  Project Overview:
&lt;/h3&gt;

&lt;p&gt;We will create a simple note-taking application with the following features:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;A GraphQL API to interact with notes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A Lambda function to handle the GraphQL resolvers.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A DynamoDB table to store the notes.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Prerequisites:
&lt;/h3&gt;

&lt;p&gt;Before we begin, make sure you have the following prerequisites installed on your machine:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Node.js&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;AWS CDK&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Step 1: Setting Up the Project
&lt;/h3&gt;

&lt;p&gt;Let's start by setting up our project. Open your terminal and follow these steps:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Create a new directory for your project
mkdir cdk-appsync-serverless-notes-app
cd cdk-appsync-serverless-notes-app

# Initialize a new Node.js project
cdk init --language=typescript

# Create a new directory for Lambda and GraphQL schema
mkdir lambdas graphql

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 2: Create a new CDK Stack
&lt;/h3&gt;

&lt;p&gt;Create a new CDK stack using the following code:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Import Required AWS CDK Libraries:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Duration, Expiration, Stack, StackProps } from 'aws-cdk-lib';
import { GraphqlApi, SchemaFile, AuthorizationType } from 'aws-cdk-lib/aws-appsync';
import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb';
import { Runtime } from 'aws-cdk-lib/aws-lambda';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Construct } from 'constructs';
import { join } from 'path';

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this section, we import the necessary AWS CDK constructs and AWS AppSync, AWS Lambda, and AWS DynamoDB libraries.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Define the AppsyncServerlessStack Class:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class AppsyncServerlessStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
    // ...
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we define a class named &lt;code&gt;AppsyncServerlessStack&lt;/code&gt;, which extends the &lt;code&gt;Stack&lt;/code&gt; class from AWS CDK. This class will be used to define our AWS infrastructure stack.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Create the GraphQL API:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const api = new GraphqlApi(this, 'notes-appsync-api', {
  name: 'notes-appsync-api',
  schema: SchemaFile.fromAsset('graphql/schema.graphql'),
  authorizationConfig: {
    defaultAuthorization: {
      authorizationType: AuthorizationType.API_KEY,
      apiKeyConfig: {
        expires: Expiration.after(Duration.days(365)),
      },
    },
  },
  xrayEnabled: true,
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this section, we create an instance of &lt;code&gt;GraphqlApi&lt;/code&gt;, which represents our AWS AppSync GraphQL API. We provide the API name, and the GraphQL schema file location, and specify that API_KEY authorization is used with an expiration of 365 days. We also enable AWS X-Ray for the API to gain insights into performance and errors.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Create the Lambda Function for Resolvers:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const notesLambda = new NodejsFunction(this, 'notes-lambda', {
  functionName: 'notes-lambda',
  runtime: Runtime.NODEJS_16_X,
  entry: join(__dirname, '../lambdas/notesLambda.ts'),
  memorySize: 1024,
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this part, we create a Node.js AWS Lambda function using the &lt;code&gt;NodejsFunction&lt;/code&gt; construct. This function will handle the GraphQL resolvers for our API. We specify the function's name, runtime, entry file location, and memory size.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Create a Data Source for the Lambda Function:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const lambdaDataSource = api.addLambdaDataSource('lambda-data-source', notesLambda);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we create a data source for the GraphQL API, which is linked to the Lambda function we created earlier. This data source allows the API to interact with the Lambda function as a data source.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Create Resolvers for GraphQL Queries and Mutations:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;lambdaDataSource.createResolver('query-resolver', {
  typeName: 'Query',
  fieldName: 'listNotes',
});

lambdaDataSource.createResolver('mutation-resolver', {
  typeName: 'Mutation',
  fieldName: 'createNote',
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this section, we create resolvers for the GraphQL queries and mutations. We specify the type and field names from the GraphQL schema and link them to the corresponding functions in the Lambda function.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Create a DynamoDB Table to Store Notes:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const notesTable = new Table(this, 'notes-api-table', {
  tableName: 'notes-api-table',
  billingMode: BillingMode.PAY_PER_REQUEST,
  partitionKey: {
    name: 'id',
    type: AttributeType.STRING,
  },
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we create a DynamoDB table to store the notes. We specify the table name, and billing mode (PAY_PER_REQUEST means we pay per request), and define a partition key named 'id' of type STRING.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Grant Lambda Function Access to the DynamoDB Table:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;notesTable.grantFullAccess(notesLambda);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This line grants the Lambda function (&lt;code&gt;notesLambda&lt;/code&gt;) full access to the DynamoDB table (&lt;code&gt;notesTable&lt;/code&gt;). It allows the Lambda function to read and write data to the table.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Add DynamoDB Table Name as an Environment Variable for the Lambda Function:&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;notesLambda.addEnvironment('NOTES_TABLE', notesTable.tableName);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We add an environment variable to the Lambda function named &lt;code&gt;NOTES_TABLE&lt;/code&gt;, and its value is set to the name of the DynamoDB table. This allows the Lambda function to know which table it should interact with.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here is a complete CDK stack code:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import required AWS CDK libraries
import { Duration, Expiration, Stack, StackProps } from 'aws-cdk-lib';
import {
  GraphqlApi,
  SchemaFile,
  AuthorizationType,
} from 'aws-cdk-lib/aws-appsync';
import { AttributeType, BillingMode, Table } from 'aws-cdk-lib/aws-dynamodb';
import { Runtime } from 'aws-cdk-lib/aws-lambda';
import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs';
import { Construct } from 'constructs';
import { join } from 'path';

export class AppsyncServerlessStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // Create the GraphQL API
    const api = new GraphqlApi(this, 'notes-appsync-api', {
      name: 'notes-appsync-api',
      schema: SchemaFile.fromAsset('graphql/schema.graphql'),
      authorizationConfig: {
        defaultAuthorization: {
          authorizationType: AuthorizationType.API_KEY,
          apiKeyConfig: {
            expires: Expiration.after(Duration.days(365)),
          },
        },
      },
      xrayEnabled: true,
    });

    // Create the Lambda function for the resolvers
    const notesLambda = new NodejsFunction(this, 'notes-lambda', {
      functionName: 'notes-lambda',
      runtime: Runtime.NODEJS_16_X,
      entry: join(__dirname, '../lambdas/notesLambda.ts'),
      memorySize: 1024,
    });

    // Create a data source for the Lambda function
    const lambdaDataSource = api.addLambdaDataSource(
      'lambda-data-source',
      notesLambda
    );

    // Create resolvers for the GraphQL queries and mutations
    lambdaDataSource.createResolver('query-resolver', {
      typeName: 'Query',
      fieldName: 'listNotes',
    });

    lambdaDataSource.createResolver('mutation-resolver', {
      typeName: 'Mutation',
      fieldName: 'createNote',
    });

    // Create a DynamoDB table to store the notes
    const notesTable = new Table(this, 'notes-api-table', {
      tableName: 'notes-api-table',
      billingMode: BillingMode.PAY_PER_REQUEST,
      partitionKey: {
        name: 'id',
        type: AttributeType.STRING,
      },
    });

    // Grant the Lambda function full access to the DynamoDB table
    notesTable.grantFullAccess(notesLambda);

    // Add the DynamoDB table name as an environment variable for the Lambda function
    notesLambda.addEnvironment('NOTES_TABLE', notesTable.tableName);
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 3: Define the GraphQL Schema
&lt;/h3&gt;

&lt;p&gt;In this step, we will define the GraphQL schema for our note-taking application. Create a file named &lt;code&gt;schema.graphql&lt;/code&gt; inside the &lt;code&gt;graphql&lt;/code&gt; directory with the following content:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type Note {
  id: ID!
  name: String!
  completed: Boolean!
}

input NoteInput {
  id: ID!
  name: String!
  completed: Boolean!
}

type Query {
  listNotes: [Note]
}

type Mutation {
  createNote(note: NoteInput!): Note
}

type Subscription {
  onCreateNote: Note @aws_subscribe(mutations: ["createNote"])
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 4: Implement the Lambda Resolvers
&lt;/h3&gt;

&lt;p&gt;Next, let's implement the Lambda function that will handle the GraphQL resolvers. Create a file named &lt;code&gt;notesLambda.ts&lt;/code&gt; inside the &lt;code&gt;lambdas&lt;/code&gt; directory with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import the required types
import { createNote, listNotes } from './notesOperations';
import { Note } from './types/Note';

// Define the AppSyncEvent type
type AppSyncEvent = {
  info: {
    fieldName: string;
  };
  arguments: {
    noteId: string;
    note: Note;
  };
};

// Lambda function handler
exports.handler = async (event: AppSyncEvent) =&amp;gt; {
  switch (event.info.fieldName) {
    case 'createNote':
      return await createNote(event.arguments.note);

    case 'listNotes':
      return await listNotes();

    default:
      return null;
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 5: Implement the Lambda Operations
&lt;/h3&gt;

&lt;p&gt;Now, let's implement the actual operations for creating and listing notes in DynamoDB. Create a file named &lt;code&gt;notesOperations.ts&lt;/code&gt; inside the &lt;code&gt;lambdas&lt;/code&gt; directory with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Import the AWS SDK and the Note type
import { DynamoDB } from 'aws-sdk';
import { Note } from '../types/Note';

// Create a DynamoDB DocumentClient
const docClient = new DynamoDB.DocumentClient();

// Function to create a new note
export const createNote = async (note: Note) =&amp;gt; {
  const params = {
    TableName: process.env.NOTES_TABLE as string,
    Item: note,
  };

  try {
    const data = await docClient.put(params).promise();
    console.log('data', data);
    return note;
  } catch (error) {
    console.log('dynamodb err: ', error);
    return null;
  }
};

// Function to list all notes
export const listNotes = async () =&amp;gt; {
  const params = {
    TableName: process.env.NOTES_TABLE as string,
  };

  try {
    const data = await docClient.scan(params).promise();
    return data.Items;
  } catch (error) {
    console.log('dynamodb err: ', error);
    return null;
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Step 6: Deploy the Application
&lt;/h3&gt;

&lt;p&gt;Now that we have implemented the GraphQL API, Lambda resolvers, and DynamoDB operations, it's time to deploy our application. Make sure you have installed and configured the AWS CLI on your machine.&lt;/p&gt;

&lt;p&gt;Run the following commands to deploy the CDK stack:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# Install dependencies
npm install

# Booststrap the CDK Env (if not already)
cdk bootstrap

# Synthesize the CDK stack
cdk synth

# Deploy the CDK stack
cdk deploy

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once the deployment is complete, the AWS CloudFormation will create the necessary resources, including the GraphQL API, Lambda function, and DynamoDB table.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion:
&lt;/h3&gt;

&lt;p&gt;Congratulations! You have successfully built an AWS AppSync serverless application using AWS CDK. You now have a GraphQL API to interact with your note-taking application, powered by AWS Lambda and DynamoDB. This is just the beginning, and you can extend the application with additional features like authentication, real-time updates using subscriptions, and more.&lt;/p&gt;

&lt;p&gt;I hope you found this blog post helpful and that it inspires you to explore further and build more sophisticated serverless applications using AWS AppSync and AWS CDK. Happy coding!&lt;/p&gt;

&lt;h3&gt;
  
  
  GitHub Repo:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://github.com/mikaeelkhalid/aws-cdk-appsync-serverless-boilerplate"&gt;https://github.com/mikaeelkhalid/aws-cdk-appsync-serverless-boilerplate&lt;/a&gt;&lt;/p&gt;

</description>
      <category>aws</category>
      <category>awscdk</category>
      <category>serverless</category>
      <category>appsync</category>
    </item>
    <item>
      <title>How to Deploy Dockerized AWS Lambda Using AWS CDK</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Tue, 16 May 2023 09:54:41 +0000</pubDate>
      <link>https://forem.com/aws-builders/how-to-deploy-dockerized-aws-lambda-using-aws-cdk-29ko</link>
      <guid>https://forem.com/aws-builders/how-to-deploy-dockerized-aws-lambda-using-aws-cdk-29ko</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--I-oiWtnJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tjawchhu28xbykej554o.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--I-oiWtnJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tjawchhu28xbykej554o.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In this blog post, we'll explore a step-by-step guide on how to deploy Dockerized AWS Lambda functions using the AWS Cloud Development Kit (CDK) with TypeScript.&lt;/p&gt;

&lt;p&gt;AWS CDK, a software development framework for defining cloud infrastructure in code, has eased cloud resources management by facilitating the use of familiar programming languages. The combination of Docker, AWS Lambda, and CDK takes it to another level, providing a seamless development and deployment process.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Prerequisites&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Before we start, make sure you have the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;An AWS Account&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;AWS CLI installed and configured&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Docker installed&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Node.js and npm installed&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;AWS CDK installed&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Step 1: Initialize a new AWS CDK project&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;First, create a new directory for your project and navigate to it:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir cdk-docker-lambda &amp;amp;&amp;amp; cd cdk-docker-lambda

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Initialize a new AWS CDK project:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk init --language=typescript

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command creates a new CDK project with TypeScript as the programming language.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Step 2: Create a Dockerfile&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Now, let's create a Dockerfile. This file is a set of instructions Docker will use to create your Docker image. Here's an example of a Dockerfile for a Node.js application:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM public.ecr.aws/lambda/nodejs:14

WORKDIR /var/task

COPY . .

RUN npm install

CMD ["index.handler"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This Dockerfile starts from a public Amazon ECR image for Node.js 14, copies your application code into the image, installs your npm dependencies, and sets &lt;code&gt;index.handler&lt;/code&gt; as the command that will be executed when your Lambda function is invoked.&lt;/p&gt;

&lt;h3&gt;
  
  
  Note: The Folder Structure should be like this
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.
 bin
 lambdas
    index.js
    Dockerfile
 lib

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Step 3: Write your AWS CDK Stack&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Now, let's define our AWS CDK stack. In the &lt;code&gt;lib&lt;/code&gt; directory, there's a file called &lt;code&gt;cdk-docker-lambda-stack.ts&lt;/code&gt; Open this file and write your stack:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Duration, Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { DockerImageCode, DockerImageFunction } from 'aws-cdk-lib/aws-lambda';
import path = require('path');

export class CdkDockerLambdaStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    new DockerImageFunction(this, 'docker-lambda-function', {
      functionName: "docker-lambda-fn",
      code: DockerImageCode.fromImageAsset(path.join(__dirname, '../lambdas')),
      memorySize: 512,
      timeout: Duration.minutes(2),
      description: "This is dockerized AWS Lambda function"
    });
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this code, we're defining a new Lambda function that uses a Docker image as its code. &lt;code&gt;lambda.DockerImageCode.fromImageAsset&lt;/code&gt; takes the path to the directory containing your Dockerfile and builds your Docker image.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Step 4: Deploy your AWS CDK Stack&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Compile your TypeScript code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run build

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, you'll need to bootstrap your AWS environment to use the CDK if you haven't already:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk bootstrap

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, deploy your AWS CDK stack:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk deploy

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will build your Docker image, push it to an Amazon ECR repository, and create your AWS Lambda function with the Docker image.&lt;/p&gt;

&lt;h3&gt;
  
  
  Note: If the deploy command failed due to ECR login
&lt;/h3&gt;

&lt;p&gt;You can use the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;aws ecr get-login-password --region your-region | docker login --username AWS --password-stdin aws-account-id.dkr.ecr.us-east-1.amazonaws.com

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After login success, you can &lt;code&gt;cdk deploy&lt;/code&gt; again&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;In this blog post, we've seen how to use the AWS CDK with TypeScript to deploy Dockerized AWS Lambda functions. This combination allows you to define your AWS infrastructure using a familiar programming language, leverage the power of modern software practices like version control and CI/CD, and package your Lambda functions as Docker containers. This last point is particularly powerful, as it enables you to use any programming language that can run inside a Docker container, not just those natively supported by AWS Lambda.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/mikaeelkhalid/aws-cdk-docker-lambda/tree/main"&gt;https://github.com/mikaeelkhalid/aws-cdk-docker-lambda/tree/main&lt;/a&gt;&lt;/p&gt;

</description>
      <category>aws</category>
      <category>awscdk</category>
      <category>docker</category>
      <category>lambda</category>
    </item>
    <item>
      <title>What does the AWS CDK Diff command do</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Mon, 20 Mar 2023 11:56:03 +0000</pubDate>
      <link>https://forem.com/aws-builders/what-does-the-aws-cdk-diff-command-do-4pbe</link>
      <guid>https://forem.com/aws-builders/what-does-the-aws-cdk-diff-command-do-4pbe</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--so0PvO4o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5rt9mum6n60vld73z4r.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--so0PvO4o--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5rt9mum6n60vld73z4r.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;The AWS Cloud Development Kit (CDK) is an open-source software development framework that simplifies the process of creating, deploying and managing AWS infrastructure. It enables developers to use familiar programming languages such as TypeScript, Python, Java, and C# to define reusable cloud components and provision them using AWS CloudFormation.&lt;/p&gt;

&lt;p&gt;One of the commands that the AWS CDK offers is the &lt;code&gt;cdk diff&lt;/code&gt; command. In this blog post, we'll delve into the &lt;code&gt;cdk diff&lt;/code&gt; command, its purpose, and how it can help you manage your infrastructure with ease. We will also explore practical examples to illustrate its utilizations.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is the CDK Diff?
&lt;/h3&gt;

&lt;p&gt;The &lt;code&gt;cdk diff&lt;/code&gt; command is a part of the AWS CDK CLI and helps developers identify the differences between the current AWS CDK application state and the deployed state in AWS CloudFormation. This comparison can be useful in various scenarios, such as validating changes before deployment, auditing infrastructure modifications, or reviewing pull requests in collaborative projects.&lt;/p&gt;

&lt;p&gt;The command provides a clear and concise output, showing the differences between your local and deployed resources, properties, and settings.&lt;/p&gt;

&lt;h3&gt;
  
  
  How to use CDK Diff?
&lt;/h3&gt;

&lt;p&gt;To use the &lt;code&gt;cdk diff&lt;/code&gt; command, first, ensure that you have the AWS CDK CLI installed. If you don't have it installed, you can follow the official AWS CDK installation guide.&lt;/p&gt;

&lt;p&gt;Once the AWS CDK CLI is installed, navigate to your CDK project directory and run the following command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk diff

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will display the differences between your local AWS CDK application and the deployed AWS CloudFormation stack. The output will show added, modified, or removed resources, as well as changes in their properties.&lt;/p&gt;

&lt;h3&gt;
  
  
  Examples
&lt;/h3&gt;

&lt;p&gt;Let's consider a simple example to understand how the &lt;code&gt;cdk diff&lt;/code&gt; command works. We'll use TypeScript for this example, but the concepts apply to other programming languages as well.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Creating a new CDK project&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk init app --language typescript

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Adding an Amazon S3 bucket to your CDK stack&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Modify the file &lt;code&gt;lib/your_stack_name-stack.ts&lt;/code&gt; and add the following code snippet&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Stack, StackProps} from 'aws-cdk-lib';
import { Bucket, RemovalPolicy } from 'aws-cdk-lib/aws-s3';

export class YourStackNameStack extends Stack {
  constructor(scope: cdk.App, id: string, props?: StackProps) {
    super(scope, id, props);

    new Bucket(this, 'MyFirstBucket', {
      versioned: true,
      removalPolicy: RemovalPolicy.DESTROY,
    });
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Deploy the CDK stack&lt;/strong&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk deploy

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's say you want to update the S3 bucket to enable server access logging. Modify the &lt;code&gt;lib/your_stack_name-stack.ts&lt;/code&gt; file as follows&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Stack, StackProps } from 'aws-cdk-lib';
import { Bucket, RemovalPolicy } from 'aws-cdk-lib/aws-s3';

export class YourStackNameStack extends Stack {
  constructor(scope: cdk.App, id: string, props?: StackProps) {
    super(scope, id, props);

    const loggingBucket = new Bucket(this, 'LoggingBucket', {
      removalPolicy: RemovalPolicy.DESTROY,
    });

    new Bucket(this, 'MyFirstBucket', {
      versioned: true,
      removalPolicy: RemovalPolicy.DESTROY,
      serverAccessLogsBucket: loggingBucket,
    });
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Running the CDK Diff command&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Before deploying the changes, let's run the &lt;code&gt;cdk diff&lt;/code&gt; command to inspect the differences between the local AWS CDK application and the deployed AWS CloudFormation stack&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk diff

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You should see an output similar to the following&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Stack YourStackNameStack
Resources
[+] AWS::S3::Bucket LoggingBucket LoggingBucketA1B2C3D4
[-] AWS::S3::Bucket MyFirstBucket MyFirstBucketE5F6G7H8
[+] AWS::S3::Bucket MyFirstBucket MyFirstBucketI9J0K1L2
   [+] LoggingConfiguration
       [+] DestinationBucketName: {"Ref":"LoggingBucketA1B2C3D4"}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output indicates the following changes:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;A new S3 bucket (LoggingBucket) has been added.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The existing S3 bucket (MyFirstBucket) will be replaced with a new S3 bucket.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The new S3 bucket (MyFirstBucket) will have a logging configuration pointing to the LoggingBucket.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Deploying the changes&lt;/strong&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now that we've reviewed the differences using &lt;code&gt;cdk diff&lt;/code&gt;, we can proceed to deploy the changes with the &lt;code&gt;cdk deploy&lt;/code&gt; command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk deploy

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will update the AWS CloudFormation stack with the new resources and configurations.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;In this blog post, we've explored the importance and usage of the &lt;code&gt;cdk diff&lt;/code&gt; command in the AWS CDK. The command serves as an efficient tool for managing and validating infrastructure changes before deployment, allowing you to catch potential issues early and maintain a clear understanding of your AWS infrastructure.&lt;/p&gt;

&lt;p&gt;By incorporating &lt;code&gt;cdk diff&lt;/code&gt; into your development workflow, you can maintain better control over your AWS resources, ensure that your infrastructure changes are consistent with your expectations, and improve collaboration in your team by reviewing infrastructure changes more effectively.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>cdk</category>
      <category>awscdk</category>
      <category>iac</category>
    </item>
    <item>
      <title>Using AWS CDK to Deploy an AWS Fargate Service</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Thu, 16 Mar 2023 09:28:14 +0000</pubDate>
      <link>https://forem.com/aws-builders/using-aws-cdk-to-deploy-an-aws-fargate-service-2b21</link>
      <guid>https://forem.com/aws-builders/using-aws-cdk-to-deploy-an-aws-fargate-service-2b21</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--rS7Em-9a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fpokcp19u60939podxrk.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--rS7Em-9a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fpokcp19u60939podxrk.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Introduction
&lt;/h3&gt;

&lt;p&gt;Amazon Web Services (AWS) offers a wide range of tools and services for developers to build, deploy, and manage their applications in the cloud. One such service is AWS Fargate, a serverless compute engine for containers that make it easier to run containerized applications without managing the underlying infrastructure. The AWS Cloud Development Kit (CDK) is an open-source software development framework for defining cloud infrastructure in code and provisioning it through AWS CloudFormation.&lt;/p&gt;

&lt;p&gt;This blog post will dive deep into using the AWS CDK to deploy an AWS Fargate service, complete with code examples. By the end of this guide, you will better understand how to deploy a containerized application using the AWS CDK and Fargate.&lt;/p&gt;

&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;

&lt;p&gt;Before getting started, make sure you have the following installed and configured:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Node.js (v10.x or later)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;AWS CLI (v2.x)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;AWS CDK (v2.x)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Docker (for building and testing the container)&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Get Started
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Initialize the AWS CDK project&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;First, create a new directory for your project and initialize a new CDK project using TypeScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ mkdir fargate-cdk &amp;amp;&amp;amp; cd fargate-cdk
$ cdk init --language typescript

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 2: Open in VSCode or any editor&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In VSCode:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ code .

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 3: Define the Fargate service stack&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Open the &lt;code&gt;lib/fargate-cdk-stack.ts&lt;/code&gt; file and replace its content with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as cdk from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as ecs_patterns from 'aws-cdk-lib/aws-ecs-patterns';

export class FargateCdkStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Create an ECS cluster
    const cluster = new ecs.Cluster(this, 'FargateCluster', {
      vpc: new cdk.Vpc(this, 'Vpc'),
    });

    // Load the ECR repository
    const ecrRepository = ecr.Repository.fromRepositoryName(
      this,
      'EcrRepository',
      'your-ecr-repo-name'
    );

    // Define the Fargate service
    new ecs_patterns.ApplicationLoadBalancedFargateService(this, 'FargateService', {
      cluster: cluster,
      taskImageOptions: {
        image: ecs.ContainerImage.fromEcrRepository(ecrRepository),
        containerPort: 80,
      },
      desiredCount: 2,
      publicLoadBalancer: true,
    });
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace &lt;code&gt;'your-ecr-repo-name'&lt;/code&gt; with the name of your existing ECR repository.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4: Build the Docker image and push it to ECR&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Create a &lt;code&gt;Dockerfile&lt;/code&gt; in your project's root directory:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FROM node:14-alpine

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 80

CMD ["npm", "start"]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Build the Docker image and push it to your ECR repository:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ aws ecr --region us-west-2 get-login-password | docker login --username AWS --password-stdin &amp;lt;your_account_id&amp;gt;.dkr.ecr.us-east-1.amazonaws.com

$ docker build -t your-ecr-repo-name .

$ docker tag your-ecr-repo-name:latest &amp;lt;your_account_id&amp;gt;.dkr.ecr.us-east-1.amazonaws.com/your-ecr-repo-name:latest

$ docker push &amp;lt;your_account_id&amp;gt;.dkr.ecr.us-east-1.amazonaws.com/your-ecr-repo-name:latest

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace &lt;code&gt;&amp;lt;your_account_id&amp;gt;&lt;/code&gt; with your AWS account ID.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5: Deploy the Fargate service&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now that you have the Docker image pushed to ECR, you can deploy the Fargate service using the AWS CDK:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm run build
$ cdk deploy

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;cdk deploy&lt;/code&gt; command will create a new CloudFormation stack with the specified Fargate service, load balancer, and other required resources. You can view the progress of the deployment in the AWS Management Console under the CloudFormation service.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; If you're using CDK for the first time make sure to &lt;code&gt;bootstrap&lt;/code&gt; your environment.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ cdk bootstrap

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Step 6: Test the Fargate service&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;After the deployment has been completed, you can test your Fargate service by navigating to the provided load balancer URL. You can find the URL in the CloudFormation stack outputs or the AWS Management Console under the Elastic Load Balancing service.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;In this blog post, we have demonstrated how to use the AWS CDK to deploy a containerized application with an AWS Fargate service. By leveraging the AWS CDK and Fargate, you can simplify the deployment and management of your applications, allowing you to focus on writing code rather than managing infrastructure.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>cdk</category>
      <category>fargate</category>
      <category>docker</category>
    </item>
    <item>
      <title>How to List Stacks in AWS CDK</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Fri, 03 Mar 2023 01:26:39 +0000</pubDate>
      <link>https://forem.com/aws-builders/how-to-list-stacks-in-aws-cdk-1ckf</link>
      <guid>https://forem.com/aws-builders/how-to-list-stacks-in-aws-cdk-1ckf</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--e5xu8q59--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kxaeof203uivozr7rfws.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--e5xu8q59--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kxaeof203uivozr7rfws.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;AWS Cloud Development Kit (CDK) is a powerful tool that allows developers to define and deploy their infrastructure as code. One of the key features of CDK is the ability to create and manage stacks, which are collections of AWS resources that are deployed together. In this article, we will explore how to list stacks in AWS CDK.&lt;/p&gt;

&lt;p&gt;To list stacks in AWS CDK, you can use the &lt;code&gt;cdk list&lt;/code&gt; command. This command will display a list of all stacks that have been defined in your CDK application. The output will include the stack name, the stack environment, and the stack status.&lt;/p&gt;

&lt;p&gt;To list all stacks in your CDK application, you can use the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note, we could use the alias - &lt;code&gt;cdk ls&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This command will display a list of all stacks that have been defined in your CDK application, including the stack name, the stack environment, and the stack status.&lt;/p&gt;

&lt;p&gt;If you want to list stacks in a specific environment, you can use the &lt;code&gt;-e&lt;/code&gt; or &lt;code&gt;--environment&lt;/code&gt; option. For example, to list stacks in the &lt;code&gt;prod&lt;/code&gt; environment, you can use the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk list -e prod
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will display a list of all stacks that have been defined in the &lt;code&gt;prod&lt;/code&gt; environment, including the stack name, the stack environment, and the stack status.&lt;/p&gt;

&lt;p&gt;If you want to list stacks in a specific region, you can use the &lt;code&gt;-r&lt;/code&gt; or &lt;code&gt;--region&lt;/code&gt; option. For example, to list stacks in the &lt;code&gt;us-east-1&lt;/code&gt; the region, you can use the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk list -r us-east-1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will display a list of all stacks that have been defined in the &lt;code&gt;us-east-1&lt;/code&gt; region, including the stack name, the stack environment, and the stack status.&lt;/p&gt;

&lt;p&gt;In addition to listing stacks, the &lt;code&gt;cdk list&lt;/code&gt; command also allows you to filter the output by stack status. You can use the &lt;code&gt;-s&lt;/code&gt; or &lt;code&gt;--status&lt;/code&gt; option to filter the output based on the stack status. For example, to list only stacks that are in the &lt;code&gt;CREATE_COMPLETE&lt;/code&gt; status, you can use the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk list -s CREATE_COMPLETE
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This command will display a list of all stacks that are in the &lt;code&gt;CREATE_COMPLETE&lt;/code&gt; status, including the stack name, the stack environment, and the stack status.&lt;/p&gt;

&lt;p&gt;Another useful option when using the &lt;code&gt;cdk list&lt;/code&gt; command is the &lt;code&gt;--long&lt;/code&gt; option. This option will display additional information about each stack, such as the stack's id, name, AWS account, region, environment, and where the stack is deployed.&lt;/p&gt;

&lt;p&gt;For example, if you want to view all the stacks in your CDK application, along with additional information, you can use the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk list --long
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;--long&lt;/code&gt; flag outputs information about the environment (&lt;code&gt;account&lt;/code&gt;and &lt;code&gt;region&lt;/code&gt;) our stacks belong to:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- id: my-stack-prod
  name: my-stack-prod
  environment:
    account: '123456789'
    region: us-east-1
    name: aws://123456789/us-east-1

- id: my-stack-dev
  name: my-stack-dev
  environment:
    account: '123456789'
    region: us-east-1
    name: aws://123456789/us-east-1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In conclusion, the &lt;code&gt;cdk list&lt;/code&gt; command is a powerful tool that allows you to list stacks in AWS CDK. You can use this command to list all stacks in your CDK application, list stacks in a specific environment, list stacks in a specific region, and filter the output by stack status. This makes it easy to manage your stacks and ensure that your infrastructure is deployed correctly.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>awscdk</category>
      <category>cdk</category>
      <category>iac</category>
    </item>
    <item>
      <title>Build serverless applications with AWS CDK</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Wed, 15 Feb 2023 15:51:13 +0000</pubDate>
      <link>https://forem.com/aws-builders/build-serverless-applications-with-aws-cdk-4a69</link>
      <guid>https://forem.com/aws-builders/build-serverless-applications-with-aws-cdk-4a69</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--u__iMd7u--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0a8yt152ds67bn73v1z.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--u__iMd7u--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0a8yt152ds67bn73v1z.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Serverless computing is becoming an increasingly popular way to develop and deploy applications. With serverless, developers can focus on writing code and not worry about the underlying infrastructure. AWS Lambda and API Gateway are two popular AWS services used for serverless computing. In this blog post, we will explore how to use AWS CDK to deploy serverless applications using these services.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Getting started with AWS CDK&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Before we get into the specifics of building serverless applications, let's start with a brief introduction to AWS CDK. AWS Cloud Development Kit (CDK) is an open-source software development framework for defining cloud infrastructure in code. With AWS CDK, you can define your infrastructure in familiar programming languages such as TypeScript, Python, and Java. AWS CDK uses AWS CloudFormation under the hood, so all of your infrastructure is defined in a CloudFormation stack.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Creating a serverless stack&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;To create a serverless stack with AWS CDK, we first need to define our resources. In this case, we will be defining an AWS Lambda function and an API Gateway endpoint. Let's start with the Lambda function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as cdk from 'aws-cdk-lib';
import * as lambda from 'aws-cdk-lib/aws-lambda';

export class ServerlessStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const myFunction = new lambda.Function(this, 'MyFunction', {
      runtime: lambda.Runtime.NODEJS_14_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset('path/to/lambda/code'),
    });
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are defining a new Lambda function with the runtime of Node.js 14.x. We are also specifying the location of the code for the function. This code could be located in a local directory or in an S3 bucket.&lt;/p&gt;

&lt;p&gt;Next, we will define the API Gateway endpoint:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as apigw from 'aws-cdk-lib/aws-apigatewayv2';

export class ServerlessStack extends cdk.Stack {
  constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const myFunction = new lambda.Function(this, 'MyFunction', {
      runtime: lambda.Runtime.NODEJS_14_X,
      handler: 'index.handler',
      code: lambda.Code.fromAsset('path/to/lambda/code'),
    });

    const api = new apigw.HttpApi(this, 'MyApi');
    api.addRoutes({
      path: '/',
      methods: [apigw.HttpMethod.GET],
      integration: new apigw.LambdaProxyIntegration({
        handler: myFunction,
      }),
    });
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we are defining a new HTTP API Gateway endpoint that routes to our Lambda function. We are specifying that this endpoint should respond to GET requests and forward them to our Lambda function.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Deploying and testing your serverless application&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Once we have defined our resources, we can deploy our stack using the AWS CDK CLI:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk deploy

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create the necessary resources in your AWS account. Once the deployment is complete, we can test our API Gateway endpoint by sending an HTTP GET request to the endpoint URL:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl https://api-gateway-url/

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This should return the output from our Lambda function.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Conclusion&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;In this blog post, we have seen how to use AWS CDK to define and deploy a serverless stack containing an AWS Lambda function and an API Gateway endpoint. With AWS CDK, you can define your infrastructure in code and easily manage it through version control systems and continuous integration/continuous deployment (CI/CD) pipelines. AWS CDK abstracts away the complexity of CloudFormation and provides an intuitive programming interface that makes it easy to create and manage AWS resources.&lt;/p&gt;

&lt;p&gt;With AWS CDK, you can take advantage of the benefits of serverless computing, such as automatic scaling and pay-as-you-go pricing. AWS Lambda and API Gateway are just two of the many serverless services provided by AWS, and with AWS CDK, you can easily create and manage these services alongside other AWS services.&lt;/p&gt;

&lt;p&gt;In summary, AWS CDK provides an excellent framework for defining and deploying serverless applications. With its intuitive programming interface and integration with AWS CloudFormation, you can easily manage your serverless infrastructure in code. By using AWS CDK, you can take advantage of the benefits of serverless computing, such as automatic scaling and pay-as-you-go pricing, and build reliable and scalable serverless applications.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>awscdk</category>
      <category>cdk</category>
      <category>serverless</category>
    </item>
    <item>
      <title>How to Create an IAM User with AWS CDK</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Wed, 08 Feb 2023 12:19:38 +0000</pubDate>
      <link>https://forem.com/aws-builders/how-to-create-an-iam-user-with-aws-cdk-k2o</link>
      <guid>https://forem.com/aws-builders/how-to-create-an-iam-user-with-aws-cdk-k2o</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--HcDLeEZ7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4sxwgxayd3eftlo2ycan.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--HcDLeEZ7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4sxwgxayd3eftlo2ycan.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The AWS Identity and Access Management (IAM) service allow you to manage users and their permissions within your AWS environment. In this article, we will show you how to create an IAM user using the AWS Cloud Development Kit (CDK).&lt;/p&gt;

&lt;p&gt;The AWS CDK is an open-source software development framework for defining cloud infrastructure as code and provisioning it through AWS CloudFormation. With the AWS CDK, you can use familiar programming languages, such as TypeScript, Python, Java, and others, to write infrastructure-as-code scripts that define your AWS environment.&lt;/p&gt;

&lt;p&gt;To create an IAM user in the AWS CDK, you will need to write a script that creates an IAM user object and assigns the desired permissions to it. To get started, you will need to install the AWS CDK and initialize a new project in your preferred programming language.&lt;/p&gt;

&lt;p&gt;Here is an example of how to create an IAM user in the AWS CDK using TypeScript:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as cdk from 'aws-cdk-lib';
import * as iam from 'aws-cdk-lib/aws-iam';

export class IamUserStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const user = new iam.User(this, 'IamUser', {
      userName: 'iam-user',
    });

    const policy = new iam.Policy(this, 'Policy', {
      policyName: 'IamUserPolicy',
      statements: [
        new iam.PolicyStatement({
          actions: ['s3:ListBucket'],
          resources: ['arn:aws:s3:::*'],
        }),
      ],
    });

    policy.attachToUser(user);
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, we first import the AWS CDK and IAM modules from the &lt;code&gt;aws-cdk-lib&lt;/code&gt; library. Then, we define a new IAM user by creating an instance of the &lt;code&gt;User&lt;/code&gt; class and specifying the desired user name.&lt;/p&gt;

&lt;p&gt;Next, we create an IAM policy using the &lt;code&gt;Policy&lt;/code&gt; class. The policy defines the permissions that will be assigned to the IAM user. In this example, we are granting the &lt;code&gt;ListBucket&lt;/code&gt; action on all S3 buckets in the AWS account.&lt;/p&gt;

&lt;p&gt;Finally, we attach the policy to the IAM user using the &lt;code&gt;attachToUser&lt;/code&gt; method of the &lt;code&gt;Policy&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;Once you have written the script, you can use the AWS CDK CLI to deploy the IAM user to your AWS environment. To deploy the IAM user, you will need to run the following command in your terminal:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk deploy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The AWS CDK will then create a CloudFormation stack and deploy the IAM user to your AWS environment. You can verify the successful deployment of the IAM user by logging into the AWS Management Console and checking the IAM section.&lt;/p&gt;

&lt;p&gt;To destroy the above stack:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk destroy
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In conclusion, the AWS CDK provides an easy and convenient way to manage IAM users in your AWS environment. With the AWS CDK, you can define IAM users and their permissions using code, making it easy to automate the creation and management of IAM users in your AWS environment.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>awscdk</category>
      <category>cdk</category>
      <category>iac</category>
    </item>
    <item>
      <title>How to do Subnet Selection in AWS CDK</title>
      <dc:creator>Mikaeel Khalid</dc:creator>
      <pubDate>Fri, 03 Feb 2023 03:30:39 +0000</pubDate>
      <link>https://forem.com/aws-builders/how-to-do-subnet-selection-in-aws-cdk-ef2</link>
      <guid>https://forem.com/aws-builders/how-to-do-subnet-selection-in-aws-cdk-ef2</guid>
      <description>&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Gy2zu6KW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g73m1pwjlrzxnz72qwb7.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Gy2zu6KW--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g73m1pwjlrzxnz72qwb7.jpeg" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;AWS CDK, or Amazon Web Services Cloud Development Kit, is a software development framework for building and deploying cloud-based applications on Amazon Web Services. The CDK provides an easy-to-use and high-level API for building cloud-based applications and automates many of the underlying infrastructure management tasks. The CDK supports several programming languages, including TypeScript, Python, and Java.&lt;/p&gt;

&lt;p&gt;In this post, we will explore how to select a subnet in AWS CDK using TypeScript. Subnets are a logical partition of a VPC (Virtual Private Cloud) network and allow you to allocate network resources and control network access. The selection of the right subnet is important in order to ensure that your applications are deployed in the desired environment and can communicate with other resources in the VPC.&lt;/p&gt;

&lt;p&gt;We will start by creating a new AWS CDK project using TypeScript. To do this, you will need to have the AWS CDK CLI installed. You can install it by running the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g aws-cdk
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, create a new project by running the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cdk init sample-app --language typescript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a new AWS CDK project named &lt;code&gt;sample-app&lt;/code&gt; and set the programming language to TypeScript.&lt;/p&gt;

&lt;p&gt;Now, let's create a VPC with two subnets in the project. To do this, add the following code to the &lt;code&gt;lib/sample-app-stack.ts&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';

export class SampleAppStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const vpc = new ec2.Vpc(this, 'VPC', {
      cidr: '10.0.0.0/16',
      subnetConfiguration: [
        {
          cidrMask: 24,
          name: 'Subnet1',
          subnetType: ec2.SubnetType.PUBLIC,
        },
        {
          cidrMask: 24,
          name: 'Subnet2',
          subnetType: ec2.SubnetType.PRIVATE,
        },
      ],
    });
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, we are creating a new VPC with two subnets. The first subnet is a public subnet and the second subnet is a private subnet. The subnet configuration is specified using the &lt;code&gt;subnetConfiguration&lt;/code&gt; parameter, which takes an array of subnet configurations. Each subnet configuration contains the CIDR mask, subnet name, and subnet type.&lt;/p&gt;

&lt;p&gt;Next, we need to select the desired subnet to deploy our applications in. To do this, we can use the &lt;code&gt;selectSubnets&lt;/code&gt; method on the VPC object. The &lt;code&gt;selectSubnets&lt;/code&gt; method allows us to specify a filter function that determines which subnets should be selected.&lt;/p&gt;

&lt;p&gt;For example, to select the private subnet, we can add the following code to the &lt;code&gt;lib/sample-app-stack.ts&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';

export class SampleAppStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);

const vpc = new ec2.Vpc(this, 'VPC', {
  cidr: '10.0.0.0/16',
  subnetConfiguration: [
    {
      cidrMask: 24,
      name: 'Subnet1',
      subnetType: ec2.SubnetType.PUBLIC,
    },
    {
      cidrMask: 24,
      name: 'Subnet2',
      subnetType: ec2.SubnetType.PRIVATE,
    },
  ],
});

const privateSubnets = vpc.selectSubnets({
  subnetType: ec2.SubnetType.PRIVATE,
});

  } 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, we are selecting the private subnets using the &lt;code&gt;selectSubnets&lt;/code&gt; method and the &lt;code&gt;subnetType&lt;/code&gt; filter. The filter is set to &lt;code&gt;ec2.SubnetType.PRIVATE&lt;/code&gt;, which means that only the subnets with the type &lt;code&gt;PRIVATE&lt;/code&gt; will be selected. The selected subnets are stored in the &lt;code&gt;privateSubnets&lt;/code&gt; variable. Now that we have selected the desired subnet, we can use it to deploy our applications. For example, to deploy an EC2 instance in the private subnet, we can add the following code to the &lt;code&gt;lib/sample-app-stack.ts&lt;/code&gt; file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';

export class SampleAppStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    const vpc = new ec2.Vpc(this, 'VPC', {
      cidr: '10.0.0.0/16',
      subnetConfiguration: [
        {
          cidrMask: 24,
          name: 'Subnet1',
          subnetType: ec2.SubnetType.PUBLIC,
        },
        {
          cidrMask: 24,
          name: 'Subnet2',
          subnetType: ec2.SubnetType.PRIVATE,
        },
      ],
    });

    const privateSubnets = vpc.selectSubnets({
      subnetType: ec2.SubnetType.PRIVATE,
    });

    new ec2.Instance(this, 'Instance', {
      vpc,
      subnet: privateSubnets[0],
      instanceType: ec2.InstanceType.of(ec2.InstanceClass.T2, ec2.InstanceSize.MICRO),
      machineImage: new ec2.AmazonLinuxImage(),
    });

  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, we are creating a new EC2 instance using the &lt;code&gt;Instance&lt;/code&gt; class from the AWS CDK library. The instance is deployed in the VPC and the selected private subnet is specified using the &lt;code&gt;subnet&lt;/code&gt; property of the &lt;code&gt;Instance&lt;/code&gt; class. The instance is deployed in the first subnet of the &lt;code&gt;privateSubnets&lt;/code&gt; array, which is accessed using &lt;code&gt;privateSubnets[0]&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Additionally, we have specified the instance type, machine image, and other required properties to deploy the EC2 instance.&lt;/p&gt;

&lt;p&gt;In conclusion, the AWS CDK library provides a simple and straightforward way to select subnets in your VPCs. With the &lt;code&gt;selectSubnets&lt;/code&gt; method, you can easily filter the subnets based on different criteria, such as subnet type, availability zone, or tags, to deploy your applications in the desired subnets.&lt;/p&gt;

&lt;p&gt;By using the subnet selection feature, you can control the network access to your applications and maintain the security of your resources. Moreover, you can optimize your network architecture by deploying applications in subnets that best match their requirements and ensure the optimal performance of your applications.&lt;/p&gt;

</description>
      <category>aws</category>
      <category>awscdk</category>
      <category>cdk</category>
      <category>iac</category>
    </item>
  </channel>
</rss>
