DEV Community

Cover image for Getting Started with AWS CDK on Linux: A Complete Setup Guide
Cristian Paniagua
Cristian Paniagua

Posted on

Getting Started with AWS CDK on Linux: A Complete Setup Guide

Getting Started with AWS CDK on Linux: A Complete Setup Guide

Infrastructure as Code (IaC) has revolutionized how we manage cloud resources, and AWS Cloud Development Kit (CDK) takes it to the next level by letting you define infrastructure using familiar programming languages. In this guide, I'll walk you through setting up AWS CDK on Linux, from installation to deploying your first stack.

What is AWS CDK?

AWS CDK is an open-source software development framework that allows you to define cloud infrastructure using programming languages like TypeScript, Python, Java, and C#. Unlike traditional CloudFormation templates written in JSON or YAML, CDK lets you leverage the full power of programming languages—including loops, conditionals, and object-oriented design patterns.

Why Choose CDK?

  • Type Safety: Catch errors at compile time, not deployment time
  • IDE Support: Get autocomplete, inline documentation, and refactoring tools
  • Reusability: Create and share constructs as libraries
  • Less Boilerplate: Write less code compared to raw CloudFormation
  • Higher-Level Abstractions: Use pre-built constructs that follow AWS best practices

Prerequisites

Before we dive in, make sure you have:

  • A Linux system (Ubuntu, Debian, Fedora, CentOS, or Arch)
  • An active AWS account
  • Basic familiarity with the terminal
  • Sudo privileges
  • About 15 minutes of your time

Step 1: Install Node.js

AWS CDK requires Node.js version 14.15.0 or higher.

Ubuntu/Debian

# Update package index
sudo apt update

# Install Node.js and npm
sudo apt install nodejs npm -y

# Or install latest LTS version using NodeSource
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt install nodejs -y
Enter fullscreen mode Exit fullscreen mode

Fedora/RHEL/CentOS

# Install Node.js and npm
sudo dnf install nodejs npm -y

# Or using NodeSource
curl -fsSL https://rpm.nodesource.com/setup_lts.x | sudo bash -
sudo dnf install nodejs -y
Enter fullscreen mode Exit fullscreen mode

Arch Linux

sudo pacman -S nodejs npm
Enter fullscreen mode Exit fullscreen mode

Verify the installation:

node --version
npm --version
Enter fullscreen mode Exit fullscreen mode

Pro Tip: If you need to manage multiple Node.js versions, consider using nvm (Node Version Manager).

Step 2: Install AWS CLI

The AWS Command Line Interface is essential for managing your AWS credentials and resources.

Ubuntu/Debian

sudo apt install awscli -y
Enter fullscreen mode Exit fullscreen mode

Fedora/RHEL/CentOS

sudo dnf install awscli -y
Enter fullscreen mode Exit fullscreen mode

Using pip (all distributions)

pip3 install awscli --user
Enter fullscreen mode Exit fullscreen mode

Verify the installation:

aws --version
Enter fullscreen mode Exit fullscreen mode

Step 3: Configure AWS Credentials

Now we need to configure your AWS credentials. You'll need your AWS Access Key ID and Secret Access Key. If you don't have these yet, create them in the AWS IAM Console.

Run the configuration command:

aws configure
Enter fullscreen mode Exit fullscreen mode

You'll be prompted to enter:

AWS Access Key ID [None]: YOUR_ACCESS_KEY_ID
AWS Secret Access Key [None]: YOUR_SECRET_ACCESS_KEY
Default region name [None]: us-east-1
Default output format [None]: json
Enter fullscreen mode Exit fullscreen mode

Security Note: Never commit your AWS credentials to version control. Consider using AWS IAM Identity Center (formerly AWS SSO) for enhanced security in production environments.

Step 4: Install AWS CDK

Now for the main event! Install the AWS CDK CLI globally using npm:

sudo npm install -g aws-cdk
Enter fullscreen mode Exit fullscreen mode

Verify the installation:

cdk --version
Enter fullscreen mode Exit fullscreen mode

