# How to Deploy MongoDB Atlas with AWS CDK in TypeScript

MongoDB Atlas, the industry’s leading developer data platform, simplifies application development and working with data for a wide variety of use cases, scales globally, and optimizes for price/performance as your data needs evolve over time. With Atlas, you can address the needs of modern applications faster to accelerate your go-to-market timelines, all while reducing data infrastructure complexity. Atlas offers a variety of features such as cloud backups, search, and easy integration with other cloud services. 

AWS Cloud Development Kit (CDK) is a tool provided by Amazon Web Services (AWS) that allows you to define infrastructure as code using familiar programming languages such as TypeScript, JavaScript, Python, Java, Go, and C#. 

MongoDB recently announced the GA for Atlas Integrations for CDK. This is an ideal use case for teams that want to leverage the TypeScript ecosystem and no longer want to manually provision AWS CloudFormation templates in YAML or JSON. Not a fan of TypeScript? No worries! MongoDB Atlas CDK Integrations also now support Python, Java, C#, and Go.

In this step-by-step guide, we will walk you through the entire process. Let's get started! 

## Setup

Before we start, you will need to do the following:

- Open a MongoDB Atlas account 
✅ Already have an AWS account? Atlas supports paying for usage via the AWS Marketplace (AWS MP) without any upfront commitment — simply sign up for MongoDB Atlas via AWS Marketplace.

- Create a MongoDB Atlas Programmatic API Key (PAK)

- Install and configure an AWS Account + AWS CLI

- Store your MongoDB Atlas PAK in AWS Secret Manager 

- Activate the below CloudFormation resources in the AWS region of your choice 

    - MongoDB::Atlas::Project
    - MongoDB::Atlas::Cluster
    - MongoDB::Atlas::DatabaseUser
    - MongoDB::Atlas::ProjectIpAccessList

## Step 1: Install AWS CDK

The AWS CDK is an open-source software (OSS) development framework for defining cloud infrastructure as code and provisioning it through AWS CloudFormation. It provides high-level components that preconfigure cloud resources with proven defaults, so you can build cloud applications without needing to be an expert. You can install it globally using npm:

```bash
npm install -g aws-cdk
```

This command installs AWS CDK. The optional -g flag allows you to use it globally anywhere on your machine.

## Step 2: Bootstrap CDK

Next, we need to bootstrap our AWS environment to create the necessary resources to manage the CDK apps. The `cdk bootstrap` command creates an Amazon S3 bucket for storing files and a CloudFormation stack to manage the resources.

```bash
cdk bootstrap aws://ACCOUNT_NUMBER/REGION
```

Replace ACCOUNT_NUMBER with your AWS account number, and REGION with the AWS region you want to use.

## Step 3: Initialize a New CDK app

Now we can initialize a new CDK app using TypeScript. This is done using the `cdk init` command:

```bash
cdk init app --language typescript
```

This command initializes a new CDK app in TypeScript language. It creates a new directory with the necessary files and directories for a CDK app.

## Step 4: Install MongoDB Atlas CDK

To manage MongoDB Atlas resources, we will need a specific CDK module called awscdk-resources-mongodbatlas (see more details on this package on our Construct Hub page). Let's install it:

```bash
npm install awscdk-resources-mongodbatlas
```

This command installs the MongoDB Atlas CDK module, which will allow us to define and manage MongoDB Atlas resources in our CDK app.

## Step 5: Replace the generated file with AtlasBasic CDK L3 repo example

Feel free to start coding if you are familiar with CDK already or if it’s easier, you can leverage the AtlasBasic CDK resource example in our repo (also included below). This is a simple CDK Level 3 resource that deploys a MongoDB Atlas project, cluster, database user, and project IP access List resources on your behalf. All you need to do is paste this in your “lib/YOUR_FILE.ts” directory, making sure to replace the generated file that is already there (which was created in Step 3). 

Please make sure to replace the `export class CdkTestingStack extends cdk.Stack` line with the specific folder name used in your specific environment. No other changes are required. 

