Sub topic 2
Installing the CLI and creating a project in TypeScript or Python
This chapter assumes you have Node.js (a current LTS release), the AWS CLI with configured credentials, and working knowledge of TypeScript or Python. The CDK CLI is a Node.js program, so you need Node.js even if you write Python.
Install the CLI
The CLI is the aws-cdk package. It is separate from the construct library, aws-cdk-lib, which your project installs as a dependency.
npm install -g aws-cdk
cdk --versionIf cdk --version prints a version number, the install worked. Run aws sts get-caller-identity as well. The CDK uses the same credentials as the AWS CLI, so this confirms which account you are about to work in.
Create a project
cdk init generates a project from a template. It requires an empty directory, and it uses the directory name to name the project and its stack class.
mkdir my-app && cd my-app
cdk init app --language typescriptFor Python, change the language and set up the virtual environment it creates:
mkdir my-app && cd my-app
cdk init app --language python
source .venv/bin/activate
pip install -r requirements.txtOn Windows, activate with .venv\Scripts\activate.bat. The init command also runs git init and installs dependencies, so TypeScript projects are ready to use right away.
What you get
The template differs by language, but the roles of the files are the same.
| File or folder | Purpose |
|---|---|
| `cdk.json` | Tells the CLI how to run your app, and holds context values |
| `bin/my-app.ts` or `app.py` | Entry point that creates the `App` and your stacks |
| `lib/my-app-stack.ts` or `my_app/my_app_stack.py` | Your first stack, where you define resources |
| `test/` or `tests/` | A sample unit test |
The app field in cdk.json is the command the CLI runs to execute your code, for example npx ts-node --prefer-ts-exts bin/my-app.ts or python3 app.py.
The CLI does not parse your source files. It runs your program, and the program writes the output into cdk.out. That is why the language runtime must work before any cdk command does.
Common errors
- "cdk init cannot be run in a non-empty directory." Create a new empty directory and run it there.
- A version mismatch between the CLI and
aws-cdk-lib. The CLI must be at least as new as the library, or you will see a "Cloud assembly schema version mismatch" error. Update withnpm install -g aws-cdk@latest. - Python import errors. The virtual environment is not active. Activate it in each new terminal.
- "Unable to resolve AWS account to use." Credentials or a default region are missing. Set up a profile, or export
AWS_PROFILEandAWS_REGION.
Exercise
You run cdk init app --language python and then cdk synth, but get ModuleNotFoundError: No module named 'aws_cdk'. What is the likely cause, and what do you do?
Show answer
The virtual environment is not active, or the dependencies were not installed in it. Run source .venv/bin/activate and then pip install -r requirements.txt, then run cdk synth again.