├── .dockerignore ├── .eslintignore ├── .eslintrc.yml ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── cli.js ├── cli.txt ├── graph.png ├── index.js ├── lib ├── aws-credentials.js ├── graph.js ├── log.js └── table.js ├── package-lock.json ├── package.json └── test ├── .eslintrc.yml ├── cli.js └── graph.js /.dockerignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | test/ 3 | .eslintignore 4 | .eslinterc.yml 5 | .gitignore 6 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules/** 2 | coverage/** 3 | -------------------------------------------------------------------------------- /.eslintrc.yml: -------------------------------------------------------------------------------- 1 | env: 2 | es6: true 3 | node: true 4 | parserOptions: 5 | ecmaVersion: 2020 6 | sourceType: module 7 | extends: 'eslint:recommended' 8 | rules: 9 | indent: 10 | - error 11 | - 2 12 | linebreak-style: 13 | - error 14 | - unix 15 | quotes: 16 | - error 17 | - single 18 | semi: 19 | - error 20 | - always 21 | no-console: 22 | - error 23 | - allow: [info, warn, error] 24 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | defaults: 4 | run: 5 | shell: bash 6 | jobs: 7 | build: 8 | runs-on: ['hyperenv', 'medium-eu-west-1'] 9 | strategy: 10 | matrix: 11 | node: ['18', '20'] 12 | name: Node.js ${{ matrix.node }} 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: actions/setup-node@v4 16 | with: 17 | node-version: ${{ matrix.node }} 18 | cache: npm 19 | - name: install dependencies 20 | run: npm ci 21 | - name: run tests 22 | run: npm test 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | widdix.log 3 | widdix-linux 4 | widdix-macos 5 | widdix-win.exe 6 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Release 2 | 3 | To release a new version: 4 | 5 | 1. Run `export VERSION="x.z.z"` 6 | 2. Update `version` in `package.json` and `package-lock.json`. 7 | 3. Commit changes. 8 | 4. Run `git tag "v${VERSION}" && git push --tags` 9 | 5. Run `npm publish`. 10 | 6. Build and push docker image: 11 | ``` 12 | docker build -t "widdix/widdix:v${VERSION}" . 13 | docker tag "widdix/widdix:v${VERSION}" widdix/widdix:latest 14 | docker push "widdix/widdix:v${VERSION}" 15 | docker push widdix/widdix:latest 16 | ``` 17 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM public.ecr.aws/docker/library/node:16 2 | 3 | WORKDIR /usr/src/app 4 | 5 | ENV NODE_ENV=production 6 | 7 | COPY package*.json ./ 8 | 9 | RUN npm ci --only=production 10 | 11 | COPY . . 12 | 13 | ENTRYPOINT [ "node", "index.js" ] 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # widdix CLI 2 | 3 | `widdix`, a CLI tool to manage [Free Templates for AWS CloudFormation](https://github.com/widdix/aws-cf-templates). 4 | 5 | > The widdix CLI is compatible with templates >= v6.13.0 6 | 7 | ## Install 8 | 9 | We provide three ways to install `widdix`. Via `npm`, Docker, or by downloading the binary manually. 10 | 11 | ### npm 12 | 13 | If you have `npx` installed (comes with `npm>=5.2.0`) you can prefix all `widdix` invocations with `npx`. E.g. `npx widdix list --all-profiles`. 14 | 15 | Or you can install `widdix` globally with `npm install -g widdix`. 16 | 17 | ### Docker 18 | 19 | Docker image available on Ducker Hub [widdix/widdix](https://hub.docker.com/r/widdix/widdix/). 20 | 21 | Usage: `docker run -it --rm -v "$HOME/.aws:/root/.aws:ro" widdix/widdix list --all-profiles` 22 | 23 | ### Binary 24 | 25 | > We don't provide binaries any longer since [pkg](https://www.npmjs.com/package/pkg) does not support ESM. 26 | 27 | ## AWS Authorization & Authentication (IAM) 28 | 29 | ### --env 30 | 31 | If you append the `--env` parameter, the following environment variables are used: `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `AWS_SESSION_TOKEN` 32 | 33 | ### --profile= 34 | 35 | If you append the `--profile=` parameter, the profile is loaded from ` ~/.aws/credentials` (MFA is supported). 36 | 37 | ### --all-profiles 38 | 39 | If you append the `--all-profiles` parameter, all profiles from ` ~/.aws/credentials` are loaded (MFA is supported). 40 | 41 | ### default 42 | 43 | If nothing is specified, the [AWS SDK for Node.js default behavior](https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/setting-credentials-node.html) applies. 44 | 45 | ## Available Commands 46 | 47 | ### List 48 | 49 | To list all your stacks in an AWS account, run: 50 | 51 | ``` 52 | widdix list 53 | ``` 54 | 55 | A sample output looks like this: 56 | 57 | ``` 58 | ----------------------------------------------------------------------------------------------------------------------------------------- 59 | | Stack Account | Stack Region | Stack Name | Template ID | Template Version | Template Drift | 60 | ----------------------------------------------------------------------------------------------------------------------------------------- 61 | | 123456789123 | eu-west-1 | operations-alert | operations/alert | 6.14.0 | false | 62 | | 123456789123 | eu-west-1 | jenkins-vpc-auth-proxy | security/auth-proxy-ha-github-orga | 6.14.0 | false | 63 | | 123456789123 | eu-west-1 | jenkins-ha-agents | jenkins/jenkins2-ha-agents | 6.13.0 (latest 6.14.0) | false | 64 | | 123456789123 | eu-west-1 | jenkins-vpc-ssh-bastion | vpc/vpc-ssh-bastion | 6.14.0 | false | 65 | | 123456789123 | eu-west-1 | jenkins-vpc-2azs | vpc/vpc-2azs | 6.14.0 | false | 66 | ----------------------------------------------------------------------------------------------------------------------------------------- 67 | ``` 68 | 69 | To filter a AWS single region, run: 70 | 71 | ``` 72 | widdix list --region=us-east-1 73 | ``` 74 | 75 | #### Columns 76 | 77 | | Column | Description | 78 | | ---------------- | -------------------------------------------------------------------------------------- | 79 | | Stack Account | AWS account alias or ID. | 80 | | Stack Region | AWS region, like `us-east-1`. | 81 | | Stack Name | Name of AWS CloudFormation stack. | 82 | | Template ID | Template id, like `vpc/vpc-2azs`. | 83 | | Template Version | Current version of the template. If an update is available it is added in parentheses. | 84 | | Template Drift | If you modified the template drift is detected. | 85 | 86 | ### Graph 87 | 88 | ![Graph](graph.png) 89 | 90 | To generate a graph in [DOT](https://graphviz.gitlab.io/_pages/doc/info/lang.html) format of your stacks in an AWS account, run: 91 | 92 | ``` 93 | widdix graph 94 | ``` 95 | 96 | To filter a single AWS region, run: 97 | 98 | ``` 99 | widdix graph --region=us-east-1 100 | ``` 101 | 102 | Do visualize the graph in a png file, pipe stdout to `dot`: 103 | 104 | ``` 105 | widdix graph | dot -Tpng > graph.png 106 | ``` 107 | 108 | If you don't have `dot` installed, you can also use Docker: 109 | 110 | ``` 111 | widdix graph | docker run -i robhaswell/dot-docker -Tpng > graph.png 112 | ``` 113 | 114 | ### Update 115 | 116 | If a new version of the template is released, you can update your existing stacks. To update all stacks in interactive mode, run: 117 | 118 | ``` 119 | widdix update 120 | ``` 121 | 122 | The update behaves as follows: 123 | 124 | 1. If no updates are available, an error is thrown. 125 | 1. If template drift is detected we do not recommend to update! You have to confirm this potentially destructive action by typing `yes`. 126 | 1. Planed changes (using AWS CloudFormation change sets) that are necessary to migrate to the new version are displayed. 127 | 1. You have to confirm the changes by typing `yes`. 128 | 1. Changes are applied and CloudWatch events are streamed to your screen. 129 | 130 | You can filter AWS CloudFormation stacks based on region and/or AWS CloudFormation stack name like this: 131 | 132 | ``` 133 | widdix update --region=us-east-1 --stack-name=vpc 134 | ``` 135 | 136 | ## Future Commands 137 | 138 | ### Catalogue 139 | 140 | List all available templates that can be installed. 141 | 142 | > Not yet implemented! 143 | 144 | ### Get 145 | 146 | Get information about a single stack. 147 | 148 | > Not yet implemented! 149 | 150 | ### Create 151 | 152 | Create a new stack from a template in the catalogue. If the template needs connect to dependent stacks, you will be asked to select one of the existing stacks (if available) or to create the dependent stack as well. 153 | 154 | > Not yet implemented! 155 | 156 | ### Delete 157 | 158 | > Not yet implemented! 159 | 160 | ## Config 161 | 162 | ### Proxy 163 | 164 | The `HTTPS_PROXY` environment variable is used if set. 165 | 166 | ## Debug 167 | 168 | If something goes wrong, a log file (`widdix.log`) is written to the current working directory. 169 | 170 | If you append the `--debug` parameter the log will be more verbose. 171 | -------------------------------------------------------------------------------- /cli.js: -------------------------------------------------------------------------------- 1 | import crypto from 'crypto'; 2 | import fs from 'fs'; 3 | import console from 'console'; 4 | import requestretry from 'requestretry'; 5 | import docopt from 'docopt'; 6 | import semver from 'semver'; 7 | import { HttpsProxyAgent } from 'hpagent'; 8 | import truncate from 'truncate-middle'; 9 | import md5 from 'md5'; 10 | import pLimit from 'p-limit'; 11 | import { EC2Client, DescribeRegionsCommand } from '@aws-sdk/client-ec2'; 12 | import { 13 | CloudFormationClient, 14 | GetTemplateSummaryCommand, 15 | GetTemplateCommand, 16 | DescribeChangeSetCommand, 17 | CreateChangeSetCommand, 18 | ExecuteChangeSetCommand, 19 | paginateDescribeStacks, 20 | paginateDescribeStackEvents, 21 | waitUntilChangeSetCreateComplete 22 | } from '@aws-sdk/client-cloudformation'; 23 | import { IAMClient, ListAccountAliasesCommand } from '@aws-sdk/client-iam'; 24 | import { STSClient, GetCallerIdentityCommand } from '@aws-sdk/client-sts'; 25 | import { fromIni, fromEnv } from '@aws-sdk/credential-providers'; 26 | import { NodeHttpHandler } from '@smithy/node-http-handler'; 27 | 28 | import { create as gcreate } from './lib/graph.js'; 29 | import { create as tcreate, print as tprint } from './lib/table.js'; 30 | import { warning, error, setLevel } from './lib/log.js'; 31 | import { fetchProfiles } from './lib/aws-credentials.js'; 32 | 33 | const { version } = JSON.parse(fs.readFileSync(new URL('./package.json', import.meta.url), {encoding: 'utf8'})); 34 | 35 | function generateAwsConfig(account, configOverrides) { 36 | const proxyConfig = {}; 37 | if ('HTTPS_PROXY' in process.env) { 38 | proxyConfig.requestHandler = new NodeHttpHandler({ 39 | httpAgent: new HttpsProxyAgent({ proxy: process.env.HTTPS_PROXY }), 40 | httpsAgent: new HttpsProxyAgent({ proxy: process.env.HTTPS_PROXY }) 41 | }); 42 | } 43 | return Object.assign({region: 'us-east-1'}, account.config, proxyConfig, configOverrides); 44 | } 45 | 46 | function generateAwsCloudFormationConfig(account, configOverrides) { 47 | const config = { 48 | apiVersion: '2010-05-15', 49 | maxAttempts: process.env.NODE_ENV === 'production' ? 12 : 1 50 | }; 51 | return generateAwsConfig(account, Object.assign({}, config, configOverrides)); 52 | } 53 | 54 | async function fetchTemplateSummary (account, url) { 55 | const cloudformation = new CloudFormationClient(generateAwsCloudFormationConfig(account, {})); 56 | return cloudformation.send(new GetTemplateSummaryCommand({ 57 | TemplateURL: url 58 | })); 59 | } 60 | 61 | async function detectTemplateDrift(account, stackRegion, stackName, templateId, templateVersion) { 62 | const cloudformation = new CloudFormationClient(generateAwsCloudFormationConfig(account, {region: stackRegion})); 63 | if (templateVersion === undefined) { 64 | return undefined; 65 | } else { 66 | const rawTemplate = await downloadS3File(`v${templateVersion}/${templateId}.yaml`); 67 | const liveTemplate = await cloudformation.send(new GetTemplateCommand({ 68 | StackName: stackName 69 | })); 70 | // CloudFormation replaces non-ascii chars with ? 71 | const rawMd5 = md5(rawTemplate.replace(/[^\x00-\x7F]/g, '?').trim()); // eslint-disable-line no-control-regex 72 | const liveMd5 = md5(liveTemplate.TemplateBody.trim()); 73 | return rawMd5 !== liveMd5; 74 | } 75 | } 76 | 77 | const downloadFileCache = new Map(); 78 | 79 | async function downloadS3File(key) { 80 | return downloadFile(`https://widdix-aws-cf-templates-releases-eu-west-1.s3.eu-west-1.amazonaws.com/${key}`); 81 | } 82 | 83 | async function downloadFile(url) { // includes caching 84 | if (downloadFileCache.has(url)) { 85 | return downloadFileCache.get(url); 86 | } 87 | const p = new Promise((resolve, reject) => { 88 | requestretry({ 89 | method: 'GET', 90 | url, 91 | maxAttempts: 5, 92 | retryDelay: 1000 93 | }, (err, res, body) => { 94 | if (err) { 95 | reject(err); 96 | } else { 97 | if (res.statusCode === 200) { 98 | resolve(body); 99 | } else { 100 | reject(new Error(`${url} 200 expected, received ${res.statusCode}: ${body}`)); 101 | } 102 | } 103 | }); 104 | }); 105 | downloadFileCache.set(url, p); 106 | return p; 107 | } 108 | 109 | async function fetchLatestTemplateVersion(input) { 110 | if (input['--latest-version'] !== null) { 111 | return input['--latest-version']; 112 | } 113 | const body = await downloadFile('https://github.com/widdix/aws-cf-templates/releases.atom'); 114 | return body.match(/(v[0-9.]*)<\/title>/i)[1].replace('v', ''); 115 | } 116 | 117 | function extractTemplateIDFromStack(stack) { 118 | const templateId = stack.Outputs.find((output) => output.OutputKey === 'TemplateID').OutputValue; 119 | if (templateId === undefined) { 120 | warning(`can not extract template id in ${stack.Region} for stack ${stack.StackName}`, stack); 121 | } 122 | return templateId; 123 | } 124 | 125 | function extractTemplateVersionFromStack(templateId, stack) { 126 | const output = stack.Outputs.find((output) => output.OutputKey === 'TemplateVersion'); 127 | if (output === undefined || output.OutputValue === '__VERSION__') { 128 | warning(`can not extract template version in ${stack.Region} for stack ${stack.StackName} (${templateId})`, stack); 129 | return undefined; 130 | } 131 | return output.OutputValue; 132 | } 133 | 134 | function extractParentStacksFromParameters(parameters) { 135 | return Object.keys(parameters) 136 | .filter(key => key.startsWith('Parent')) 137 | .filter(key => parameters[key] !== '') 138 | .map(key => ({ 139 | parameterName: key, 140 | stackName: parameters[key] 141 | })); 142 | } 143 | 144 | function initArrayIfUndefined(obj, name) { 145 | if (!Array.isArray(obj[name])) { 146 | obj[name] = []; 147 | } 148 | return obj; 149 | } 150 | 151 | async function fetchStacks(account, region) { 152 | const cloudformation = new CloudFormationClient(generateAwsCloudFormationConfig(account, {region: region})); 153 | const stacks = []; 154 | const paginator = paginateDescribeStacks({ 155 | client: cloudformation 156 | }, {}); 157 | for await (const page of paginator) { 158 | page.Stacks 159 | .map(stack => Object.assign({}, stack, {Region: region})) 160 | .map(stack => initArrayIfUndefined(stack, 'Parameters')) 161 | .map(stack => initArrayIfUndefined(stack, 'Outputs')) 162 | .forEach(stack => stacks.push(stack)); 163 | } 164 | return stacks; 165 | } 166 | 167 | async function fetchRegions(account, region) { 168 | if (region !== null) { 169 | return Promise.resolve([region]); 170 | } else { 171 | const ec2 = new EC2Client(generateAwsConfig(account, {apiVersion: '2016-11-15'})); 172 | const data = await ec2.send(new DescribeRegionsCommand({})); 173 | return data.Regions.map(region => region.RegionName); 174 | } 175 | } 176 | 177 | async function enrichStack(account, stack, input) { 178 | const templateId = extractTemplateIDFromStack(stack); 179 | const templateVersion = extractTemplateVersionFromStack(templateId, stack); 180 | const parameters = stack.Parameters.reduce((acc, parameter) => { 181 | acc[parameter.ParameterKey] = parameter.ParameterValue; 182 | return acc; 183 | }, {}); 184 | const parentStacks = extractParentStacksFromParameters(parameters); 185 | const isUpdateAvailable = (latestVersion, templateVersion) => { 186 | if (templateVersion === undefined) { // unreleased version, from git repo directly 187 | return undefined; 188 | } 189 | try { 190 | return semver.gt(latestVersion, templateVersion); 191 | } catch (e) { 192 | warning(`can not compare latest template version (v${latestVersion}) in ${stack.Region} for stack ${stack.StackName} (${templateId} v${templateVersion})`, e); 193 | return undefined; 194 | } 195 | }; 196 | const latestVersion = await fetchLatestTemplateVersion(input).catch(e => { 197 | warning(`can not get latest template version in ${stack.Region} for stack ${stack.StackName} (${templateId} v${templateVersion})`, e); 198 | return undefined; 199 | }); 200 | const templateDrift = await detectTemplateDrift(account, stack.Region, stack.StackName, templateId, templateVersion).catch(e => { 201 | warning(`can not get detect template drift in ${stack.Region} for stack ${stack.StackName} (${templateId} v${templateVersion})`, e); 202 | return undefined; 203 | }); 204 | return { 205 | account, 206 | region: stack.Region, 207 | name: stack.StackName, 208 | parameters, 209 | parentStacks, 210 | templateId, 211 | templateVersion, 212 | templateDrift, 213 | templateLatestVersion: latestVersion, 214 | templateUpdateAvailable: isUpdateAvailable(latestVersion, templateVersion) 215 | }; 216 | } 217 | 218 | async function fetchAllStacks(account, input) { 219 | const limit = pLimit(4); 220 | return fetchRegions(account, input['--region']) 221 | .then(regions => Promise.all(regions.map(region => fetchStacks(account, region)))) 222 | .then(stackLists => { 223 | return Promise.all( 224 | stackLists 225 | .flat() 226 | .filter(stack => !stack.StackName.startsWith('StackSet-')) 227 | .filter((stack) => { 228 | return stack.Outputs.some((output) => (output.OutputKey === 'TemplateID' && output.OutputValue.includes('/'))); 229 | }) 230 | .map((stack) => limit(() => enrichStack(account, stack, input))) 231 | ); 232 | }); 233 | } 234 | 235 | async function yes(stdconsole, stdin, question, alwaysYes) { 236 | if (alwaysYes === true) { 237 | return Promise.resolve(); 238 | } else { 239 | return new Promise((resolve, reject) => { 240 | stdin.once('data', b => { 241 | const answer = b.toString('utf8').replace(/[^a-z]/gi, '').toLowerCase(); 242 | if (answer === 'y' || answer === 'yes') { 243 | resolve(); 244 | } else { 245 | reject(new Error('abort')); 246 | } 247 | }); 248 | stdconsole.info(`${question} [y/N]`); 249 | }); 250 | } 251 | } 252 | 253 | async function createChangeSet(stack) { 254 | const cloudformation = new CloudFormationClient(generateAwsCloudFormationConfig(stack.account, {region: stack.region})); 255 | const changeSetName = `widdix-${crypto.randomBytes(16).toString('hex')}`; 256 | const templateURL = `https://s3-eu-west-1.amazonaws.com/widdix-aws-cf-templates-releases-eu-west-1/v${stack.templateLatestVersion}/${stack.templateId}.yaml`; 257 | const template = await fetchTemplateSummary(stack.account, templateURL); 258 | const parameters = template.Parameters.reduce((acc, parameter) => { 259 | acc[parameter.ParameterKey] = { 260 | default: parameter.DefaultValue, 261 | previous: stack.parameters[parameter.ParameterKey] 262 | }; 263 | return acc; 264 | }, {}); 265 | await cloudformation.send(new CreateChangeSetCommand({ 266 | ChangeSetName: changeSetName, 267 | StackName: stack.name, 268 | ChangeSetType: 'UPDATE', 269 | Description: `widdix-v${version}`, 270 | Parameters: Object.keys(parameters).map(key => { 271 | const parameter = parameters[key]; 272 | const ret ={ 273 | ParameterKey: key, 274 | }; 275 | if (parameter.previous !== undefined) { // existing parameter 276 | ret.UsePreviousValue = true; 277 | } else if (parameter.default !== undefined) { // new parameter with default 278 | ret.ParameterValue = parameter.default; 279 | } else { // new parameter without default 280 | throw new Error('not yet implemented: update contains new parameter (without default)'); // TODO implement 281 | } 282 | return ret; 283 | }), 284 | TemplateURL: templateURL, 285 | Capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM'] 286 | })); 287 | await waitUntilChangeSetCreateComplete({ 288 | client: cloudformation 289 | }, { 290 | StackName: stack.name, 291 | ChangeSetName: changeSetName 292 | }); 293 | const data = await cloudformation.send(new DescribeChangeSetCommand({ 294 | StackName: stack.name, 295 | ChangeSetName: changeSetName 296 | })); 297 | return { 298 | name: data.ChangeSetName, 299 | changes: data.Changes.map(change => ({ 300 | action: change.ResourceChange.Action, 301 | actionModifyReplacement: change.ResourceChange.Replacement, 302 | resource: { 303 | type: change.ResourceChange.ResourceType, 304 | id: change.ResourceChange.PhysicalResourceId 305 | } 306 | })) 307 | }; 308 | } 309 | 310 | async function timeout(ms) { 311 | return new Promise(resolve => setTimeout(resolve, ms)); 312 | } 313 | 314 | async function tailStackEvents(stack, changeSetType, eventCallback) { 315 | const cloudformation = new CloudFormationClient(generateAwsCloudFormationConfig(stack.account, {region: stack.region})); 316 | const publishedEventIds = new Set(); 317 | const publishEvent = (event) => { 318 | publishedEventIds.add(event.EventId); 319 | eventCallback(event); 320 | }; 321 | const fetchAll = async () => { 322 | const allEvents = []; 323 | const paginator = paginateDescribeStackEvents({ 324 | client: cloudformation 325 | }, { 326 | StackName: stack.name 327 | }); 328 | for await (const page of paginator) { 329 | page.StackEvents.forEach(event => allEvents.push(event)); 330 | } 331 | return allEvents; 332 | }; 333 | const ts = Date.now() + (60 * 60 * 1000); // TODO make timeout of 1 hour configurable 334 | while(Date.now() < ts) { 335 | await timeout(1000); 336 | const allEvents = await fetchAll(); 337 | const startEventIdx = allEvents.findIndex((event) => event.ResourceStatus === `${changeSetType}_IN_PROGRESS` && event.ResourceType === 'AWS::CloudFormation::Stack'); 338 | if (startEventIdx === -1) { 339 | continue; 340 | } 341 | const events = allEvents.slice(0, startEventIdx+1); 342 | const endEventIdx = events.findIndex((event) => event.ResourceStatus === `${changeSetType}_COMPLETE` && event.ResourceType === 'AWS::CloudFormation::Stack'); 343 | const relevantEvents = events.slice((endEventIdx === -1) ? 0 : endEventIdx).reverse(); 344 | relevantEvents 345 | .filter((event) => !publishedEventIds.has(event.EventId)) 346 | .forEach(publishEvent); 347 | if (endEventIdx === -1) { 348 | const mostRecentEvent = relevantEvents[relevantEvents.length-1]; 349 | if (mostRecentEvent.ResourceStatus === `${changeSetType}_FAILED` && mostRecentEvent.ResourceType === 'AWS::CloudFormation::Stack') { // failure 350 | throw new Error(`stack ${changeSetType.toLowerCase()} failed`); 351 | } else { 352 | continue; 353 | } 354 | } else { 355 | return relevantEvents; 356 | } 357 | } 358 | throw Error(`stack ${changeSetType.toLowerCase()} timed out`); 359 | } 360 | 361 | async function executeChangeSet(stack, changeSet, eventCallback) { 362 | const cloudformation = new CloudFormationClient(generateAwsCloudFormationConfig(stack.account, {region: stack.region})); 363 | await cloudformation.send(new ExecuteChangeSetCommand({ 364 | ChangeSetName: changeSet.name, 365 | StackName: stack.name 366 | })); 367 | await tailStackEvents(stack, 'UPDATE', eventCallback); 368 | } 369 | 370 | async function token(stdconsole, stdin, question) { 371 | return new Promise((resolve, reject) => { 372 | stdin.once('data', b => { 373 | const answer = b.toString('utf8').replace(/[^0-9]/gi, ''); 374 | if (answer.length !== 6) { 375 | reject(new Error('a token must have 6 digits')); 376 | } else { 377 | resolve(answer); 378 | } 379 | }); 380 | stdconsole.error(question); 381 | }); 382 | } 383 | 384 | async function enrichAwsAccount(account) { 385 | const iam = new IAMClient(generateAwsConfig(account, {apiVersion: '2010-05-08'})); 386 | const sts = new STSClient(generateAwsConfig(account, {apiVersion: '2011-06-15'})); 387 | let accountId = null; 388 | let accountAlias = null; 389 | try { 390 | const callerIdentityData = await sts.send(new GetCallerIdentityCommand({})); 391 | accountId = callerIdentityData.Account; 392 | } catch (e) { 393 | warning(`can not enrich account ${account.label} of type ${account.type} with id`, e); 394 | } 395 | try { 396 | const accountAliasesData = await iam.send(new ListAccountAliasesCommand({})); 397 | if (accountAliasesData.AccountAliases.length === 1) { 398 | accountAlias = accountAliasesData.AccountAliases[0]; 399 | } 400 | } catch (e) { 401 | warning(`can not enrich account ${account.label} of type ${account.type} with alias`, e); 402 | } 403 | return Object.assign({}, account, {alias: accountAlias, id: accountId}); 404 | } 405 | 406 | async function fetchAwsAccounts(stdconsole, stdin, input) { 407 | if (input['--env'] === true) { 408 | return [await enrichAwsAccount({ 409 | type: 'env', 410 | label: 'AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN', 411 | config: { 412 | credentials: fromEnv() 413 | } 414 | })]; 415 | } else if (input['--profile'] !== null || input['--all-profiles'] === true) { 416 | const profiles = await fetchProfiles(); 417 | const accounts = []; 418 | const keys = Object.keys(profiles); 419 | for (const key of keys) { 420 | if (input['--profile'] !== null && key !== input['--profile']) { 421 | continue; 422 | } 423 | const credentials = fromIni({ 424 | profile: key, 425 | mfaCodeProvider: async (mfaSerial) => token(stdconsole, stdin, `Please enter the MFA token for ${mfaSerial}`) 426 | }); 427 | accounts.push(await enrichAwsAccount({ 428 | type: 'profile', 429 | label: `profile ${key}`, 430 | config: { 431 | credentials 432 | } 433 | })); 434 | } 435 | if (accounts.length === 0) { 436 | if (input['--profile'] !== null) { 437 | throw new Error(`profile ${input['--profile']} not found`); 438 | } else { 439 | throw new Error('no profiles found'); 440 | } 441 | } 442 | return accounts; 443 | } else { 444 | return [await enrichAwsAccount({ 445 | type: 'default', 446 | label: 'default AWS Nodejs. SDK chain', 447 | config: {} 448 | })]; 449 | } 450 | } 451 | 452 | export function clearCache() { 453 | downloadFileCache.clear(); 454 | } 455 | 456 | function displayAccount(account) { 457 | if (account.alias !== null) { 458 | return account.alias; 459 | } 460 | if (account.id !== null) { 461 | return account.id; 462 | } 463 | return `${account.label} of type ${account.type}`; 464 | } 465 | 466 | export async function run(argv, stdout, stderr, stdin) { 467 | const cli = fs.readFileSync(new URL('./cli.txt', import.meta.url), {encoding: 'utf8'}); 468 | const stdconsole = new console.Console(stdout, stderr); 469 | const input = docopt.docopt(cli, { 470 | version, 471 | argv: argv 472 | }); 473 | 474 | if (input['--debug'] === true) { 475 | setLevel('debug'); 476 | } else { 477 | setLevel('info'); 478 | } 479 | 480 | if (input.list === true) { 481 | const accounts = await fetchAwsAccounts(stdconsole, stdin, input); 482 | const rows = []; 483 | for (const account of accounts) { 484 | try { 485 | const stacks = await fetchAllStacks(account, input); 486 | const accountRows = stacks.map((stack) => { 487 | const row = [displayAccount(account), stack.region, stack.name, stack.templateId]; 488 | if (stack.templateUpdateAvailable === true) { 489 | row.push(`${stack.templateVersion} (latest ${stack.templateLatestVersion})`); 490 | } else { 491 | row.push(stack.templateVersion); 492 | } 493 | row.push(stack.templateDrift); 494 | return row; 495 | }); 496 | rows.push(...accountRows); 497 | } catch (err) { 498 | error(`can not access account ${account.label} of type ${account.type}`, err); 499 | } 500 | } 501 | tprint(stdconsole, stdout.columns, ['Stack Account', 'Stack Region', 'Stack Name', 'Template ID', 'Template Version', 'Template Drift'], rows); 502 | } else if (input.graph === true) { 503 | const accounts = await fetchAwsAccounts(stdconsole, stdin, input); 504 | const intelligentLabelShortening = (label) => { 505 | return truncate(label, 12, 12, '...'); 506 | }; 507 | const groot = gcreate('root', `widdix-v${version}`); 508 | for (const account of accounts) { 509 | try { 510 | const stacks = await fetchAllStacks(account, input); 511 | const gaccount = groot.subgraph(account.id, displayAccount(account)); 512 | stacks.forEach(stack => { 513 | const gregion = gaccount.subgraph(stack.region, stack.region); 514 | let label = `${stack.templateId}\n${intelligentLabelShortening(stack.name)}\n`; 515 | if (stack.templateUpdateAvailable === true) { 516 | label += `${stack.templateVersion} (latest ${stack.templateLatestVersion})`; 517 | } else { 518 | label += stack.templateVersion; 519 | } 520 | gregion.create(`${stack.account.id}:${stack.region}:${stack.name}`, label, stack); 521 | }); 522 | stacks.forEach(stack => { 523 | const gregion = gaccount.subgraph(stack.region, stack.region); 524 | const node = gregion.find(`${stack.account.id}:${stack.region}:${stack.name}`); 525 | stack.parentStacks.forEach(parentStack => { 526 | gregion.find(`${stack.account.id}:${stack.region}:${parentStack.stackName}`).connect(node); 527 | }); 528 | }); 529 | } catch (err) { 530 | error(`can not access account ${account.label} of type ${account.type}`, err); 531 | } 532 | } 533 | stdconsole.log(groot.toDOT()); 534 | } else if (input.update === true) { 535 | const relevantStacks = async () => { 536 | if (input['--stack-name'] !== null) { 537 | const accounts = await fetchAwsAccounts(stdconsole, stdin, input); 538 | const stacks = []; 539 | for (const account of accounts) { 540 | const allStacks = await fetchAllStacks(account, input); 541 | Array.prototype.push.apply(stacks, allStacks.filter(stack => stack.name === input['--stack-name'])); 542 | } 543 | if (stacks.length === 0) { 544 | throw new Error(`no stack found with name ${input['--stack-name']}`); 545 | } else if (stacks.length > 1) { 546 | throw new Error(`more then one stack found with name ${input['--stack-name']}. Set the --region parameter to restrict to a single region.`); 547 | } 548 | return stacks; 549 | } else { 550 | const accounts = await fetchAwsAccounts(stdconsole, stdin, input); 551 | const g = gcreate('root', `widdix-v${version}`); 552 | for (const account of accounts) { 553 | const stacksRandomOrder = await fetchAllStacks(account, input); 554 | stacksRandomOrder.forEach(stack => { 555 | const id = `${stack.account.id}:${stack.region}:${stack.name}`; 556 | g.create(id, id, stack); 557 | }); 558 | stacksRandomOrder.forEach(stack => { 559 | const id = `${stack.account.id}:${stack.region}:${stack.name}`; 560 | const node = g.find(id); 561 | stack.parentStacks.forEach(parentStack => { 562 | g.find(`${stack.account.id}:${stack.region}:${parentStack.stackName}`).connect(node); 563 | }); 564 | }); 565 | } 566 | return g.sort().map(node => node.data()).reverse(); // start with stacks that have no dependencies 567 | } 568 | }; 569 | const stacks = (await relevantStacks()); 570 | const updateableStacks = stacks.filter(stack => stack.templateUpdateAvailable === true); 571 | if (updateableStacks.length == 0) { 572 | throw new Error('no update available'); 573 | } 574 | const updateableStacksWithTemplateDrift = updateableStacks.filter(stack => stack.templateDrift === true); 575 | for (const stack of updateableStacksWithTemplateDrift) { 576 | await yes(stdconsole, stdin, `Stack ${stack.name} in ${stack.region} uses a modified template. An update will override any modificytions. Continue?`, input['--yes']); 577 | } 578 | const stacksAndChangeSets = []; 579 | for (const stack of updateableStacks) { // TODO optimization, run regions in parallel 580 | const changeSet = await createChangeSet(stack); 581 | stacksAndChangeSets.push({ 582 | stack, 583 | changeSet 584 | }); 585 | } 586 | const rows = []; 587 | stacksAndChangeSets.forEach(({stack, changeSet}) => { 588 | rows.push([displayAccount(stack.account), stack.region, stack.name, stack.templateId, `${stack.templateVersion} (updating to ${stack.templateLatestVersion})`, 'AWS::CloudFormation::Stack', stack.name, 'Update']); 589 | changeSet.changes.map((change) => { 590 | const row = [displayAccount(stack.account), stack.region, stack.name, stack.templateId, `${stack.templateVersion} (updating to ${stack.templateLatestVersion})`, change.resource.type, change.resource.id]; 591 | if (change.action === 'Modify') { 592 | if (change.actionModifyReplacement === 'True') { 593 | row.push('Replace'); 594 | } else if (change.actionModifyReplacement === 'False') { 595 | row.push('Modify'); 596 | } else if (change.actionModifyReplacement === 'Conditional') { 597 | row.push('Replace (Conditional)'); 598 | } else { 599 | throw new Error(`unexpected actionModifyReplacement ${change.actionModifyReplacement}`); 600 | } 601 | } else { 602 | row.push(change.action); 603 | } 604 | rows.push(row); 605 | }); 606 | }); 607 | tprint(stdconsole, stdout.columns, ['Stack Account', 'Stack Region', 'Stack Name', 'Template ID', 'Template Version', 'Resource Type', 'Resource Id', 'Resource Action'], rows); 608 | await yes(stdconsole, stdin, 'Apply changes?', input['--yes']); 609 | const eventTable = tcreate(['Time', 'Status', 'Type', 'Logical ID', 'Status Reason'], []); 610 | eventTable.printHeader(stdconsole, stdout.columns); 611 | for (const {stack, changeSet} of stacksAndChangeSets) { 612 | await executeChangeSet(stack, changeSet, (event) => { 613 | eventTable.printBodyRow(stdconsole, stdout.columns, [event.Timestamp, event.ResourceStatus, event.ResourceType, event.LogicalResourceId, event.ResourceStatusReason]); 614 | }); 615 | } 616 | eventTable.printFooter(stdconsole, stdout.columns); 617 | } 618 | } 619 | -------------------------------------------------------------------------------- /cli.txt: -------------------------------------------------------------------------------- 1 | widdix CLI 2 | 3 | Usage: 4 | widdix catalogue [--all-profiles] [--profile=<name>] [--env] [--debug] 5 | widdix list [--region=<region>] [--all-profiles] [--profile=<name>] [--env] [--latest-version=<version>] [--debug] 6 | widdix graph [--region=<region>] [--all-profiles] [--profile=<name>] [--env] [--latest-version=<version>] [--debug] 7 | widdix get --stack-name=<stackname> [--region=<region>] [--all-profiles] [--profile=<name>] [--env] [--latest-version=<version>] [--debug] 8 | widdix create [--template-id=<templateid>] [--stack-name=<stackname>] [--parameter=<key=value>...] [--all-profiles] [--profile=<name>] [--env] [--latest-version=<version>] [--debug] 9 | widdix update [--stack-name=<stackname>] [--region=<region>] [--yes] [--all-profiles] [--profile=<name>] [--env] [--latest-version=<version>] [--debug] 10 | widdix delete --stack-name=<stackname> [--all-profiles] [--profile=<name>] [--env] [--debug] 11 | widdix -h | --help 12 | widdix --version 13 | 14 | Options: 15 | -t <templateid>, --template-id=<templateid> ID of the template. 16 | -s <stackname>, --stack-name=<stackname> Name of the CloudFormation stack. 17 | -r <region>, --region=<region> Region, e.g. us-east-1 (all regions if not specified). 18 | -p <key=value>, --parameter=<key=value> Format ParameterKey=ParameterValue. 19 | -y, --yes Answer all questions with yes. 20 | -d, --debug Print debug information. 21 | --all-profiles All profiles from ~/.aws/credentials 22 | --profile=<name> One specific profile from ~/.aws/credentials 23 | --env Using environment variables AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN 24 | --latest-version=<version> Override latest version fetched from GitHub 25 | -h, --help Show help. 26 | -v, --version Show version. 27 | -------------------------------------------------------------------------------- /graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/widdix/aws-cf-templates-cli/98a3b7e7935fd178c248034ad83efcf7e3c793ba/graph.png -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | import { fatal } from './lib/log.js'; 4 | import { run } from './cli.js'; 5 | 6 | if (!('NODE_ENV' in process.env)) { 7 | process.env.NODE_ENV = 'production'; 8 | } 9 | 10 | run(process.argv.splice(2), process.stdout, process.stderr, process.stdin) 11 | .then(() => process.nextTick(() => process.exit(0))) 12 | .catch(err => { 13 | console.error(`unexpected error ${process.argv.join(' ')}`, err); 14 | fatal(`unexpected error ${process.argv.join(' ')}`, err); 15 | process.nextTick(() => process.exit(1)); 16 | }); 17 | -------------------------------------------------------------------------------- /lib/aws-credentials.js: -------------------------------------------------------------------------------- 1 | import os from 'os'; 2 | import fs from 'fs'; 3 | import util from 'util'; 4 | 5 | const CONFIG_FILE_PATH = `${os.homedir()}/.aws/config`; 6 | const CREDENTIALS_FILE_PATH = `${os.homedir()}/.aws/credentials`; 7 | 8 | async function fetchProfilesFromFile(file, profiles) { 9 | const readFile = util.promisify(fs.readFile); 10 | const body = await readFile(file, 'utf8'); 11 | const initial = {currentProfile: '', profiles}; 12 | const final = body.split('\n') 13 | .reduce((acc, line) => { 14 | const cleanLine = line.trim(); 15 | if (cleanLine.startsWith('#')) { 16 | return acc; 17 | } else if (cleanLine.startsWith('[') && cleanLine.endsWith(']')) { 18 | const key = cleanLine.substring(1, cleanLine.length - 1); 19 | if (key.startsWith('profile ')) { 20 | acc.currentProfile = key.substr(8); 21 | } else { 22 | acc.currentProfile = key; 23 | } 24 | } else if(cleanLine.includes('=')) { 25 | if (!(acc.currentProfile in acc.profiles)) { 26 | acc.profiles[acc.currentProfile] = {}; 27 | } 28 | const [key, value] = cleanLine.split('=', 2); 29 | const cleanKey = key.trim(); 30 | const cleanValue = value.trim(); 31 | acc.profiles[acc.currentProfile][cleanKey] = cleanValue; 32 | } 33 | return acc; 34 | }, initial); 35 | return final.profiles; 36 | } 37 | 38 | export async function fetchProfiles() { 39 | let profiles = {}; 40 | if (fs.existsSync(CONFIG_FILE_PATH)) { 41 | profiles = await fetchProfilesFromFile(CONFIG_FILE_PATH, profiles); 42 | } 43 | if (fs.existsSync(CREDENTIALS_FILE_PATH)) { 44 | profiles = await fetchProfilesFromFile(CREDENTIALS_FILE_PATH, profiles); 45 | } 46 | 47 | return profiles; 48 | } 49 | -------------------------------------------------------------------------------- /lib/graph.js: -------------------------------------------------------------------------------- 1 | export function create(gid, glabel) { 2 | const subgraphs = new Map(); 3 | const nodes = new Map(); 4 | const find = (id) => { 5 | const internalNode = nodes.get(id); 6 | if (internalNode === undefined) { 7 | return null; 8 | } 9 | return nodeWrapper(internalNode); 10 | }; 11 | const filter = (condition) => { 12 | const res = []; 13 | for (const internalNode of nodes.values()) { 14 | const node = nodeWrapper(internalNode); 15 | if (condition(node) === true) { 16 | res.push(node); 17 | } 18 | } 19 | return res; 20 | }; 21 | const nodeWrapper = (internalNode) => { 22 | const connect = (node) => { 23 | const internalNode2 = nodes.get(node.id()); 24 | if (internalNode2 === undefined) { 25 | throw new Error(`node ${node.id()} does not exist`); 26 | } 27 | internalNode.outgoing.add(internalNode2.id); 28 | internalNode2.incoming.add(internalNode.id); 29 | return nodeWrapper(internalNode); 30 | }; 31 | return { 32 | id: () => internalNode.id, 33 | label: () => internalNode.label, 34 | data: () => internalNode.data, 35 | findAndConnect: (id)=> { 36 | const node = find(id); 37 | if (node === null) { 38 | throw new Error(`node ${id} does not exist`); 39 | } else { 40 | return connect(node); 41 | } 42 | }, 43 | connect, 44 | outgoing: () => { 45 | const res = []; 46 | for (const id of internalNode.outgoing.values()) { 47 | res.push(find(id)); 48 | } 49 | return res; 50 | }, 51 | incoming: () => { 52 | const res = []; 53 | for (const id of internalNode.incoming.values()) { 54 | res.push(find(id)); 55 | } 56 | return res; 57 | } 58 | }; 59 | }; 60 | const _toDOT = (type) => { 61 | let dot = ''; 62 | if (type === 'subgraph') { 63 | dot += `${type} "cluster_${gid}" {\n`; 64 | } else { 65 | dot += `${type} "${gid}" {\n`; 66 | } 67 | dot += 'rankdir=LR;\n'; 68 | dot += `label="${glabel}";\n`; 69 | for (const internalNode of nodes.values()) { 70 | const node = nodeWrapper(internalNode); 71 | dot += `"${node.id()}"[label="${node.label()}"];\n`; 72 | } 73 | for (const internalNode of nodes.values()) { 74 | const node = nodeWrapper(internalNode); 75 | dot += node.outgoing().map(n => `"${node.id()}" -> "${n.id()}";\n`).join(''); 76 | } 77 | for (const g of subgraphs.values()) { 78 | dot += g._toDOT('subgraph'); 79 | } 80 | dot += '}\n'; 81 | return dot; 82 | }; 83 | return { 84 | id: () => { 85 | return gid; 86 | }, 87 | label: () => { 88 | return glabel; 89 | }, 90 | create: (id, label, data) => { 91 | const internalNode = {id, label, data, outgoing: new Set(), incoming: new Set()}; 92 | nodes.set(id, internalNode); 93 | return nodeWrapper(internalNode); 94 | }, 95 | find, 96 | filter, 97 | subgraph: (id, label) => { 98 | if (subgraphs.has(id)) { 99 | return subgraphs.get(id); 100 | } else { 101 | const g = create(id, label); 102 | subgraphs.set(id, g); 103 | return g; 104 | } 105 | }, 106 | sort: () => { // starts with nodes that have no outgoing connections 107 | if (nodes.size === 0) { 108 | return []; 109 | } 110 | const startNodes = filter(node => node.outgoing().length === 0); 111 | if (startNodes.length === 0) { 112 | throw new Error('no start nodes found'); 113 | } 114 | const visitedNodeIds = new Set(startNodes.map(node => node.id())); 115 | const remainingNodeIds = new Set(filter(node => node.outgoing().length !== 0).map(node => node.id())); 116 | const res = [...startNodes]; 117 | while (remainingNodeIds.size > 0) { 118 | let progress = false; 119 | remainingNodeIds.forEach((id) => { 120 | const node = find(id); 121 | if (node.outgoing().every(outgoing => visitedNodeIds.has(outgoing.id()))) { 122 | // all outgoing nodes are visited, so we can visit this node as well 123 | res.push(node); 124 | remainingNodeIds.delete(node.id()); 125 | visitedNodeIds.add(node.id()); 126 | progress = true; 127 | } 128 | }); 129 | if (progress === false) { 130 | throw new Error('cyclic connections found'); 131 | } 132 | } 133 | return res; 134 | }, 135 | _toDOT: _toDOT, // internal 136 | toDOT: () => { 137 | return _toDOT('digraph'); 138 | } 139 | }; 140 | } 141 | -------------------------------------------------------------------------------- /lib/log.js: -------------------------------------------------------------------------------- 1 | import SimpleLogger from 'simple-node-logger'; 2 | const log = SimpleLogger.createSimpleLogger('widdix.log'); // TODO replace with something that can be flushed finally 3 | import { serializeError } from 'serialize-error'; 4 | 5 | function wrapper(level) { 6 | return (message, data) => { 7 | if (data !== undefined) { 8 | if (data instanceof Error) { 9 | log[level](message, serializeError(data)); 10 | } else { 11 | log[level](message, JSON.stringify(data)); 12 | } 13 | } else { 14 | log[level](message); 15 | } 16 | }; 17 | } 18 | 19 | export function setLevel (level) { 20 | log.setLevel(level); 21 | } 22 | 23 | export const trace = wrapper('trace'); 24 | 25 | export const debug = wrapper('debug'); 26 | 27 | export const info = wrapper('info'); 28 | 29 | export const warning = wrapper('warn'); 30 | 31 | export const error = wrapper('error'); 32 | 33 | export const fatal = wrapper('fatal'); 34 | -------------------------------------------------------------------------------- /lib/table.js: -------------------------------------------------------------------------------- 1 | function stringCell(cell) { 2 | if (cell === undefined || cell === null) { 3 | return ''; 4 | } 5 | return cell.toString(); 6 | } 7 | 8 | function optimizeColSize(colLabel, cells) { 9 | const size = Math.max(5, colLabel.length); 10 | return cells.reduce((acc, cell) => { 11 | const str = stringCell(cell); 12 | return Math.max(str.length, acc); 13 | }, size); 14 | } 15 | 16 | function saveCell(cell, size) { 17 | const str = stringCell(cell); 18 | if (str.length > size) { 19 | return `${str.substr(0, size-3)}${'.'.repeat(3)}`; 20 | } 21 | return stringCell(cell).padEnd(size); 22 | } 23 | 24 | export function create(cols, rows) { 25 | const lineCharacter = '-'; 26 | const colCharacter = '|'; 27 | const internalCols = cols.map((colLabel, i) => { 28 | const optimizedSize = optimizeColSize(colLabel, rows.map(row => row[i])); 29 | return { 30 | label: colLabel, 31 | optimizedSize, 32 | size: (stdcolumns) => { 33 | const availableCols = stdcolumns - 2 - (cols.length-1)*3 - 2; 34 | if (usedCols > availableCols) { // scale down 35 | return Math.floor(optimizedSize * availableCols / usedCols); 36 | } else if (usedCols < (availableCols*0.8)) { // scale up 37 | return Math.floor(optimizedSize * (availableCols*0.8) / usedCols); 38 | } 39 | return optimizedSize; 40 | } 41 | }; 42 | }); 43 | const usedCols = internalCols.reduce((acc, internalCol) => acc + internalCol.optimizedSize, 0); 44 | const printLine = (stdconsole, stdcolumns) => { 45 | const colsSize = internalCols.reduce((acc, internalCol) => acc + internalCol.size(stdcolumns), 0); 46 | stdconsole.info(`${lineCharacter.repeat(2)}${lineCharacter.repeat(colsSize + (cols.length-1) * 3)}${lineCharacter.repeat(2)}`); 47 | }; 48 | const printData = (stdconsole, stdcolumns, data) => { 49 | stdconsole.info(`${colCharacter} ${data.map((cell, i) => saveCell(cell, internalCols[i].size(stdcolumns))).join(` ${colCharacter} `)} ${colCharacter}`); 50 | }; 51 | const printHeader = (stdconsole, stdcolumns) => { 52 | printLine(stdconsole, stdcolumns); 53 | printData(stdconsole, stdcolumns, internalCols.map(internalCol => internalCol.label)); 54 | printLine(stdconsole, stdcolumns); 55 | }; 56 | const printBodyRow = printData; 57 | const printBody = (stdconsole, stdcolumns) => { 58 | rows.forEach(row => printBodyRow(stdconsole, stdcolumns, row)); 59 | }; 60 | const printFooter = printLine; 61 | 62 | return { 63 | printHeader, 64 | printBodyRow, 65 | printBody, 66 | printFooter, 67 | print: (stdconsole = console, stdcolumns = process.stdout.columns) => { 68 | printHeader(stdconsole, stdcolumns); 69 | printBody(stdconsole, stdcolumns); 70 | printFooter(stdconsole, stdcolumns); 71 | } 72 | }; 73 | } 74 | 75 | export function print(stdconsole, stdcolumns, cols, rows) { 76 | const table = create(cols, rows); 77 | table.print(stdconsole, stdcolumns); 78 | } 79 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "widdix", 3 | "version": "0.4.1", 4 | "description": "A CLI tool to manage Free Templates for AWS CloudFormation", 5 | "author": "Michael Wittig <michael@widdix.de>", 6 | "license": "Apache-2.0", 7 | "dependencies": { 8 | "@aws-sdk/client-cloudformation": "3.507.0", 9 | "@aws-sdk/client-ec2": "3.507.0", 10 | "@aws-sdk/client-iam": "3.507.0", 11 | "@aws-sdk/client-sts": "3.507.0", 12 | "@aws-sdk/credential-providers": "3.507.0", 13 | "@smithy/node-http-handler": "2.3.1", 14 | "docopt": "0.6.2", 15 | "md5": "2.3.0", 16 | "p-limit": "5.0.0", 17 | "hpagent": "1.2.0", 18 | "request": "2.88.2", 19 | "requestretry": "7.1.0", 20 | "semver": "7.6.0", 21 | "serialize-error": "11.0.3", 22 | "simple-node-logger": "21.8.12", 23 | "truncate-middle": "1.0.6" 24 | }, 25 | "devDependencies": { 26 | "eslint": "8.56.0", 27 | "mocha": "10.2.0", 28 | "nock": "13.5.1", 29 | "stdio-mock": "1.2.0" 30 | }, 31 | "scripts": { 32 | "test": "eslint . && NODE_ENV=development AWS_ACCESS_KEY_ID=AKID AWS_SECRET_ACCESS_KEY=SECRET mocha -t 10000 test/*.js" 33 | }, 34 | "bin": "index.js", 35 | "type": "module" 36 | } 37 | -------------------------------------------------------------------------------- /test/.eslintrc.yml: -------------------------------------------------------------------------------- 1 | env: 2 | mocha: true 3 | extends: '../.eslintrc.yml' 4 | -------------------------------------------------------------------------------- /test/cli.js: -------------------------------------------------------------------------------- 1 | import { strict as assert } from 'assert'; 2 | import nock from 'nock'; 3 | import stdiomock from 'stdio-mock'; 4 | 5 | import { clearCache, run } from '../cli.js'; 6 | 7 | function generateEc2DescribeRegionsResponse(regions) { 8 | let xml = '<DescribeRegionsResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/">'; 9 | xml += '<requestId>b9b4b068-3a41-11e5-94eb-example</requestId>'; 10 | xml += '<regionInfo>'; 11 | regions.forEach(region => { 12 | xml += '<item>'; 13 | xml += `<regionName>${region}</regionName>`; 14 | xml += `<regionEndpoint>ec2.${region}.amazonaws.com</regionEndpoint>`; 15 | xml += '</item>'; 16 | }); 17 | xml += '</regionInfo>'; 18 | xml += '</DescribeRegionsResponse>'; 19 | return xml; 20 | } 21 | 22 | function generateGitHubResponse(version) { 23 | return `<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xml:lang="en-US"><entry><title>v${version}`; 24 | } 25 | 26 | function generateCloudFormationDescribeStacksResponse(stacks) { 27 | let xml = ''; 28 | xml += ''; 29 | xml += ''; 30 | stacks.forEach(stack => { 31 | xml += ''; 32 | xml += `${stack.name}`; 33 | xml += `arn:aws:cloudformation:us-east-1:123456789:stack/${stack.name}/aaf549a0-a413-11df-adb3-5081b3858e83`; 34 | xml += `${stack.description}`; 35 | xml += `${stack.status}`; 36 | xml += ''; 37 | xml += ''; 38 | xml += ''; 39 | Object.keys(stack.outputs).forEach(key => { 40 | xml += ''; 41 | xml += `${key}`; 42 | xml += `${stack.outputs[key]}`; 43 | xml += ''; 44 | }); 45 | xml += ''; 46 | xml += ''; 47 | }); 48 | xml += ''; 49 | xml += ''; 50 | xml += 'b9b4b068-3a41-11e5-94eb-example'; 51 | xml += ''; 52 | return xml; 53 | } 54 | 55 | function generateCloudFormationGetTemplateSummaryResponse(template) { 56 | let xml = ''; 57 | xml += ''; 58 | xml += 'A sample template description.'; 59 | xml += ''; 60 | Object.keys(template.parameters).forEach(key => { 61 | const parameter = template.parameters[key]; 62 | xml += ''; 63 | xml += `${key}`; 64 | xml += `${parameter.type}`; 65 | xml += 'false'; 66 | if ('description' in parameter) { 67 | xml += `${parameter.description}`; 68 | } 69 | if ('default' in parameter) { 70 | xml += `${parameter.default}`; 71 | } 72 | xml += ''; 73 | }); 74 | xml += ''; 75 | xml += '2010-09-09'; 76 | xml += ''; 77 | xml += 'b9b4b068-3a41-11e5-94eb-example'; 78 | xml += ''; 79 | return xml; 80 | } 81 | 82 | function generateCloudFormationDescribeChangeSetResponse(changeSet) { 83 | let xml = ''; 84 | xml += ''; 85 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:stack/SampleStack/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 86 | xml += `${changeSet.status}`; 87 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:changeSet/SampleChangeSet/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 88 | xml += 'SampleStack'; 89 | xml += 'SampleChangeSet-direct'; 90 | xml += ''; 91 | xml += '2016-03-17T23:35:25.813Z'; 92 | xml += ''; 93 | /* 94 | 95 | testing 96 | Purpose 97 | 98 | 99 | MyKeyName 100 | KeyPairName 101 | 102 | 103 | t2.micro 104 | InstanceType 105 | 106 | */ 107 | xml += ''; 108 | /* 109 | 110 | False 111 | 112 | Tags 113 | 114 |
115 | 116 | DirectModification 117 | 118 | Never 119 | Tags 120 | 121 | Static 122 | 123 |
124 | MyEC2Instance 125 | Modify 126 | i-1abc23d4 127 | AWS::EC2::Instance 128 |
129 | Resource 130 |
*/ 131 | xml += '
'; 132 | xml += '
'; 133 | xml += 'b9b4b068-3a41-11e5-94eb-example'; 134 | xml += '
'; 135 | return xml; 136 | } 137 | 138 | function generateCloudFormationCreateChangeSetResponse() { 139 | let xml = ''; 140 | xml += ''; 141 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:changeSet/SampleChangeSet/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 142 | xml += ''; 143 | xml += 'b9b4b068-3a41-11e5-94eb-example'; 144 | xml += ''; 145 | return xml; 146 | } 147 | 148 | function generateCloudFormationExecuteChangeSetResponse() { 149 | let xml = ''; 150 | xml += ''; 151 | xml += 'b9b4b068-3a41-11e5-94eb-example'; 152 | xml += ''; 153 | return xml; 154 | } 155 | 156 | function generateCloudFormationDescribeStackEventsResponse() { 157 | let xml = ''; 158 | xml += ''; 159 | xml += ''; 160 | xml += ''; 161 | xml += '2016-03-15T20:54:31.809Z'; 162 | xml += 'UPDATE_COMPLETE'; 163 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 164 | xml += '1dedea10-eaf0-11e5-8451-500c5242948e'; 165 | xml += 'MyStack'; 166 | xml += 'MyStack'; 167 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 168 | xml += 'AWS::CloudFormation::Stack'; 169 | xml += ''; 170 | xml += ''; 171 | xml += '2016-03-15T20:54:30.174Z'; 172 | xml += 'CREATE_COMPLETE'; 173 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 174 | xml += 'MyEC2Instance-CREATE_COMPLETE-2016-03-15T20:54:30.174Z'; 175 | xml += 'MyEC2Instance'; 176 | xml += 'MyStack'; 177 | xml += 'i-1abc23d4'; 178 | xml += '{"ImageId":ami-8fcee4e5",...}'; 179 | xml += 'AWS::EC2::Instance'; 180 | xml += ''; 181 | xml += ''; 182 | xml += '2016-03-15T20:53:17.660Z'; 183 | xml += 'CREATE_IN_PROGRESS'; 184 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 185 | xml += 'MyEC2Instance-CREATE_IN_PROGRESS-2016-03-15T20:53:17.660Z'; 186 | xml += 'MyEC2Instance'; 187 | xml += 'Resource creation Initiated'; 188 | xml += 'MyStack'; 189 | xml += 'i-1abc23d4'; 190 | xml += '{"ImageId":ami-8fcee4e5",...}'; 191 | xml += 'AWS::EC2::Instance'; 192 | xml += ''; 193 | xml += ''; 194 | xml += '2016-03-15T20:53:16.516Z'; 195 | xml += 'CREATE_IN_PROGRESS'; 196 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 197 | xml += 'MyEC2Instance-CREATE_IN_PROGRESS-2016-03-15T20:53:16.516Z'; 198 | xml += 'MyEC2Instance'; 199 | xml += 'MyStack'; 200 | xml += ''; 201 | xml += '{"ImageId":ami-8fcee4e5",...}'; 202 | xml += 'AWS::EC2::Instance'; 203 | xml += ''; 204 | xml += ''; 205 | xml += '2016-03-15T20:53:11.231Z'; 206 | xml += 'UPDATE_IN_PROGRESS'; 207 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 208 | xml += 'edbf2ac0-eaef-11e5-adeb-500c28903236'; 209 | xml += 'MyStack'; 210 | xml += 'User Initiated'; 211 | xml += 'MyStack'; 212 | xml += 'arn:aws:cloudformation:us-east-1:123456789012:stack/MyStack/12a3b456-0e10-4ce0-9052-5d484a8c4e5b'; 213 | xml += 'AWS::CloudFormation::Stack'; 214 | xml += ''; 215 | xml += ''; 216 | xml += ''; 217 | xml += 'b9b4b068-3a41-11e5-94eb-example'; 218 | xml += ''; 219 | return xml; 220 | } 221 | 222 | function generateCloudFormationGetTemplateResponse() { 223 | let xml = ''; 224 | xml += ''; 225 | xml += ''; 226 | xml += 'test'; 227 | xml += ''; 228 | xml += ''; 229 | xml += 'b9b4b068-3a41-11e5-94eb-example'; 230 | xml += ''; 231 | return xml; 232 | } 233 | 234 | function generateS3Reponse() { 235 | return 'test'; 236 | } 237 | 238 | describe('cli', () => { 239 | afterEach(() => { 240 | nock.cleanAll(); 241 | clearCache(); 242 | }); 243 | describe('list', () => { 244 | it('happy', (done) => { 245 | const github = nock('https://github.com') 246 | .get('/widdix/aws-cf-templates/releases.atom') 247 | .reply(200, generateGitHubResponse('6.13.0'), {'Content-Type': 'application/xml'}); 248 | const ec2 = nock('https://ec2.us-east-1.amazonaws.com') 249 | .post('/') 250 | .reply(200, generateEc2DescribeRegionsResponse(['us-east-1']), {'Content-Type': 'application/xml'}); 251 | const cloudformation = nock('https://cloudformation.us-east-1.amazonaws.com') 252 | .post('/', { 253 | Action: 'DescribeStacks', 254 | Version: '2010-05-15' 255 | }) 256 | .reply(200, generateCloudFormationDescribeStacksResponse([{ 257 | name: 'MyStack', 258 | description: 'test, a cloudonaut.io template', 259 | status: 'CREATE_COMPLETE', 260 | outputs: { 261 | TemplateID: 'test/test', 262 | TemplateVersion: '6.13.0' 263 | } 264 | }]), {'Content-Type': 'application/xml'}) 265 | .post('/', { 266 | Action: 'GetTemplate', 267 | Version: '2010-05-15', 268 | StackName: 'MyStack' 269 | }) 270 | .reply(200, generateCloudFormationGetTemplateResponse(), {'Content-Type': 'application/xml'}); 271 | const s3 = nock('https://widdix-aws-cf-templates-releases-eu-west-1.s3.eu-west-1.amazonaws.com') 272 | .get('/v6.13.0/test/test.yaml') 273 | .reply(200, generateS3Reponse()); 274 | 275 | const {stdout, stdin, stderr} = stdiomock.stdio(); 276 | stdout.columns = 300; 277 | run(['list'], stdout, stderr, stdin) 278 | .then(() => { 279 | assert.equal(ec2.isDone(), true); 280 | assert.equal(github.isDone(), true); 281 | assert.equal(cloudformation.isDone(), true); 282 | assert.equal(s3.isDone(), true); 283 | assert.equal(stderr.data().length, 0); 284 | const lines = stdout.data().join('').split('\n'); 285 | assert.equal(lines.length, 6); 286 | assert.equal(lines[3].includes('us-east-1'), true); 287 | assert.equal(lines[3].includes('MyStack'), true); 288 | assert.equal(lines[3].includes('test'), true); 289 | assert.equal(lines[3].includes('6.13.0'), true); 290 | done(); 291 | }); 292 | }); 293 | }); 294 | describe('update', () => { 295 | describe('stack', () => { 296 | it('happy', (done) => { 297 | const github = nock('https://github.com') 298 | .get('/widdix/aws-cf-templates/releases.atom') 299 | .reply(200, generateGitHubResponse('6.13.0'), {'Content-Type': 'application/xml'}); 300 | const ec2 = nock('https://ec2.us-east-1.amazonaws.com') 301 | .post('/') 302 | .reply(200, generateEc2DescribeRegionsResponse(['us-east-1']), {'Content-Type': 'application/xml'}); 303 | const cloudformation = nock('https://cloudformation.us-east-1.amazonaws.com') 304 | .post('/', { 305 | Action: 'DescribeStacks', 306 | Version: '2010-05-15' 307 | }) 308 | .reply(200, generateCloudFormationDescribeStacksResponse([{ 309 | name: 'MyStack', 310 | description: 'test, a cloudonaut.io template', 311 | status: 'CREATE_COMPLETE', 312 | outputs: { 313 | TemplateID: 'test/test', 314 | TemplateVersion: '6.12.0' 315 | } 316 | }]), {'Content-Type': 'application/xml'}) 317 | .post('/', { 318 | Action: 'GetTemplate', 319 | Version: '2010-05-15', 320 | StackName: 'MyStack' 321 | }) 322 | .reply(200, generateCloudFormationGetTemplateResponse(), {'Content-Type': 'application/xml'}) 323 | .post('/', { 324 | Action: 'GetTemplateSummary', 325 | Version: '2010-05-15', 326 | TemplateURL: /.*/ 327 | }) 328 | .reply(200, generateCloudFormationGetTemplateSummaryResponse({ 329 | parameters: { 330 | NameA: { 331 | type: 'String', 332 | default: 'x' 333 | } 334 | } 335 | }), {'Content-Type': 'application/xml'}) 336 | .post('/', { 337 | Action: 'CreateChangeSet', 338 | Version: '2010-05-15', 339 | Capabilities: { 340 | // eslint-disable-next-line no-sparse-arrays 341 | member: [, 'CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM'] 342 | }, 343 | ChangeSetName: /.*/, 344 | ChangeSetType: 'UPDATE', 345 | Description: /.*/, 346 | Parameters: { 347 | // eslint-disable-next-line no-sparse-arrays 348 | member: [, { 349 | ParameterKey: 'NameA', 350 | ParameterValue: 'x' 351 | }] 352 | }, 353 | StackName: 'MyStack', 354 | TemplateURL: 'https://s3-eu-west-1.amazonaws.com/widdix-aws-cf-templates-releases-eu-west-1/v6.13.0/test/test.yaml' 355 | }) 356 | .reply(200, generateCloudFormationCreateChangeSetResponse(), {'Content-Type': 'application/xml'}) 357 | .post('/', { 358 | Action: 'DescribeChangeSet', 359 | Version: '2010-05-15', 360 | ChangeSetName: /.*/, 361 | StackName: 'MyStack' 362 | }) 363 | .times(2) 364 | .reply(200, generateCloudFormationDescribeChangeSetResponse({status: 'CREATE_COMPLETE'}), {'Content-Type': 'application/xml'}) 365 | .post('/', { 366 | Action: 'ExecuteChangeSet', 367 | ChangeSetName: /.*/, 368 | StackName: 'MyStack', 369 | Version: '2010-05-15' 370 | }) 371 | .reply(200, generateCloudFormationExecuteChangeSetResponse(), {'Content-Type': 'application/xml'}) 372 | .post('/', { 373 | Action: 'DescribeStackEvents', 374 | Version: '2010-05-15', 375 | StackName: 'MyStack' 376 | }) 377 | .reply(200, generateCloudFormationDescribeStackEventsResponse(), {'Content-Type': 'application/xml'}); 378 | const s3 = nock('https://widdix-aws-cf-templates-releases-eu-west-1.s3.eu-west-1.amazonaws.com') 379 | .get('/v6.12.0/test/test.yaml') 380 | .reply(200, generateS3Reponse()); 381 | 382 | const {stdout, stdin, stderr} = stdiomock.stdio(); 383 | stdout.columns = 300; 384 | stdout.on('data', (d) => { 385 | if (d.includes('Apply changes?')) { 386 | stdin.write('y'); 387 | } 388 | }); 389 | run(['update', '--stack-name', 'MyStack'], stdout, stderr, stdin) 390 | .then(() => { 391 | assert.equal(ec2.isDone(), true); 392 | assert.equal(github.isDone(), true); 393 | assert.equal(cloudformation.isDone(), true); 394 | assert.equal(s3.isDone(), true); 395 | assert.equal(stderr.data().length, 0); 396 | const lines = stdout.data().join('').split('\n'); 397 | assert.equal(lines.length, 16); 398 | assert.equal(lines[3].includes('us-east-1'), true); 399 | assert.equal(lines[3].includes('MyStack'), true); 400 | assert.equal(lines[3].includes('test'), true); 401 | assert.equal(lines[3].includes('Update'), true); 402 | assert.equal(lines[5].includes('Apply changes?'), true); 403 | assert.equal(lines[9].includes('MyStack'), true); 404 | assert.equal(lines[9].includes('AWS::CloudFormation::Stack'), true); 405 | assert.equal(lines[9].includes('UPDATE_IN_PROGRESS'), true); 406 | assert.equal(lines[13].includes('MyStack'), true); 407 | assert.equal(lines[13].includes('AWS::CloudFormation::Stack'), true); 408 | assert.equal(lines[13].includes('UPDATE_COMPLETE'), true); 409 | done(); 410 | }); 411 | }); 412 | }); 413 | }); 414 | }); 415 | -------------------------------------------------------------------------------- /test/graph.js: -------------------------------------------------------------------------------- 1 | import { strict as assert } from 'assert'; 2 | import { create } from '../lib/graph.js'; 3 | 4 | describe('graph', () => { 5 | describe('sort', () => { 6 | it('empty graph', () => { 7 | const g = create('id', 'test'); 8 | assert.deepEqual(g.sort(), []); 9 | }); 10 | it('one node, no connections', () => { 11 | const g = create('id', 'test'); 12 | g.create('n1', 'test1', 1); 13 | assert.deepEqual(g.sort().map(n => n.id()), ['n1']); 14 | }); 15 | it('two nodes, no connections', () => { 16 | const g = create('id', 'test'); 17 | g.create('n1', 'test1', 1); 18 | g.create('n2', 'test2', 2); 19 | assert.deepEqual(g.sort().map(n => n.id()), ['n1', 'n2']); 20 | }); 21 | it('two nodes, single connection', () => { 22 | const g = create('id', 'test'); 23 | const n1 = g.create('n1', 'test1', 1); 24 | const n2 = g.create('n2', 'test2', 2); 25 | n1.connect(n2); 26 | assert.deepEqual(g.sort().map(n => n.id()), ['n2', 'n1']); 27 | }); 28 | it('two nodes, cyclic connection, no start nodes', () => { 29 | const g = create('id', 'test'); 30 | const n1 = g.create('n1', 'test1', 1); 31 | const n2 = g.create('n2', 'test2', 2); 32 | n1.connect(n2); 33 | n2.connect(n1); 34 | assert.throws(() => g.sort().map(n => n.id()), /^Error: no start nodes found$/); 35 | }); 36 | it('three nodes, cyclic connection', () => { 37 | const g = create('id', 'test'); 38 | const n1 = g.create('n1', 'test1', 1); 39 | const n2 = g.create('n2', 'test2', 2); 40 | g.create('n3', 'test3', 3); 41 | n1.connect(n2); 42 | n2.connect(n1); 43 | assert.throws(() => g.sort().map(n => n.id()), /^Error: cyclic connections found$/); 44 | }); 45 | it('three nodes, single connection', () => { 46 | const g = create('id', 'test'); 47 | const n1 = g.create('n1', 'test1', 1); 48 | const n2 = g.create('n2', 'test2', 2); 49 | const n3 = g.create('n3', 'test2', 3); 50 | n1.connect(n2); 51 | n2.connect(n3); 52 | assert.deepEqual(g.sort().map(n => n.id()), ['n3', 'n2', 'n1']); 53 | }); 54 | it('three nodes, multiple connections', () => { 55 | const g = create('id', 'test'); 56 | const n1 = g.create('n1', 'test1', 1); 57 | const n2 = g.create('n2', 'test2', 2); 58 | const n3 = g.create('n3', 'test2', 3); 59 | n1.connect(n2); 60 | n1.connect(n3); 61 | n2.connect(n3); 62 | assert.deepEqual(g.sort().map(n => n.id()), ['n3', 'n2', 'n1']); 63 | }); 64 | }); 65 | describe('find', () => { 66 | it('empty graph', () => { 67 | const g = create('id', 'test'); 68 | assert.equal(g.find('n1'), null); 69 | }); 70 | it('missing', () => { 71 | const g = create('id', 'test'); 72 | g.create('n1', 'test1', 1); 73 | assert.equal(g.find('n2'), null); 74 | }); 75 | it('existing', () => { 76 | const g = create('id', 'test'); 77 | g.create('n1', 'test1', 1); 78 | assert.equal(g.find('n1').id(), 'n1'); 79 | assert.equal(g.find('n1').data(), 1); 80 | assert.deepEqual(g.find('n1').outgoing(), []); 81 | assert.deepEqual(g.find('n1').incoming(), []); 82 | }); 83 | it('multiple existing', () => { 84 | const g = create('id', 'test'); 85 | g.create('n1', 'test1', 1); 86 | g.create('n2', 'test2', 2); 87 | g.create('n3', 'test3', 3); 88 | assert.equal(g.find('n1').data(), 1); 89 | assert.equal(g.find('n2').data(), 2); 90 | assert.equal(g.find('n3').data(), 3); 91 | }); 92 | }); 93 | describe('connect', () => { 94 | it('happy', () => { 95 | const g = create('id', 'test'); 96 | const n1 = g.create('n1', 'test1', 1); 97 | const n2 = g.create('n2', 'test2', 2).connect(n1); 98 | assert.equal(n1.outgoing().length, 0); 99 | assert.equal(n1.incoming().length, 1); 100 | assert.equal(n1.incoming()[0].id(), 'n2'); 101 | assert.equal(n2.outgoing().length, 1); 102 | assert.equal(n2.outgoing()[0].id(), 'n1'); 103 | assert.equal(n2.incoming().length, 0); 104 | }); 105 | }); 106 | describe('findAndConnect', () => { 107 | it('happy', () => { 108 | const g = create('id', 'test'); 109 | const n1 = g.create('n1', 'test1', 1); 110 | const n2 = g.create('n2', 'test2', 2).findAndConnect('n1'); 111 | assert.equal(n1.outgoing().length, 0); 112 | assert.equal(n1.incoming().length, 1); 113 | assert.equal(n1.incoming()[0].id(), 'n2'); 114 | assert.equal(n2.outgoing().length, 1); 115 | assert.equal(n2.outgoing()[0].id(), 'n1'); 116 | assert.equal(n2.incoming().length, 0); 117 | }); 118 | }); 119 | describe('filter', () => { 120 | it('empty graph', () => { 121 | const g = create('id', 'test'); 122 | const nodes = g.filter(() => true); 123 | assert.equal(nodes.length, 0); 124 | }); 125 | it('all true', () => { 126 | const g = create('id', 'test'); 127 | g.create('n1', 'test1', 1); 128 | g.create('n2', 'test2', 2); 129 | g.create('n3', 'test3', 3); 130 | const nodes = g.filter(() => true); 131 | assert.equal(nodes.length, 3); 132 | }); 133 | it('all false', () => { 134 | const g = create('id', 'test'); 135 | g.create('n1', 'test1', 1); 136 | g.create('n2', 'test2', 2); 137 | g.create('n3', 'test3', 3); 138 | const nodes = g.filter(() => false); 139 | assert.equal(nodes.length, 0); 140 | }); 141 | it('condition on data', () => { 142 | const g = create('id', 'test'); 143 | g.create('n1', 'test1', 1); 144 | g.create('n2', 'test2', 2); 145 | g.create('n3', 'test3', 3); 146 | const nodes = g.filter((node) => (node.data() % 2) === 0); 147 | assert.equal(nodes.length, 1); 148 | assert.equal(nodes[0].id(), 'n2'); 149 | }); 150 | it('condition on id', () => { 151 | const g = create('id', 'test'); 152 | g.create('n1', 'test1', 1); 153 | g.create('n2', 'test2', 2); 154 | g.create('n3', 'test3', 3); 155 | const nodes = g.filter((node) => node.id() === 'n3'); 156 | assert.equal(nodes.length, 1); 157 | assert.equal(nodes[0].id(), 'n3'); 158 | }); 159 | it('condition on outgoing', () => { 160 | const g = create('id', 'test'); 161 | const n1 = g.create('n1', 'test1', 1); 162 | g.create('n2', 'test2', 2).connect(n1); 163 | g.create('n3', 'test3', 3); 164 | const nodes = g.filter((node) => node.outgoing().length > 0); 165 | assert.equal(nodes.length, 1); 166 | assert.equal(nodes[0].id(), 'n2'); 167 | }); 168 | }); 169 | describe('toDOT', () => { 170 | it('empty', () => { 171 | const g = create('id', 'test'); 172 | const lines = ['digraph "id" {', 'rankdir=LR;', 'label="test";', '}', '']; 173 | assert.equal(g.toDOT(), lines.join('\n')); 174 | }); 175 | it('single node', () => { 176 | const g = create('id', 'test'); 177 | g.create('n1', 'test1', 1); 178 | const lines = ['digraph "id" {', 'rankdir=LR;', 'label="test";', '"n1"[label="test1"];', '}', '']; 179 | assert.equal(g.toDOT(), lines.join('\n')); 180 | }); 181 | it('two nodes', () => { 182 | const g = create('id', 'test'); 183 | g.create('n1', 'test1', 1); 184 | g.create('n2', 'test2', 2); 185 | const lines = ['digraph "id" {', 'rankdir=LR;', 'label="test";', '"n1"[label="test1"];', '"n2"[label="test2"];', '}', '']; 186 | assert.equal(g.toDOT(), lines.join('\n')); 187 | }); 188 | it('two nodes connected', () => { 189 | const g = create('id', 'test'); 190 | const n1 = g.create('n1', 'test1', 1); 191 | g.create('n2', 'test2', 2).connect(n1); 192 | const lines = ['digraph "id" {', 'rankdir=LR;', 'label="test";', '"n1"[label="test1"];', '"n2"[label="test2"];', '"n2" -> "n1";', '}', '']; 193 | assert.equal(g.toDOT(), lines.join('\n')); 194 | }); 195 | it('two nodes all connected', () => { 196 | const g = create('id', 'test'); 197 | const n1 = g.create('n1', 'test1', 1); 198 | const n2 = g.create('n2', 'test2', 2).connect(n1); 199 | n1.connect(n2); 200 | const lines = ['digraph "id" {', 'rankdir=LR;', 'label="test";', '"n1"[label="test1"];', '"n2"[label="test2"];', '"n1" -> "n2";', '"n2" -> "n1";', '}', '']; 201 | assert.equal(g.toDOT(), lines.join('\n')); 202 | }); 203 | describe('subgraphs', () => { 204 | it('mixed subgraph and root', () => { 205 | const g = create('id', 'test'); 206 | g.create('n1', 'test1', 1); 207 | g.subgraph('sub1', 'test1'); 208 | const lines = ['digraph "id" {', 'rankdir=LR;', 'label="test";', '"n1"[label="test1"];', 'subgraph "cluster_sub1" {', 'rankdir=LR;', 'label="test1";', '}', '}', '']; 209 | assert.equal(g.toDOT(), lines.join('\n')); 210 | }); 211 | it('single subgraph', () => { 212 | const g = create('id', 'test'); 213 | const sub1 = g.subgraph('sub1', 'test1'); 214 | sub1.create('n1', 'test1', 1); 215 | const lines = ['digraph "id" {', 'rankdir=LR;', 'label="test";', 'subgraph "cluster_sub1" {', 'rankdir=LR;', 'label="test1";', '"n1"[label="test1"];', '}', '}', '']; 216 | assert.equal(g.toDOT(), lines.join('\n')); 217 | }); 218 | it('two subgraphs', () => { 219 | const g = create('id', 'test'); 220 | g.subgraph('sub1', 'test1'); 221 | g.subgraph('sub2', 'test2'); 222 | const lines = ['digraph "id" {', 'rankdir=LR;', 'label="test";', 'subgraph "cluster_sub1" {', 'rankdir=LR;', 'label="test1";', '}', 'subgraph "cluster_sub2" {', 'rankdir=LR;', 'label="test2";', '}', '}', '']; 223 | assert.equal(g.toDOT(), lines.join('\n')); 224 | }); 225 | }); 226 | }); 227 | }); 228 | --------------------------------------------------------------------------------