```javascript
// This CDK L3 example creates a MongoDB Atlas project, cluster, databaseUser, and projectIpAccessList

import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { AtlasBasic } from 'awscdk-resources-mongodbatlas';

interface AtlasStackProps {
    readonly orgId: string;
    readonly profile: string;
    readonly clusterName: string;
    readonly region: string;
    readonly ip: string;
}

//Make sure to replace "CdkTestingStack" with your specific folder name used 
export class CdkTestingStack extends cdk.Stack {

    constructor(scope: Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        const atlasProps = this.getContextProps();
        const atlasBasic = new AtlasBasic(this, 'AtlasBasic', {
            clusterProps: {
                name: atlasProps.clusterName, 
                replicationSpecs:  
                    {
                        numShards: 1,
                        advancedRegionConfigs: [
                            {
                                analyticsSpecs: {
                                    ebsVolumeType: "STANDARD",
                                    instanceSize: "M10",
                                    nodeCount: 1
                                },
                                electableSpecs: {
                                    ebsVolumeType: "STANDARD",
                                    instanceSize: "M10",
                                    nodeCount: 3
                                },
                                priority: 7,
                                regionName: atlasProps.region,
                            }]
                    }]    
            },
            projectProps: {
                orgId: atlasProps.orgId,
            },
            ipAccessListProps: {
                accessList:[
                    { ipAddress: atlasProps.ip, comment: 'My first IP address' }
                ]
            },
            profile: atlasProps.profile,
        });
    }

    getContextProps(): AtlasStackProps {
        const orgId = this.node.tryGetContext('orgId');

        if (!orgId){
            throw "No context value specified for orgId. Please specify via the cdk context."
        }

        const profile = this.node.tryGetContext('profile') ?? 'default';
        const clusterName = this.node.tryGetContext('clusterName') ?? 'test-cluster';
        const region = this.node.tryGetContext('region') ?? "US_EAST_1";
        const ip = this.node.tryGetContext('ip');
        
        if (!ip){
            throw "No context value specified for ip. Please specify via the cdk context."
        }
        
        return {
            orgId,
            profile,
            clusterName,
            region,
            ip
        }
    }
}
```

## Step 6: Compare the deployed stack with the current state

It's always a good idea to check what changes the CDK will make before actually deploying the stack. Use `cdk diff` command to do so:

```bash
cdk diff --context orgId="YOUR_ORG" --context ip="YOUR_IP"
```

Replace YOUR_ORG with your MongoDB Atlas organization ID and YOUR_IP with your IP address. This command shows the proposed changes to be made in your infrastructure between the deployed stack and the current state of your app, notice highlights for any resources to be created, deleted, or modified. This is for review purposes only. No changes will be made to your infrastructure. 

## Step 7: Deploy the app

Finally, if everything is set up correctly, you can deploy the app:

```bash
cdk deploy --context orgId="YOUR_ORG" --context ip="YOUR_IP"
```

Again, replace YOUR_ORG with your MongoDB Atlas organization ID and YOUR_IP with your IP address. This command deploys your app using AWS CloudFormation.

## (Optional) Step 8: Clean up the deployed resources

Once you're finished with your MongoDB Atlas setup, you might want to clean up the resources you've provisioned to avoid incurring unnecessary costs. You can destroy the resources you've created using the cdk destroy command:

```bash
cdk destroy --context orgId="YOUR_ORG" --context ip="YOUR_IP"
```

This command will destroy the CloudFormation stack associated with your CDK app, effectively deleting all the resources that were created during the deployment process.

Congratulations! You have just deployed MongoDB Atlas with AWS CDK in TypeScript. Next, head to YouTube for a [full video step-by-step walkthrough and demo.

The MongoDB Atlas CDK resources are open-sourced under the Apache-2.0 license and we welcome community contributions. To learn more, see our contributing guidelines. 

The fastest way to get started is to create a MongoDB Atlas account from the AWS Marketplace. Go build with MongoDB Atlas and the AWS CDK today!