'Get a list of stack dependencies using CDK cli

Is it somehow possible to get a list of the stacks that another stack depends on using the AWS CDK CLI? For example, given a list of stacks that looks something like:

const app = new App();
const alphaStack = new Stack(app);

const betaStack = new Stack(app);
betaStack.addDependency(alphaStack);

const gammaStack = new Stack(app);
gammaStack.addDependency(gammaStack);

const deltaStack = new Stack(app);
deltaStack.addDependency(betaStack);
deltaStack.addDependency(gammaStack);

I'd like to run a command that could give me output similar to the following:

$ cdk list-deps alpha-stack  # no result

$ cdk list-deps beta-stack
alpha-stack

$ cdk list-deps gamma-stack
alpha-stack

$ cdk list-deps delta-stack
beta-stack
gamma-stack

Specifically, I'd like to be able to run this before I deploy my stacks.



Solution 1:[1]

In case this helps anyone in the future; the following seems to solve the problem that I wanted to solve:

// the stack that we're interested in finding deps for
const stackName = "...";

// assuming app is as defined in the question
const { stacks } = app.synth();

stacks
  .find(({ stackName }) => stackName === searchForStackName)
  ?.dependencies.forEach((dep) => console.log(dep.id));

Caveats:

  • It's obviously not built-in to the CLI, and requires exposing app from your CDK definitions.
  • This does require calling synth on the app. Initially my understanding was that this creates some artifacts within AWS, which I wanted to avoid; but it seems that's not actually the case.
  • I'm not sure how reliable/stable dep.id is from this snippet/answer. Although it has so far been robust enough for my purposes, dependencies returns a list of CloudArtifact which I'm not certain if it will always represent a Stack.

Solution 2:[2]

Run cdk synth STACK_NAME

and you should find the dependencies from cdk.out/manifest.json

? jq '.artifacts.STACK_NAME.dependencies' cdk.out/manifest.json
[
  "STACK_NAME.assets"
  ...
]

Solution 3:[3]

I know this isn't quite as robust as what you're looking for but here is a useful command to find the stacks that depend on a particular export:

aws cloudformation list-imports --export-name EXPORT_NAME

Solution 4:[4]

You can also run

cdk destroy stackName

It will ask you for confirmation of the dependencies necesary to destroy your stack.

This is a dangerous operation and should be done with care because it can destroy your stacks.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Micheal Hill
Solution 2 Epeli
Solution 3 nsquires
Solution 4 Tomas G.