├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .husky └── pre-commit ├── .prettierignore ├── .prettierrc ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── bin └── cli.ts ├── mermaidRenderConfig.json ├── package-lock.json ├── package.json ├── src ├── CloudFormationGraph.ts └── mermaid │ ├── MermaidConfig.ts │ ├── MermaidConfigSettings.ts │ ├── MermaidFlowchart.ts │ ├── MermaidFlowchartNode.ts │ ├── MermaidFlowchartNodeConfig.ts │ ├── MermaidFlowchartNodeShape.ts │ ├── MermaidFlowchartRelationship.ts │ ├── MermaidRenderer.ts │ └── index.ts ├── tsconfig-dev.json └── tsconfig.json /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "prettier", 4 | "plugin:import/errors", 5 | "plugin:import/warnings", 6 | "plugin:import/typescript", 7 | "plugin:jasmine/recommended", 8 | "plugin:@typescript-eslint/recommended" 9 | ], 10 | "plugins": ["prettier", "jasmine", "no-only-tests"], 11 | "parserOptions": { 12 | "ecmaVersion": 6, 13 | "sourceType": "module" 14 | }, 15 | "env": { 16 | "jasmine": true 17 | }, 18 | "overrides": [ 19 | { 20 | "files": ["./**/*.ts"], 21 | "parser": "@typescript-eslint/parser" 22 | } 23 | ], 24 | "rules": { 25 | "@typescript-eslint/no-unused-vars": [ 26 | "error", 27 | { "argsIgnorePattern": "^_" } 28 | ], 29 | "@typescript-eslint/no-explicit-any": ["error", { "fixToUnknown": true }], 30 | "no-only-tests/no-only-tests": "error", 31 | "@typescript-eslint/no-var-requires": "off" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | node_modules 3 | dist 4 | 5 | # Runtime app files 6 | cfn-stacks-graph.mmd 7 | cfn-stacks-graph.pdf 8 | cfn-stacks-graph.png 9 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | # SPDX-License-Identifier: Apache-2.0 5 | 6 | . "$(dirname "$0")/_/husky.sh" 7 | 8 | npx lint-staged 9 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | package-lock.json 4 | tsconfig.json 5 | tsconfig-dev.json 6 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "bracketSpacing": true, 4 | "tabWidth": 2, 5 | "trailingComma": "none" 6 | } -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | 3 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 4 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 5 | opensource-codeofconduct@amazon.com with any additional questions or comments. 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional 4 | documentation, we greatly value feedback and contributions from our community. 5 | 6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary 7 | information to effectively respond to your bug report or contribution. 8 | 9 | ## Reporting Bugs/Feature Requests 10 | 11 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 12 | 13 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already 14 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 15 | 16 | - A reproducible test case or series of steps 17 | - The version of our code being used 18 | - Any modifications you've made relevant to the bug 19 | - Anything unusual about your environment or deployment 20 | 21 | ## Contributing via Pull Requests 22 | 23 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 24 | 25 | 1. You are working against the latest source on the _main_ branch. 26 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 27 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 28 | 29 | To send us a pull request, please: 30 | 31 | 1. Fork the repository. 32 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 33 | 3. Ensure local tests pass. 34 | 4. Commit to your fork using clear commit messages. 35 | 5. Send us a pull request, answering any default questions in the pull request interface. 36 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 37 | 38 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 39 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 40 | 41 | ## Finding contributions to work on 42 | 43 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. 44 | 45 | ## Code of Conduct 46 | 47 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 48 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 49 | opensource-codeofconduct@amazon.com with any additional questions or comments. 50 | 51 | ## Security issue notifications 52 | 53 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. 54 | 55 | ## Licensing 56 | 57 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 58 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | aws-cloudformation-stacks-graph 2 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-cloudformation-stacks-graph [![NPM][npm-image]][npm-url] 2 | 3 | Generate a network diagram of the CloudFormation stacks using the import/export dependencies that exist amongst them. 4 | 5 | This helps to visualize the dependency complexity between various stacks in an application and shows the deployment order for these stacks. 6 | 7 | ### Usage 8 | 9 | 1. Install the application 10 | 11 | ```shell 12 | npm install --global aws-cloudformation-stacks-graph 13 | ``` 14 | 15 | 2. Run the application against all stacks in a given AWS account and region 16 | 17 | ```shell 18 | cfn-stacks-graph --profile="profile" --region="your-region" 19 | ``` 20 | 21 | ### Parameters 22 | 23 | #### `--profile ` 24 | 25 | The AWS CLI named profile to use. If available, `AWS_PROFILE` environment variable is used if this parameter is not specified, otherwise uses 'default'. 26 | 27 | #### `--region ` 28 | 29 | The AWS region to use. Uses `us-east-1` if this parameter is not specified. 30 | 31 | #### `--output ` 32 | 33 | Output file name to use. Uses 'cfn-stacks-graph' if this parameter is not specified. 34 | 35 | #### `--format ` 36 | 37 | Output file format to use - should be 'pdf', 'png', or 'svg'. Uses 'pdf' if this parameter is invalid or not specified. 38 | 39 | ### Technical Notes 40 | 41 | This uses the Mermaid-JS (https://mermaid-js.github.io/) library / 42 | Mermaid-CLI (https://github.com/mermaidjs/mermaid.cli) to render the graph of the information. 43 | 44 | The AWS SDKv3 for Javascript is used to gather the stack information. 45 | 46 | An intermediate file named `cfn-stacks-graph.mmd` will be generated as part of running this application. This is the 47 | config file leveraged by mermaid to render the actual graph 48 | 49 | ### IAM Permissions Needed 50 | 51 | A policy attached to your role must have the following minimum permissions: 52 | 53 | ```json 54 | { 55 | "Effect": "Allow", 56 | "Action": [ 57 | "cloudformation:ListExports", 58 | "cloudformation:ListImports", 59 | "cloudformation:ListStacks" 60 | ], 61 | "Resource": "*" 62 | } 63 | ``` 64 | 65 | ### Security 66 | 67 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information. 68 | 69 | ### License 70 | 71 | This project is licensed under the Apache-2.0 License. 72 | 73 | [npm-image]: https://img.shields.io/npm/v/aws-cloudformation-stacks-graph 74 | [npm-url]: https://www.npmjs.com/package/aws-cloudformation-stacks-graph 75 | -------------------------------------------------------------------------------- /bin/cli.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | // SPDX-License-Identifier: Apache-2.0 5 | 6 | import process from 'process'; 7 | 8 | import args from 'args'; 9 | 10 | import { CloudFormationGraph } from '../src/CloudFormationGraph'; 11 | import * as mermaid from '../src/mermaid'; 12 | 13 | args 14 | .option( 15 | 'profile', 16 | "The AWS CLI named profile to use. If available, 'AWS_PROFILE' environment variable is used.", 17 | 'default' 18 | ) 19 | .option('region', 'The AWS region to use.', 'us-east-1') 20 | .option('output', 'Output file name', 'cfn-stacks-graph') 21 | .option('format', 'Output file format. Should be pdf, png or svg.', 'pdf'); 22 | 23 | process.on('unhandledRejection', (err) => { 24 | console.error(err instanceof Error ? err.message : err); 25 | process.exit(-1); 26 | }); 27 | 28 | (async () => { 29 | const flags = args.parse(process.argv); 30 | const profile: string = 31 | flags.profile === 'default' 32 | ? process.env.AWS_PROFILE || 'default' 33 | : flags.profile; 34 | const region: string = flags.region; 35 | 36 | const extension = ['pdf', 'png', 'svg'].includes(flags.format.toLowerCase()) 37 | ? flags.format.toLowerCase() 38 | : 'pdf'; 39 | 40 | const stacksGraphOutput = `${flags.output}.${extension}`; 41 | 42 | const graph = new CloudFormationGraph(); 43 | const config = await graph.query(profile, region); 44 | 45 | console.log('Rendering...'); 46 | const renderer = new mermaid.MermaidRenderer(); 47 | await renderer.render(config, stacksGraphOutput); 48 | 49 | console.log('See output files: '); 50 | console.log(stacksGraphOutput); 51 | 52 | await renderer.cleanIntermediateFiles(); 53 | 54 | process.exit(0); 55 | })(); 56 | -------------------------------------------------------------------------------- /mermaidRenderConfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "maxTextSize": 99999999, 3 | "flowchart": { 4 | "diagramPadding": 1, 5 | "htmlLabels": true, 6 | "nodeSpacing": 50, 7 | "rankSpacing": 50, 8 | "curve": "basis", 9 | "defaultRenderer": "dagre-d3", 10 | "useMaxWidth": false 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "aws-cloudformation-stacks-graph", 3 | "version": "1.2.2", 4 | "description": "Generate a network diagram of the CloudFormation stacks using the import/export dependencies that exist amongst them.", 5 | "keywords": [ 6 | "aws cloudformation", 7 | "stacks", 8 | "graph", 9 | "network diagram", 10 | "dependency diagram" 11 | ], 12 | "homepage": "https://github.com/awslabs/aws-cloudformation-stacks-graph#readme", 13 | "repository": { 14 | "type": "git", 15 | "url": "https://github.com/awslabs/aws-cloudformation-stacks-graph" 16 | }, 17 | "license": "Apache-2.0", 18 | "contributors": [ 19 | { 20 | "name": "Sebastian Carreras", 21 | "email": "carreseb@amazon.com" 22 | }, 23 | { 24 | "name": "Hari Pachuveetil", 25 | "email": "pachuvee@amazon.com" 26 | } 27 | ], 28 | "types": "./dist/__types__", 29 | "bin": { 30 | "cfn-stacks-graph": "dist/bin/cli.js" 31 | }, 32 | "files": [ 33 | "bin", 34 | "dist", 35 | "mermaidRenderConfig.json" 36 | ], 37 | "scripts": { 38 | "prebuild": "npm run clean", 39 | "build": "tsc", 40 | "prebuild:dev": "npm run clean", 41 | "build:dev": "tsc --build ./tsconfig-dev.json", 42 | "clean": "rm -rf dist", 43 | "lint": "prettier --check \"./**/*.{js,ts,json,md}\" && eslint \"./**/*.{js,ts}\" && sort-package-json --check package.json", 44 | "lint:fix": "prettier --write \"./**/*.{js,ts,json,md}\" && eslint --fix \"./**/*.{js,ts}\" && sort-package-json package.json", 45 | "precommit:eslint": "eslint --fix", 46 | "precommit:prettier": "prettier --write", 47 | "precommit:sort-package-json": "sort-package-json", 48 | "prepare": "husky install", 49 | "prepublishOnly": "npm run lint:fix && npm run build", 50 | "test": "echo 'No Unit Tests Yet'" 51 | }, 52 | "lint-staged": { 53 | "**/*.{js,ts,json,md}": [ 54 | "npm run precommit:prettier" 55 | ], 56 | "**/*.{js,ts}": [ 57 | "npm run precommit:eslint" 58 | ], 59 | "**/package.json": [ 60 | "npm run precommit:sort-package-json" 61 | ] 62 | }, 63 | "dependencies": { 64 | "@aws-sdk/client-cloudformation": "^3.183.0", 65 | "@aws-sdk/credential-provider-node": "^3.183.0", 66 | "@mermaid-js/mermaid-cli": "^9.1.7", 67 | "args": "^5.0.3" 68 | }, 69 | "devDependencies": { 70 | "@types/args": "^5.0.0", 71 | "@types/node": "^18.8.2", 72 | "@typescript-eslint/eslint-plugin": "~5.39.0", 73 | "@typescript-eslint/parser": "~5.39.0", 74 | "eslint": "~8.24.0", 75 | "eslint-config-prettier": "~8.5.0", 76 | "eslint-plugin-import": "~2.26.0", 77 | "eslint-plugin-jasmine": "~4.1.3", 78 | "eslint-plugin-no-only-tests": "~3.0.0", 79 | "eslint-plugin-prettier": "~4.2.1", 80 | "husky": "~8.0.1", 81 | "import-sort-style-module": "~6.0.0", 82 | "lint-staged": "~13.0.3", 83 | "prettier": "~2.7.1", 84 | "prettier-plugin-import-sort": "~0.0.7", 85 | "sort-package-json": "~2.0.0", 86 | "typescript": "^4.8.4" 87 | }, 88 | "importSort": { 89 | ".js, .ts": { 90 | "style": "module", 91 | "parser": "typescript" 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/CloudFormationGraph.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import * as cfn from '@aws-sdk/client-cloudformation'; 5 | import { defaultProvider } from '@aws-sdk/credential-provider-node'; 6 | 7 | import * as mermaid from './mermaid'; 8 | import { MermaidFlowchartNodeShape } from './mermaid'; 9 | 10 | export class CloudFormationGraph { 11 | async query(profile: string, region: string): Promise { 12 | const client = new cfn.CloudFormationClient({ 13 | credentials: defaultProvider({ 14 | profile: profile 15 | }), 16 | region: region 17 | }); 18 | 19 | console.log('Getting Stack Information'); 20 | const summaries = await CloudFormationGraph.getStackSummaries(client); 21 | console.log('Getting Stack Exports'); 22 | const exports = await CloudFormationGraph.getStackExports(client); 23 | console.log('Getting Stack Imports'); 24 | const imports = await CloudFormationGraph.getStackImports(client, exports); 25 | 26 | // Minimize the length of the NodeIDs since mermaid has a length limitation 27 | const stackNodeIds: Map = new Map(); 28 | summaries.forEach((summary, index) => { 29 | const nodeId = `S${index}`; 30 | stackNodeIds.set(summary.StackId, nodeId); 31 | }); 32 | 33 | const nodes: Map = new Map< 34 | string, 35 | mermaid.MermaidFlowchartNode 36 | >(); 37 | 38 | const flowchart = new mermaid.MermaidFlowchart(); 39 | summaries.forEach((summary) => { 40 | const nodeId = stackNodeIds.get(summary.StackId); 41 | 42 | const node = flowchart.addNode(nodeId, { 43 | displayText: summary.StackName, 44 | fillColor: null, 45 | shape: MermaidFlowchartNodeShape.Rectangle 46 | }); 47 | nodes.set(summary.StackId, node); 48 | }); 49 | 50 | // Import/Export Dependencies 51 | imports.forEach((i) => { 52 | const parentNode = nodes.get(i.exportingStackId); 53 | i.importingStackNames.forEach((importingStackName) => { 54 | const childStack = summaries.find( 55 | (s) => s.StackName === importingStackName 56 | ); 57 | if (childStack) { 58 | const childNode = nodes.get(childStack.StackId); 59 | // Dont add duplicate relationships 60 | if (flowchart.hasRelationship(parentNode, childNode) == false) { 61 | flowchart.addRelationship(parentNode, childNode); 62 | } 63 | } 64 | }); 65 | }); 66 | 67 | // Nested Stack dependencies 68 | summaries.forEach((s) => { 69 | if ( 70 | s.ParentId !== undefined && 71 | s.ParentId !== null && 72 | s.ParentId !== '' 73 | ) { 74 | if (s.ParentId === s.StackId) { 75 | // This is the root of the nested stack 76 | // We do not need to draw a dependency here 77 | return; 78 | } 79 | 80 | const parentNode = nodes.get(s.ParentId); 81 | const childNode = nodes.get(s.StackId); 82 | 83 | console.log( 84 | `found a nested stack: ${s.StackName} from ${s.StackId} to ${s.ParentId}` 85 | ); 86 | 87 | if (parentNode && childNode) { 88 | if (flowchart.hasRelationship(parentNode, childNode) == false) { 89 | flowchart.addRelationship(parentNode, childNode); 90 | } 91 | } 92 | } 93 | }); 94 | 95 | return flowchart.renderMermaidConfig(); 96 | } 97 | 98 | private static async getStackSummaries( 99 | client: cfn.CloudFormationClient 100 | ): Promise> { 101 | let nextToken: string = null; 102 | const summaries: Array = new Array(); 103 | while (true) { 104 | const listStacksCommand = new cfn.ListStacksCommand({ 105 | NextToken: nextToken 106 | }); 107 | 108 | const result: cfn.ListStacksOutput = await client.send(listStacksCommand); 109 | summaries.push(...result.StackSummaries); 110 | 111 | nextToken = result.NextToken; 112 | if (nextToken == null) { 113 | break; 114 | } 115 | } 116 | 117 | return summaries; 118 | } 119 | 120 | private static async getStackExports( 121 | client: cfn.CloudFormationClient 122 | ): Promise> { 123 | let nextToken: string = null; 124 | const exports: Array = new Array(); 125 | 126 | while (true) { 127 | const listExportsCommand = new cfn.ListExportsCommand({ 128 | NextToken: nextToken 129 | }); 130 | 131 | const result: cfn.ListExportsCommandOutput = await client.send( 132 | listExportsCommand 133 | ); 134 | exports.push(...result.Exports); 135 | 136 | nextToken = result.NextToken; 137 | if (nextToken == null) { 138 | break; 139 | } 140 | } 141 | 142 | return exports; 143 | } 144 | 145 | private static async getStackImports( 146 | client: cfn.CloudFormationClient, 147 | exports: Array 148 | ): Promise> { 149 | const associations: Array = new Array(); 150 | 151 | for (let x = 0; x < exports.length; x++) { 152 | const exp = exports[x]; 153 | 154 | const stackNamesUsingExport = 155 | await CloudFormationGraph.getStackNamesUsingExport(client, exp.Name); 156 | 157 | const association: StackAssociation = new StackAssociation(); 158 | association.exportingStackId = exp.ExportingStackId; 159 | association.exportingStackName = exp.Name; 160 | association.importingStackNames = stackNamesUsingExport; 161 | associations.push(association); 162 | } 163 | 164 | return associations; 165 | } 166 | 167 | private static async getStackNamesUsingExport( 168 | client: cfn.CloudFormationClient, 169 | exportName: string 170 | ): Promise> { 171 | console.log(`Looking for stacks importing: ${exportName}`); 172 | let nextToken: string = null; 173 | const stackNamesUsingExport: Array = new Array(); 174 | 175 | try { 176 | while (true) { 177 | const listImports = new cfn.ListImportsCommand({ 178 | NextToken: nextToken, 179 | ExportName: exportName 180 | }); 181 | 182 | const response: cfn.ListImportsOutput = await client.send(listImports); 183 | stackNamesUsingExport.push(...response.Imports); 184 | 185 | nextToken = response.NextToken; 186 | if (nextToken == null) { 187 | break; 188 | } 189 | } 190 | } catch (error: unknown) { 191 | // This throws an error if there are no imports 192 | } 193 | 194 | return stackNamesUsingExport; 195 | } 196 | } 197 | 198 | class StackAssociation { 199 | exportingStackId: string; 200 | exportingStackName: string; 201 | importingStackNames: Array; 202 | } 203 | -------------------------------------------------------------------------------- /src/mermaid/MermaidConfig.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { MermaidConfigSettings } from './MermaidConfigSettings'; 5 | 6 | export interface MermaidConfig { 7 | code: string; 8 | mermaid: MermaidConfigSettings; 9 | updateEditor: boolean; 10 | } 11 | -------------------------------------------------------------------------------- /src/mermaid/MermaidConfigSettings.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export interface MermaidConfigSettings { 5 | theme: string; 6 | } 7 | -------------------------------------------------------------------------------- /src/mermaid/MermaidFlowchart.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { MermaidConfig } from './MermaidConfig'; 5 | import { MermaidFlowchartNode } from './MermaidFlowchartNode'; 6 | import { MermaidFlowchartNodeConfig } from './MermaidFlowchartNodeConfig'; 7 | import { MermaidFlowchartRelationship } from './MermaidFlowchartRelationship'; 8 | 9 | export class MermaidFlowchart { 10 | private _nodes: Map; 11 | private _relationships: Array; 12 | 13 | constructor() { 14 | this._nodes = new Map(); 15 | this._relationships = new Array(); 16 | } 17 | 18 | addNode( 19 | id: string, 20 | config: MermaidFlowchartNodeConfig 21 | ): MermaidFlowchartNode { 22 | const nodeExists = this.getNode(id); 23 | if (nodeExists !== null) { 24 | throw new Error(`node with id ${id} already exists`); 25 | } 26 | 27 | const node = new MermaidFlowchartNode(id, config); 28 | this._nodes.set(id, node); 29 | return node; 30 | } 31 | 32 | hasRelationship( 33 | parentNode: MermaidFlowchartNode, 34 | childNode: MermaidFlowchartNode 35 | ): boolean { 36 | const exists = this._relationships.some((r) => { 37 | if (parentNode.id == r.parent.id && childNode.id == r.child.id) { 38 | return true; 39 | } 40 | return false; 41 | }); 42 | return exists; 43 | } 44 | 45 | addRelationship( 46 | parentNode: MermaidFlowchartNode, 47 | childNode: MermaidFlowchartNode 48 | ): void { 49 | const relationship = new MermaidFlowchartRelationship( 50 | parentNode, 51 | childNode 52 | ); 53 | this._relationships.push(relationship); 54 | } 55 | 56 | renderMermaidConfig(): MermaidConfig { 57 | const graphConfig = new Array(); 58 | 59 | // Render the nodes themselves 60 | this._nodes.forEach((node) => { 61 | const nodeDef = node.renderNodeDefinition(); 62 | graphConfig.push(nodeDef); 63 | }); 64 | 65 | // Render the relationships 66 | this._relationships.forEach((relationship) => { 67 | const relationshipDef = relationship.renderRelationship(); 68 | graphConfig.push(relationshipDef); 69 | }); 70 | 71 | // Style the nodes 72 | this._nodes.forEach((node) => { 73 | const nodeStyle = node.renderNodeStyle(); 74 | if (nodeStyle != null) { 75 | graphConfig.push(nodeStyle); 76 | } 77 | }); 78 | 79 | const indentedConfig = graphConfig.map((line) => ` ${line}`); 80 | 81 | const mermaidCode = Array(); 82 | mermaidCode.push('graph LR'); 83 | mermaidCode.push(...indentedConfig); 84 | const mermaidCodeText: string = mermaidCode.join('\n'); 85 | 86 | const config = { 87 | code: mermaidCodeText, 88 | mermaid: { 89 | theme: 'default' 90 | }, 91 | updateEditor: false 92 | }; 93 | 94 | return config; 95 | } 96 | 97 | private getNode(id: string): MermaidFlowchartNode | null { 98 | const node = this._nodes.get(id); 99 | if (node) { 100 | return node; 101 | } 102 | 103 | return null; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/mermaid/MermaidFlowchartNode.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { MermaidFlowchartNodeConfig } from './MermaidFlowchartNodeConfig'; 5 | import { MermaidFlowchartNodeShape } from './MermaidFlowchartNodeShape'; 6 | 7 | export class MermaidFlowchartNode { 8 | constructor(id: string, config: MermaidFlowchartNodeConfig) { 9 | this.id = id; 10 | this.config = config; 11 | } 12 | 13 | public readonly id: string; 14 | public readonly config: MermaidFlowchartNodeConfig; 15 | 16 | renderNodeDefinition(): string { 17 | let startTitleCharacter: string; 18 | let endTitleCharacter: string; 19 | switch (this.config.shape) { 20 | case MermaidFlowchartNodeShape.Rectangle: 21 | startTitleCharacter = '['; 22 | endTitleCharacter = ']'; 23 | break; 24 | case MermaidFlowchartNodeShape.Diamond: 25 | startTitleCharacter = '{'; 26 | endTitleCharacter = '}'; 27 | break; 28 | default: 29 | throw Error(`unknown node shape: ${this.config.shape}`); 30 | } 31 | 32 | const nodeLine = `${this.id}${startTitleCharacter}${this.config.displayText}${endTitleCharacter}`; 33 | return nodeLine; 34 | } 35 | 36 | renderNodeStyle(): string | null { 37 | if (this.config.fillColor === null) { 38 | return null; 39 | } 40 | 41 | return `style ${this.id} fill:${this.config.fillColor}`; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/mermaid/MermaidFlowchartNodeConfig.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { MermaidFlowchartNodeShape } from './MermaidFlowchartNodeShape'; 5 | 6 | export class MermaidFlowchartNodeConfig { 7 | displayText: string; 8 | fillColor: string = null; 9 | shape: MermaidFlowchartNodeShape = MermaidFlowchartNodeShape.Rectangle; 10 | } 11 | -------------------------------------------------------------------------------- /src/mermaid/MermaidFlowchartNodeShape.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export enum MermaidFlowchartNodeShape { 5 | Rectangle, 6 | Diamond 7 | } 8 | -------------------------------------------------------------------------------- /src/mermaid/MermaidFlowchartRelationship.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { MermaidFlowchartNode } from './MermaidFlowchartNode'; 5 | 6 | export class MermaidFlowchartRelationship { 7 | constructor(parent: MermaidFlowchartNode, child: MermaidFlowchartNode) { 8 | this.parent = parent; 9 | this.child = child; 10 | } 11 | 12 | public readonly parent: MermaidFlowchartNode; 13 | public readonly child: MermaidFlowchartNode; 14 | 15 | renderRelationship(): string { 16 | return `${this.parent.id} --> ${this.child.id}`; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/mermaid/MermaidRenderer.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { execSync } from 'child_process'; 5 | import { promises } from 'fs'; 6 | import path from 'path'; 7 | 8 | import { MermaidConfig } from './MermaidConfig'; 9 | 10 | export class MermaidRenderer { 11 | private static TempMermaidDefinitionFilePath = path.join( 12 | '.', 13 | 'cfn-stacks-graph.mmd' 14 | ); 15 | 16 | async render( 17 | mermaidConfig: MermaidConfig, 18 | outputFilePath: string 19 | ): Promise { 20 | await promises.writeFile( 21 | MermaidRenderer.TempMermaidDefinitionFilePath, 22 | mermaidConfig.code, 23 | { 24 | encoding: 'ascii' 25 | } 26 | ); 27 | 28 | const appInstallFolder = path.join(__dirname, '..', '..', '..'); 29 | const configFilePath = path.join( 30 | appInstallFolder, 31 | 'mermaidRenderConfig.json' 32 | ); 33 | const mermaidCli = path.join( 34 | appInstallFolder, 35 | 'node_modules', 36 | '.bin', 37 | 'mmdc' 38 | ); 39 | execSync( 40 | `${mermaidCli} --input ${MermaidRenderer.TempMermaidDefinitionFilePath} --output ${outputFilePath} --pdfFit --configFile=${configFilePath}`, 41 | { stdio: 'inherit' } 42 | ); 43 | } 44 | 45 | async cleanIntermediateFiles(): Promise { 46 | await promises.unlink(MermaidRenderer.TempMermaidDefinitionFilePath); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/mermaid/index.ts: -------------------------------------------------------------------------------- 1 | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | export * from './MermaidConfig'; 5 | export * from './MermaidConfigSettings'; 6 | export * from './MermaidFlowchart'; 7 | export * from './MermaidFlowchartNode'; 8 | export * from './MermaidFlowchartNodeConfig'; 9 | export * from './MermaidFlowchartNodeShape'; 10 | export * from './MermaidFlowchartRelationship'; 11 | export * from './MermaidRenderer'; 12 | -------------------------------------------------------------------------------- /tsconfig-dev.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | // Development specific 5 | "removeComments": false, 6 | "sourceMap": true, 7 | "watch": true, 8 | // Checks 9 | "noUnusedLocals": false, 10 | "allowUnreachableCode": true 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": true, 4 | "alwaysStrict": true, 5 | "downlevelIteration": true, 6 | "emitDecoratorMetadata": true, 7 | "esModuleInterop": true, 8 | "experimentalDecorators": true, 9 | "forceConsistentCasingInFileNames": true, 10 | "module": "commonjs", 11 | "moduleResolution": "node", 12 | "target": "es6", 13 | "outDir": "./dist", 14 | "declaration": true, 15 | "declarationDir": "./dist/__types__", 16 | "resolveJsonModule": true, 17 | // Production specific 18 | "removeComments": true, 19 | "sourceMap": false, 20 | "watch": false 21 | }, 22 | "include": [ 23 | "./bin", 24 | "./src" 25 | ] 26 | } 27 | --------------------------------------------------------------------------------