Congratulations! AWS CDK is now installed on your Linux system. 🎉

Step 5: Bootstrap Your AWS Environment

Before you can deploy CDK apps, you need to bootstrap your AWS environment. This creates the necessary resources (like an S3 bucket) that CDK uses to store deployment artifacts.

cdk bootstrap
Enter fullscreen mode Exit fullscreen mode

You only need to do this once per AWS account/region combination.

Step 6: Create Your First CDK Project

Let's create a simple CDK project to verify everything is working correctly.

Create a Project Directory

mkdir my-first-cdk-app
cd my-first-cdk-app
Enter fullscreen mode Exit fullscreen mode

Initialize a CDK App

We'll use TypeScript for this example:

cdk init app --language typescript
Enter fullscreen mode Exit fullscreen mode

This creates a complete project structure with:

  • lib/ - Your CDK stack definitions
  • bin/ - The entry point for your CDK app
  • test/ - Unit tests
  • package.json - Node.js dependencies
  • cdk.json - CDK configuration

Install Dependencies

npm install
Enter fullscreen mode Exit fullscreen mode

Step 7: Build Your First Stack

Let's create a simple S3 bucket to demonstrate CDK in action.

Open lib/my-first-cdk-app-stack.ts and replace its contents with:

import * as cdk from 'aws-cdk-lib';
import * as s3 from 'aws-cdk-lib/aws-s3';
import { Construct } from 'constructs';

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

    // Create an S3 bucket with versioning enabled
    const bucket = new s3.Bucket(this, 'MyFirstBucket', {
      versioned: true,
      removalPolicy: cdk.RemovalPolicy.DESTROY,
      autoDeleteObjects: true,
      encryption: s3.BucketEncryption.S3_MANAGED,
    });

    // Output the bucket name
    new cdk.CfnOutput(this, 'BucketName', {
      value: bucket.bucketName,
      description: 'The name of the S3 bucket',
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

What's Happening Here?

  • We're importing the necessary CDK libraries
  • Creating an S3 bucket with versioning enabled
  • Setting a removal policy to destroy the bucket when the stack is deleted
  • Enabling automatic object deletion
  • Adding server-side encryption
  • Outputting the bucket name for easy reference

Step 8: Synthesize CloudFormation Template

Before deploying, let's see what CloudFormation template CDK generates:

cdk synth
Enter fullscreen mode Exit fullscreen mode

This command generates a CloudFormation template from your CDK code. You'll see YAML output in your terminal.

Step 9: Preview Changes

Before deploying, it's good practice to see what changes will be made:

cdk diff
Enter fullscreen mode Exit fullscreen mode

Step 10: Deploy Your Stack

Now for the moment of truth—let's deploy to AWS:

cdk deploy
Enter fullscreen mode Exit fullscreen mode

CDK will show you the changes and ask for confirmation. Type y and press Enter.

After a minute or two, your stack will be deployed! You'll see the bucket name in the outputs.

Verify in AWS Console

Head over to the S3 Console to see your newly created bucket.

Essential CDK Commands Cheat Sheet

Here are the commands you'll use most often:

Command Description
cdk init Initialize a new CDK project
cdk synth Synthesize CloudFormation template
cdk diff Compare deployed stack with current state
cdk deploy Deploy stack to AWS
cdk destroy Delete stack from AWS
cdk list List all stacks in the app
cdk doctor Check for potential problems
cdk watch Watch for changes and deploy automatically

Step 11: Clean Up

To avoid incurring charges, let's destroy the stack:

cdk destroy
Enter fullscreen mode Exit fullscreen mode

Confirm by typing y when prompted.

Best Practices for CDK Development

Now that you have CDK set up, here are some best practices to follow:

1. Use TypeScript for Type Safety

TypeScript provides excellent IDE support and catches errors before deployment:

// TypeScript will catch this error at compile time
const bucket = new s3.Bucket(this, 'MyBucket', {
  versioned: 'yes', // ❌ Error: Type 'string' is not assignable to type 'boolean'
});
Enter fullscreen mode Exit fullscreen mode

2. Organize Your Stacks

For larger projects, separate concerns into multiple stacks:

// networking-stack.ts
export class NetworkingStack extends cdk.Stack { }

// database-stack.ts
export class DatabaseStack extends cdk.Stack { }

// application-stack.ts
export class ApplicationStack extends cdk.Stack { }
Enter fullscreen mode Exit fullscreen mode

3. Use Environment Variables

Make your stacks reusable across environments:

const app = new cdk.App();

new MyStack(app, 'DevStack', {
  env: { account: '123456789', region: 'us-east-1' },
  stage: 'dev',
});

new MyStack(app, 'ProdStack', {
  env: { account: '987654321', region: 'us-west-2' },
  stage: 'prod',
});
Enter fullscreen mode Exit fullscreen mode

4. Leverage Constructs

Use high-level constructs (L2 and L3) that encapsulate best practices:

// L1 (low-level) - more verbose
new s3.CfnBucket(this, 'MyBucket', {
  bucketName: 'my-bucket',
  versioningConfiguration: {
    status: 'Enabled',
  },
});

// L2 (high-level) - recommended
new s3.Bucket(this, 'MyBucket', {
  versioned: true,
});
Enter fullscreen mode Exit fullscreen mode

5. Write Tests

CDK supports unit testing out of the box:

import { Template } from 'aws-cdk-lib/assertions';
import * as MyStack from '../lib/my-stack';

test('S3 Bucket Created', () => {
  const app = new cdk.App();
  const stack = new MyStack.MyStack(app, 'MyTestStack');
  const template = Template.fromStack(stack);

  template.hasResourceProperties('AWS::S3::Bucket', {
    VersioningConfiguration: {
      Status: 'Enabled',
    },
  });
});
Enter fullscreen mode Exit fullscreen mode

Run tests with:

npm test
Enter fullscreen mode Exit fullscreen mode

Troubleshooting Common Issues

Issue: "Command not found: cdk"

Solution: Make sure npm's global bin directory is in your PATH:

echo 'export PATH="$HOME/.npm-packages/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc
Enter fullscreen mode Exit fullscreen mode

Issue: "Need to perform AWS calls for account..."

Solution: Run cdk bootstrap to prepare your AWS environment.

Issue: Permission Denied Errors

Solution: Verify your AWS credentials have the necessary permissions. For development, you might need AdministratorAccess, but in production, use least-privilege IAM policies.

Issue: Permission denied when installing npm packages globally

If you get permission errors, configure npm to use a different directory:

mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc
npm install -g aws-cdk
Enter fullscreen mode Exit fullscreen mode

Issue: Node Version Conflicts

Solution: Use nvm to manage Node.js versions:

# Install nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.0/install.sh | bash

# Restart terminal or source profile
source ~/.bashrc

# Install and use Node.js 18
nvm install 18
nvm use 18
Enter fullscreen mode Exit fullscreen mode

Next Steps

Congratulations! You now have a fully functional AWS CDK development environment on Linux. Here's what you can explore next:

  1. Learn CDK Patterns: Check out the CDK Patterns website for common architecture patterns
  2. Explore AWS Constructs: Browse the Construct Hub for pre-built constructs
  3. Take the CDK Workshop: Complete the official CDK Workshop
  4. Build Real Projects: Try creating a serverless API, a static website, or a data pipeline
  5. Join the Community: Participate in the AWS CDK GitHub discussions

Useful Resources

Conclusion

AWS CDK transforms infrastructure management by bringing the power of programming languages to cloud infrastructure. With CDK installed on your Linux system, you're now equipped to define, deploy, and manage AWS resources using code you're already familiar with.

The journey from traditional CloudFormation to CDK might seem daunting at first, but the benefits—type safety, IDE support, reusability, and less boilerplate—make it well worth the investment.

What will you build with CDK? Share your projects in the comments below! 👇


Found this guide helpful? Follow me for more AWS and DevOps content. Have questions? Drop them in the comments!


Tags:#aws #cdk #devops #infrastructure #typescript #cloudformation #iac #tutorial #linux #beginners

Top comments (0)