├── .github └── PULL_REQUEST_TEMPLATE.md ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── client ├── demo │ └── index.html ├── package.json ├── src │ ├── main.js │ └── views │ │ ├── widget.html │ │ └── widget.js └── webpack.config.js └── server ├── apigateway-lambda.json ├── package.json └── server.js /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | *Issue #, if available:* 2 | 3 | *Description of changes:* 4 | 5 | 6 | By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license. 7 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 4 | opensource-codeofconduct@amazon.com with any additional questions or comments. 5 | -------------------------------------------------------------------------------- /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 | 10 | ## Reporting Bugs/Feature Requests 11 | 12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features. 13 | 14 | When filing an issue, please check [existing open](https://github.com/aws-samples/aws-cloudwatch-building-dashboard-outside-aws-console/issues), or [recently closed](https://github.com/aws-samples/aws-cloudwatch-building-dashboard-outside-aws-console/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already 15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: 16 | 17 | * A reproducible test case or series of steps 18 | * The version of our code being used 19 | * Any modifications you've made relevant to the bug 20 | * Anything unusual about your environment or deployment 21 | 22 | 23 | ## Contributing via Pull Requests 24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: 25 | 26 | 1. You are working against the latest source on the *master* branch. 27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. 29 | 30 | To send us a pull request, please: 31 | 32 | 1. Fork the repository. 33 | 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. 34 | 3. Ensure local tests pass. 35 | 4. Commit to your fork using clear commit messages. 36 | 5. Send us a pull request, answering any default questions in the pull request interface. 37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. 38 | 39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and 40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). 41 | 42 | 43 | ## Finding contributions to work on 44 | 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'](https://github.com/aws-samples/aws-cloudwatch-building-dashboard-outside-aws-console/labels/help%20wanted) issues is a great place to start. 45 | 46 | 47 | ## Code of Conduct 48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). 49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact 50 | opensource-codeofconduct@amazon.com with any additional questions or comments. 51 | 52 | 53 | ## Security issue notifications 54 | 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. 55 | 56 | 57 | ## Licensing 58 | 59 | See the [LICENSE](https://github.com/aws-samples/aws-cloudwatch-building-dashboard-outside-aws-console/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. 60 | 61 | We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. 62 | -------------------------------------------------------------------------------- /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 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Amazon CloudWatch Building Dashboards Outside the AWS Console 2 | Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Amazon CloudWatch Building Dashboards Outside the AWS Console 2 | 3 | Code samples related to "Building a CloudWatch Dashboard Outside of the AWS Console" blog post published on the [AWS DevOps blog](https://aws.amazon.com/blogs/devops/building-an-amazon-cloudwatch-dashboard-outside-of-the-aws-management-console/). This post demonstrates how to build a custom monitoring dashboard outside of the AWS Console by leveraging snapshot graphs. 4 | 5 | ## License 6 | 7 | This library is licensed under the Apache 2.0 License. 8 | 9 | ## Setup Instructions 10 | 11 | This project includes client code which is packaged using WebPack into a Javascript embeddable widget. There is a sample HTML page index.html that has the resulting widget embedded. 12 | 13 | The server code is intended to run as an AWS Lambda function behind an API GateWay. The Lambda function retrieves the requested CloudWatch widget by calling the CloudWatch [GetMetricWidgetImage](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricWidgetImage.html) API. 14 | 15 | ### Server Setup: 16 | 17 | 1. Download the repository. 18 | 2. Navigate to **./server** and run `npm install`. 19 | 3. From the server folder, run `zip -r snapshotwidgetdemo.zip ./*` 20 | 4. Upload **snapshotwidgetdemo.zip** to any S3 bucket. 21 | 5. Upload **./server/apigateway-lambda.json** to any S3 bucket. 22 | 6. Navigate to the Cloud Formation console and Create Stack. 23 | a) Point the new stack to the S3 location from step 5. 24 | b) During setup, you will be asked for the Lambda S3 bucket name from step 4. 25 | 26 | The Cloud Formation script should create the following: 27 | 1. EC2 instance to monitor. Instance is in a VPC. 28 | 2. API GateWay endpoint for the client side widget to communicate with. 29 | 3. Lambda function that sits behind the API GateWay and retreives the snapshot graph from the CloudWatch API. 30 | 31 | ### Client Setup: 32 | 33 | 1. Navigate to **./client** and run `npm install`. 34 | 2. Edit **./demo/index.html** to add the API Gateway endpoint and API key that are output by the Cloud Formation script (step 6 above). 35 | 3. Build the component using WebPack 36 | 37 | ./node_modules/.bin/webpack --config webpack.config.js 38 | or 39 | 40 | npm build 41 | 4. Serve the demo webpage on localhost 42 | 43 | ./node_modules/.bin/webpack-dev-server --open 44 | 45 | 46 | or 47 | 48 | npm start 49 | 50 | The browser should open automatically at index.html. The page contains 2 embedded snapshot graphs displaying the CPUUtilization and CPUCreditUsage metrics your EC2. 51 | 52 | ### Troubleshooting: 53 | 54 | 1. View the API GateWay log file in CloudWatch. 55 | 2. View the Lambda log file in CloudWatch. 56 | 57 | See the CloudWatch API documentation for [GetMetricWidgetImage](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricWidgetImage.html) for more information. 58 | 59 | 60 | ## Cross-account Dashboards 61 | 62 | The widget definition JSON supports an optional parameter called accountId. This defaults to the account the Lambda is running in. You can use the accountId parameter to specify the account where the metric(s) live. Enabling you to build cross-account dashboards. 63 | 64 | `"accountId": 1234567` 65 | 66 | ### Cross-account Permissions 67 | 68 | The Lambda attempts to assume a role called CloudWatchSnapshotGraphs in the accounts you define in the widget. To build a cross-account dashboard you first need to establish a trust relationship between the accounts running the Lambda and the account ids specified in the widget definition(s). 69 | 70 | 1. Ensure that the role running the Lambda has permissions to assume the role in any account. 71 | ```json 72 | { 73 | "Version": "2012-10-17", 74 | "Statement": [ 75 | { 76 | "Effect": "Allow", 77 | "Action": [ 78 | "sts:AssumeRole", 79 | "sts:GetFederationToken" 80 | ], 81 | "Resource": "arn:aws:iam::*:role/CloudWatchSnapshotGraphs" 82 | } 83 | ] 84 | } 85 | ``` 86 | 2. Create a role called CloudWatchSnapshotGraphs in each account you want to retrieve charts from. Ensure that the role has read-only permissions to CloudWatch and has a trust relationship with the account that executes the Lambda. 87 | ```json 88 | { 89 | "Version": "2012-10-17", 90 | "Statement": [ 91 | { 92 | "Effect": "Allow", 93 | "Principal": { 94 | "AWS": "arn:aws:iam:::root" 95 | }, 96 | "Action": "sts:AssumeRole" 97 | } 98 | ] 99 | } 100 | ``` 101 | 102 | 103 | -------------------------------------------------------------------------------- /client/demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | Demo page of the widget 4 | 5 | 6 | 7 | 36 | 37 | 67 | 68 | 98 | 99 | 116 | 117 | 118 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "js-widget", 3 | "scripts": { 4 | "build": "./node_modules/.bin/webpack --config webpack.config.js", 5 | "start": "./node_modules/.bin/webpack-dev-server --open" 6 | }, 7 | "dependencies": { 8 | "@babel/core": "^7.0.0-beta.32", 9 | "@babel/preset-env": "^7.0.0-beta.32", 10 | "babel-loader": "^8.0.0-beta.0", 11 | "copy-webpack-plugin": "^4.5.2", 12 | "html-loader": "^0.5.1", 13 | "json-loader": "^0.5.7", 14 | "webpack": "^3.12.0", 15 | "webpack-dev-server": ">=3.1.11", 16 | "request": "^2.88.0" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /client/src/main.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import { render } from './views/widget' 5 | const request = require('request') 6 | 7 | 8 | function app(window) { 9 | console.log('CW-Widget'); 10 | 11 | let configurations = {}; 12 | 13 | let queue = window[window['CW-Widget']].q; 14 | if (queue) { 15 | for (var i = 0; i < queue.length; i++) { 16 | 17 | configurations = addParams(configurations, queue[i][1]); 18 | apiHandler(queue[i][0], configurations); 19 | } 20 | } 21 | } 22 | 23 | function apiHandler(api, params) { 24 | 25 | console.log(`API Handler ${api}`, params); 26 | 27 | params.widget.forEach((val) => { 28 | 29 | let accountId = val.accountId?val.accountId:"" ; 30 | 31 | var options = { 32 | url: params.url+'?role=CloudWatchSnapshotGraphs&accountId='+accountId+ '&widgetDefinition='+encodeURIComponent(JSON.stringify(val.widgetDefinition)), 33 | headers: { 34 | 'x-api-key' : params.api_key, 35 | 'Content-Type': 'application/x-www-form-urlencoded', 36 | 'Accept' : 'image/png' 37 | } 38 | }; 39 | 40 | request(options, function (error, response, body) { 41 | console.log('error:', error); 42 | console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 43 | console.log('body:', body) 44 | 45 | var img = new Buffer(body, 'base64'); 46 | render(img); 47 | 48 | }); 49 | }); 50 | 51 | } 52 | 53 | function addParams(a, b) { 54 | for (var key in b) 55 | if (b.hasOwnProperty(key)) 56 | a[key] = b[key]; 57 | return a; 58 | } 59 | 60 | app(window); -------------------------------------------------------------------------------- /client/src/views/widget.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /client/src/views/widget.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | import html from './widget.html'; 5 | 6 | let elements = []; 7 | let body; 8 | 9 | function arrayBufferToBase64( buffer ) { 10 | var binary = ''; 11 | var bytes = new Uint8Array( buffer ); 12 | var len = bytes.byteLength; 13 | for (var i = 0; i < len; i++) { 14 | binary += String.fromCharCode( bytes[ i ] ); 15 | } 16 | return window.btoa( binary ); 17 | } 18 | 19 | export function render(body) { 20 | 21 | var buffer = body; 22 | 23 | var imageStr = arrayBufferToBase64(buffer); 24 | 25 | let temporary = document.createElement('div'); 26 | temporary.innerHTML = html; 27 | 28 | body = document.getElementsByTagName('body')[0]; 29 | while (temporary.children.length > 0) { 30 | elements.push(temporary.children[0]); 31 | temporary.children[0].setAttribute('src', 'data:image/png;base64,' + imageStr); 32 | body.appendChild(temporary.children[0]); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /client/webpack.config.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | const path = require('path'); 5 | const webpack = require('webpack'); 6 | var copyWebpackPlugin = require('copy-webpack-plugin'); 7 | const bundleOutputDir = './dist'; 8 | 9 | module.exports = (env) => { 10 | const isDevBuild = !(env && env.prod); 11 | 12 | return [{ 13 | entry: './src/main.js', 14 | output: { 15 | filename: 'widget.js', 16 | path: path.resolve(bundleOutputDir), 17 | }, 18 | devServer: { 19 | contentBase: bundleOutputDir 20 | }, 21 | plugins: isDevBuild 22 | ? [new webpack.SourceMapDevToolPlugin(), new copyWebpackPlugin([{ from: 'demo/' }])] 23 | : [new webpack.optimize.UglifyJsPlugin()], 24 | module: { 25 | rules: [ 26 | { test: /\.html$/i, use: 'html-loader' }, 27 | { 28 | test: /\.js$/i, exclude: /node_modules/, use: { 29 | loader: 'babel-loader', 30 | options: { 31 | presets: [['@babel/env', { 32 | 'targets': { 33 | 'browsers': ['ie 6', 'safari 7'] 34 | } 35 | }]] 36 | } 37 | } 38 | } 39 | ] 40 | }, 41 | node: { 42 | console: true, 43 | fs: 'empty', 44 | net: 'empty', 45 | tls: 'empty' 46 | } 47 | }]; 48 | }; -------------------------------------------------------------------------------- /server/apigateway-lambda.json: -------------------------------------------------------------------------------- 1 | { 2 | "AWSTemplateFormatVersion": "2010-09-09", 3 | "Description": "AWS CloudFormation sample template that contains a single Lambda function behind an API Gateway", 4 | 5 | "Parameters" : { 6 | "InstanceType" : { 7 | "Description" : "WebServer EC2 instance type", 8 | "Type" : "String", 9 | "Default" : "t2.small", 10 | "AllowedValues" : [ "t1.micro", "t2.micro", "t2.small", "t2.medium", "m1.small", "m1.medium", "m1.large", "m1.xlarge", "m2.xlarge", "m2.2xlarge", "m2.4xlarge", "m3.medium", "m3.large", "m3.xlarge", "m3.2xlarge", "c1.medium", "c1.xlarge", "c3.large", "c3.xlarge", "c3.2xlarge", "c3.4xlarge", "c3.8xlarge", "g2.2xlarge", "r3.large", "r3.xlarge", "r3.2xlarge", "r3.4xlarge", "r3.8xlarge", "i2.xlarge", "i2.2xlarge", "i2.4xlarge", "i2.8xlarge", "hi1.4xlarge", "hs1.8xlarge", "cr1.8xlarge", "cc2.8xlarge", "cg1.4xlarge"], 11 | "ConstraintDescription" : "Must be a valid EC2 instance type" 12 | }, 13 | "LambdaS3Bucket": { 14 | "Description" : "Name of an S3 bucket containing snapshotwidgetdemo.zip", 15 | "Type" : "String", 16 | "ConstraintDescription" : "Must be a valid S3 bucket" 17 | }, 18 | }, 19 | 20 | "Mappings" : { 21 | "AWSInstanceType2Arch" : { 22 | "t1.micro" : { "Arch" : "PV64" }, 23 | "t2.micro" : { "Arch" : "HVM64" }, 24 | "t2.small" : { "Arch" : "HVM64" }, 25 | "t2.medium" : { "Arch" : "HVM64" }, 26 | "m1.small" : { "Arch" : "PV64" }, 27 | "m1.medium" : { "Arch" : "PV64" }, 28 | "m1.large" : { "Arch" : "PV64" }, 29 | "m1.xlarge" : { "Arch" : "PV64" }, 30 | "m2.xlarge" : { "Arch" : "PV64" }, 31 | "m2.2xlarge" : { "Arch" : "PV64" }, 32 | "m2.4xlarge" : { "Arch" : "PV64" }, 33 | "m3.medium" : { "Arch" : "HVM64" }, 34 | "m3.large" : { "Arch" : "HVM64" }, 35 | "m3.xlarge" : { "Arch" : "HVM64" }, 36 | "m3.2xlarge" : { "Arch" : "HVM64" }, 37 | "c1.medium" : { "Arch" : "PV64" }, 38 | "c1.xlarge" : { "Arch" : "PV64" }, 39 | "c3.large" : { "Arch" : "HVM64" }, 40 | "c3.xlarge" : { "Arch" : "HVM64" }, 41 | "c3.2xlarge" : { "Arch" : "HVM64" }, 42 | "c3.4xlarge" : { "Arch" : "HVM64" }, 43 | "c3.8xlarge" : { "Arch" : "HVM64" }, 44 | "g2.2xlarge" : { "Arch" : "HVMG2" }, 45 | "r3.large" : { "Arch" : "HVM64" }, 46 | "r3.xlarge" : { "Arch" : "HVM64" }, 47 | "r3.2xlarge" : { "Arch" : "HVM64" }, 48 | "r3.4xlarge" : { "Arch" : "HVM64" }, 49 | "r3.8xlarge" : { "Arch" : "HVM64" }, 50 | "i2.xlarge" : { "Arch" : "HVM64" }, 51 | "i2.2xlarge" : { "Arch" : "HVM64" }, 52 | "i2.4xlarge" : { "Arch" : "HVM64" }, 53 | "i2.8xlarge" : { "Arch" : "HVM64" }, 54 | "hi1.4xlarge" : { "Arch" : "HVM64" }, 55 | "hs1.8xlarge" : { "Arch" : "HVM64" }, 56 | "cr1.8xlarge" : { "Arch" : "HVM64" }, 57 | "cc2.8xlarge" : { "Arch" : "HVM64" } 58 | }, 59 | 60 | "AWSRegionArch2AMI" : { 61 | "us-east-1" : { "PV64" : "ami-50842d38", "HVM64" : "ami-08842d60", "HVMG2" : "ami-3a329952" }, 62 | "us-west-2" : { "PV64" : "ami-af86c69f", "HVM64" : "ami-8786c6b7", "HVMG2" : "ami-47296a77" }, 63 | "us-west-1" : { "PV64" : "ami-c7a8a182", "HVM64" : "ami-cfa8a18a", "HVMG2" : "ami-331b1376" }, 64 | "eu-west-1" : { "PV64" : "ami-aa8f28dd", "HVM64" : "ami-748e2903", "HVMG2" : "ami-00913777" }, 65 | "ap-southeast-1" : { "PV64" : "ami-20e1c572", "HVM64" : "ami-d6e1c584", "HVMG2" : "ami-fabe9aa8" }, 66 | "ap-northeast-1" : { "PV64" : "ami-21072820", "HVM64" : "ami-35072834", "HVMG2" : "ami-5dd1ff5c" }, 67 | "ap-southeast-2" : { "PV64" : "ami-8b4724b1", "HVM64" : "ami-fd4724c7", "HVMG2" : "ami-e98ae9d3" }, 68 | "sa-east-1" : { "PV64" : "ami-9d6cc680", "HVM64" : "ami-956cc688", "HVMG2" : "NOT_SUPPORTED" }, 69 | "cn-north-1" : { "PV64" : "ami-a857c591", "HVM64" : "ami-ac57c595", "HVMG2" : "NOT_SUPPORTED" }, 70 | "eu-central-1" : { "PV64" : "ami-a03503bd", "HVM64" : "ami-b43503a9", "HVMG2" : "ami-b03503ad" } 71 | } 72 | }, 73 | 74 | "Resources": { 75 | 76 | "VPC" : { 77 | "Type" : "AWS::EC2::VPC", 78 | "Properties" : { 79 | "CidrBlock" : "10.0.0.0/16", 80 | "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ] 81 | } 82 | }, 83 | 84 | "SubnetA" : { 85 | "Type" : "AWS::EC2::Subnet", 86 | "Properties" : { 87 | "VpcId" : { "Ref" : "VPC" }, 88 | "AvailabilityZone" : { 89 | "Fn::Select" : [ "0", { "Fn::GetAZs" : "" } ] 90 | }, 91 | "CidrBlock" : "10.0.0.0/17", 92 | "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ] 93 | } 94 | }, 95 | 96 | "SubnetB" : { 97 | "Type" : "AWS::EC2::Subnet", 98 | "Properties" : { 99 | "VpcId" : { "Ref" : "VPC" }, 100 | "AvailabilityZone" : { 101 | "Fn::Select" : [ "1", { "Fn::GetAZs" : "" } ] 102 | }, 103 | "CidrBlock" : "10.0.128.0/17", 104 | "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ] 105 | } 106 | }, 107 | 108 | "InternetGateway" : { 109 | "Type" : "AWS::EC2::InternetGateway", 110 | "Properties" : { 111 | "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ] 112 | } 113 | }, 114 | 115 | "AttachGateway" : { 116 | "Type" : "AWS::EC2::VPCGatewayAttachment", 117 | "Properties" : { 118 | "VpcId" : { "Ref" : "VPC" }, 119 | "InternetGatewayId" : { "Ref" : "InternetGateway" } 120 | } 121 | }, 122 | 123 | "RouteTable" : { 124 | "Type" : "AWS::EC2::RouteTable", 125 | "Properties" : { 126 | "VpcId" : {"Ref" : "VPC"}, 127 | "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ] 128 | } 129 | }, 130 | 131 | "Route" : { 132 | "Type" : "AWS::EC2::Route", 133 | "DependsOn" : "AttachGateway", 134 | "Properties" : { 135 | "RouteTableId" : { "Ref" : "RouteTable" }, 136 | "DestinationCidrBlock" : "0.0.0.0/0", 137 | "GatewayId" : { "Ref" : "InternetGateway" } 138 | } 139 | }, 140 | 141 | "SubnetRouteTableAssociation" : { 142 | "Type" : "AWS::EC2::SubnetRouteTableAssociation", 143 | "Properties" : { 144 | "SubnetId" : { "Ref" : "SubnetA" }, 145 | "RouteTableId" : { "Ref" : "RouteTable" } 146 | } 147 | }, 148 | 149 | "NetworkAcl" : { 150 | "Type" : "AWS::EC2::NetworkAcl", 151 | "Properties" : { 152 | "VpcId" : {"Ref" : "VPC"}, 153 | "Tags" : [ {"Key" : "Application", "Value" : { "Ref" : "AWS::StackId"} } ] 154 | } 155 | }, 156 | 157 | "InboundHTTPNetworkAclEntry" : { 158 | "Type" : "AWS::EC2::NetworkAclEntry", 159 | "Properties" : { 160 | "NetworkAclId" : {"Ref" : "NetworkAcl"}, 161 | "RuleNumber" : "100", 162 | "Protocol" : "6", 163 | "RuleAction" : "allow", 164 | "Egress" : "false", 165 | "CidrBlock" : "0.0.0.0/0", 166 | "PortRange" : {"From" : "80", "To" : "80"} 167 | } 168 | }, 169 | 170 | "InboundSSHNetworkAclEntry" : { 171 | "Type" : "AWS::EC2::NetworkAclEntry", 172 | "Properties" : { 173 | "NetworkAclId" : {"Ref" : "NetworkAcl"}, 174 | "RuleNumber" : "101", 175 | "Protocol" : "6", 176 | "RuleAction" : "allow", 177 | "Egress" : "false", 178 | "CidrBlock" : "0.0.0.0/0", 179 | "PortRange" : {"From" : "22", "To" : "22"} 180 | } 181 | }, 182 | 183 | "InboundResponsePortsNetworkAclEntry" : { 184 | "Type" : "AWS::EC2::NetworkAclEntry", 185 | "Properties" : { 186 | "NetworkAclId" : {"Ref" : "NetworkAcl"}, 187 | "RuleNumber" : "102", 188 | "Protocol" : "6", 189 | "RuleAction" : "allow", 190 | "Egress" : "false", 191 | "CidrBlock" : "0.0.0.0/0", 192 | "PortRange" : {"From" : "1024", "To" : "65535"} 193 | } 194 | }, 195 | 196 | "OutBoundHTTPNetworkAclEntry" : { 197 | "Type" : "AWS::EC2::NetworkAclEntry", 198 | "Properties" : { 199 | "NetworkAclId" : {"Ref" : "NetworkAcl"}, 200 | "RuleNumber" : "100", 201 | "Protocol" : "6", 202 | "RuleAction" : "allow", 203 | "Egress" : "true", 204 | "CidrBlock" : "0.0.0.0/0", 205 | "PortRange" : {"From" : "80", "To" : "80"} 206 | } 207 | }, 208 | 209 | "OutBoundHTTPSNetworkAclEntry" : { 210 | "Type" : "AWS::EC2::NetworkAclEntry", 211 | "Properties" : { 212 | "NetworkAclId" : {"Ref" : "NetworkAcl"}, 213 | "RuleNumber" : "101", 214 | "Protocol" : "6", 215 | "RuleAction" : "allow", 216 | "Egress" : "true", 217 | "CidrBlock" : "0.0.0.0/0", 218 | "PortRange" : {"From" : "443", "To" : "443"} 219 | } 220 | }, 221 | 222 | "OutBoundResponsePortsNetworkAclEntry" : { 223 | "Type" : "AWS::EC2::NetworkAclEntry", 224 | "Properties" : { 225 | "NetworkAclId" : {"Ref" : "NetworkAcl"}, 226 | "RuleNumber" : "102", 227 | "Protocol" : "6", 228 | "RuleAction" : "allow", 229 | "Egress" : "true", 230 | "CidrBlock" : "0.0.0.0/0", 231 | "PortRange" : {"From" : "1024", "To" : "65535"} 232 | } 233 | }, 234 | 235 | "SubnetNetworkAclAssociation" : { 236 | "Type" : "AWS::EC2::SubnetNetworkAclAssociation", 237 | "Properties" : { 238 | "SubnetId" : { "Ref" : "SubnetA" }, 239 | "NetworkAclId" : { "Ref" : "NetworkAcl" } 240 | } 241 | }, 242 | 243 | "InstanceSecurityGroup" : { 244 | "Type" : "AWS::EC2::SecurityGroup", 245 | "Properties" : { 246 | "VpcId" : { "Ref" : "VPC" }, 247 | "GroupDescription" : "Enable SSH access via port 22", 248 | "SecurityGroupIngress" : [ 249 | ] 250 | } 251 | }, 252 | 253 | "EC2Instance": { 254 | "Type": "AWS::EC2::Instance", 255 | "Properties": { 256 | "ImageId" : { "Fn::FindInMap" : [ "AWSRegionArch2AMI", { "Ref" : "AWS::Region" }, 257 | { "Fn::FindInMap" : [ "AWSInstanceType2Arch", { "Ref" : "InstanceType" }, "Arch" ] } ] }, 258 | "InstanceType" : { "Ref" : "InstanceType" }, 259 | "Monitoring" : "true", 260 | "NetworkInterfaces" : [{ 261 | "GroupSet" : [{ "Ref" : "InstanceSecurityGroup" }], 262 | "AssociatePublicIpAddress" : "true", 263 | "DeviceIndex" : "0", 264 | "DeleteOnTermination" : "true", 265 | "SubnetId" : { "Ref" : "SubnetA" } 266 | }] 267 | } 268 | }, 269 | 270 | "SnapshotGraphsLambda": { 271 | "Type": "AWS::Lambda::Function", 272 | "Properties": { 273 | "Code": { 274 | "S3Bucket": { "Ref" : "LambdaS3Bucket" }, 275 | "S3Key": "snapshotwidgetdemo.zip" 276 | }, 277 | "Timeout" : "30", 278 | "Description": "A function to retrieve a CloudWatch snapshot graph", 279 | "FunctionName": "SnapshotGraphsLambda", 280 | "Handler": "server.myHandler", 281 | "Role": { "Fn::GetAtt": ["LambdaExecutionRole", "Arn"]}, 282 | "Runtime": "nodejs10.x" 283 | } 284 | }, 285 | 286 | "LambdaExecutionRole": { 287 | "Type": "AWS::IAM::Role", 288 | "Properties": { 289 | "AssumeRolePolicyDocument": { 290 | "Version": "2012-10-17", 291 | "Statement": [{ 292 | "Effect": "Allow", 293 | "Principal": { "Service": ["lambda.amazonaws.com"] }, 294 | "Action": ["sts:AssumeRole"] 295 | }] 296 | }, 297 | "ManagedPolicyArns": ["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole", 298 | "arn:aws:iam::aws:policy/CloudWatchReadOnlyAccess"] 299 | } 300 | }, 301 | 302 | "SnapshotGraphsApi": { 303 | "Type": "AWS::ApiGateway::RestApi", 304 | "Properties": { 305 | "Name": "CloudWatch Snapshot Graphs API", 306 | "Description": "API used to retrieve CloudWatch snapshot graphs", 307 | "FailOnWarnings": true 308 | } 309 | }, 310 | 311 | "LambdaPermission": { 312 | "Type": "AWS::Lambda::Permission", 313 | "Properties": { 314 | "Action": "lambda:invokeFunction", 315 | "FunctionName": {"Fn::GetAtt": ["SnapshotGraphsLambda", "Arn"]}, 316 | "Principal": "apigateway.amazonaws.com", 317 | "SourceArn": {"Fn::Join": ["", ["arn:aws:execute-api:", {"Ref": "AWS::Region"}, ":", {"Ref": "AWS::AccountId"}, ":", {"Ref": "SnapshotGraphsApi"}, "/*"]]} 318 | } 319 | }, 320 | 321 | "ApiGatewayCloudWatchLogsRole": { 322 | "Type": "AWS::IAM::Role", 323 | "Properties": { 324 | "AssumeRolePolicyDocument": { 325 | "Version": "2012-10-17", 326 | "Statement": [{ 327 | "Effect": "Allow", 328 | "Principal": { "Service": ["apigateway.amazonaws.com"] }, 329 | "Action": ["sts:AssumeRole"] 330 | }] 331 | }, 332 | "Policies": [{ 333 | "PolicyName": "ApiGatewayLogsPolicy", 334 | "PolicyDocument": { 335 | "Version": "2012-10-17", 336 | "Statement": [{ 337 | "Effect": "Allow", 338 | "Action": [ 339 | "logs:CreateLogGroup", 340 | "logs:CreateLogStream", 341 | "logs:DescribeLogGroups", 342 | "logs:DescribeLogStreams", 343 | "logs:PutLogEvents", 344 | "logs:GetLogEvents", 345 | "logs:FilterLogEvents" 346 | ], 347 | "Resource": "*" 348 | }] 349 | } 350 | }] 351 | } 352 | }, 353 | 354 | "ApiGatewayAccount": { 355 | "Type": "AWS::ApiGateway::Account", 356 | "Properties": { 357 | "CloudWatchRoleArn": {"Fn::GetAtt": ["ApiGatewayCloudWatchLogsRole", "Arn"] } 358 | } 359 | }, 360 | 361 | "SnapshotGraphsApiStage": { 362 | "DependsOn": ["ApiGatewayAccount"], 363 | "Type": "AWS::ApiGateway::Stage", 364 | "Properties": { 365 | "DeploymentId": {"Ref": "ApiDeployment"}, 366 | "MethodSettings": [{ 367 | "DataTraceEnabled": true, 368 | "HttpMethod": "*", 369 | "LoggingLevel": "INFO", 370 | "ResourcePath": "/*" 371 | }], 372 | "RestApiId": {"Ref": "SnapshotGraphsApi"}, 373 | "StageName": "LATEST" 374 | } 375 | }, 376 | 377 | "ApiDeployment": { 378 | "Type": "AWS::ApiGateway::Deployment", 379 | "DependsOn": ["SnapshotGraphsRequest"], 380 | "Properties": { 381 | "RestApiId": {"Ref": "SnapshotGraphsApi"}, 382 | "StageName": "DummyStage" 383 | } 384 | }, 385 | 386 | "SnapshotGraphsResource": { 387 | "Type": "AWS::ApiGateway::Resource", 388 | "Properties": { 389 | "RestApiId": {"Ref": "SnapshotGraphsApi"}, 390 | "ParentId": {"Fn::GetAtt": ["SnapshotGraphsApi", "RootResourceId"]}, 391 | "PathPart": "graph" 392 | } 393 | }, 394 | 395 | "SnapshotGraphsRequest": { 396 | "DependsOn": "LambdaPermission", 397 | "Type": "AWS::ApiGateway::Method", 398 | "Properties": { 399 | "ApiKeyRequired": "true", 400 | "AuthorizationType": "NONE", 401 | "HttpMethod": "GET", 402 | "Integration": { 403 | "Type": "AWS_PROXY", 404 | "IntegrationHttpMethod": "POST", 405 | "Uri": {"Fn::Join": ["", 406 | ["arn:aws:apigateway:", {"Ref": "AWS::Region"}, ":lambda:path/2015-03-31/functions/", {"Fn::GetAtt": ["SnapshotGraphsLambda", "Arn"]}, "/invocations"] 407 | ]}, 408 | "IntegrationResponses": [{ 409 | "StatusCode": "200" 410 | }] 411 | }, 412 | "RequestParameters": { 413 | "method.request.querystring.widgetDefinition": "true", 414 | "method.request.querystring.accountId": "false" 415 | }, 416 | "ResourceId": {"Ref": "SnapshotGraphsResource"}, 417 | "RestApiId": {"Ref": "SnapshotGraphsApi"}, 418 | "MethodResponses": [{ 419 | "StatusCode": "200" 420 | }] 421 | } 422 | }, 423 | 424 | "SnapshotGraphsCORSRequest": { 425 | "Type": "AWS::ApiGateway::Method", 426 | "Properties": { 427 | "AuthorizationType": "NONE", 428 | "HttpMethod": "OPTIONS", 429 | "Integration": { 430 | "Type":"MOCK", 431 | "PassthroughBehavior": "NEVER", 432 | "RequestTemplates": { 433 | "application/json": "{ statusCode: 200 }" 434 | }, 435 | "IntegrationResponses": [{ 436 | "ResponseParameters": { 437 | "method.response.header.Access-Control-Allow-Headers": "'x-api-key'", 438 | "method.response.header.Access-Control-Allow-Methods": "'GET,POST,OPTIONS'", 439 | "method.response.header.Access-Control-Allow-Origin": "'*'" 440 | }, 441 | "ResponseTemplates": { 442 | "application/json": "Empty" 443 | }, 444 | "StatusCode": "200" 445 | }] 446 | }, 447 | "MethodResponses" : [ { 448 | "ResponseParameters": { 449 | "method.response.header.Access-Control-Allow-Headers": "'*'", 450 | "method.response.header.Access-Control-Allow-Methods": "'GET,POST,OPTIONS'", 451 | "method.response.header.Access-Control-Allow-Origin": "'*'" 452 | }, 453 | "ResponseModels": { 454 | "application/json": "Empty" 455 | }, 456 | "StatusCode": "200" 457 | }], 458 | "ResourceId": {"Ref": "SnapshotGraphsResource"}, 459 | "RestApiId": {"Ref": "SnapshotGraphsApi"} 460 | } 461 | }, 462 | 463 | "APIUsagePlan" : { 464 | "Type" : "AWS::ApiGateway::UsagePlan", 465 | "Properties" : { 466 | "ApiStages" : [ {"ApiId" : { "Ref" : "SnapshotGraphsApi" }, 467 | "Stage" : { "Ref" : "SnapshotGraphsApiStage" }} ], 468 | "Description" : "Demo usage plan", 469 | "Quota" : { 470 | "Limit" : 5000, 471 | "Period" : "MONTH" 472 | }, 473 | "Throttle" : { 474 | "BurstLimit" : 200, 475 | "RateLimit" : 100 476 | }, 477 | "UsagePlanName" : "Plan_ABC" 478 | } 479 | }, 480 | 481 | "ApiKey": { 482 | "Type": "AWS::ApiGateway::ApiKey", 483 | "DependsOn": ["SnapshotGraphsApi","SnapshotGraphsApiStage"], 484 | "Properties": { 485 | "Name": "TestApiKey", 486 | "Description": "API Key V1", 487 | "Enabled": "true", 488 | "StageKeys": [{ 489 | "RestApiId": { "Ref": "SnapshotGraphsApi" }, 490 | "StageName": { "Ref":"SnapshotGraphsApiStage" } 491 | }] 492 | } 493 | }, 494 | 495 | "UsagePlanKey" : { 496 | "Type": "AWS::ApiGateway::UsagePlanKey", 497 | "Properties": { 498 | "KeyId" : {"Ref" : "ApiKey"}, 499 | "KeyType" : "API_KEY", 500 | "UsagePlanId" : {"Ref" : "APIUsagePlan"} 501 | } 502 | } 503 | 504 | }, 505 | 506 | "Outputs": { 507 | "Url": { 508 | "Description": "URL of the API gateway", 509 | "Value": {"Fn::Join": ["", ["https://", {"Ref": "SnapshotGraphsApi"}, ".execute-api.", {"Ref": "AWS::Region"}, ".amazonaws.com/LATEST/graph"]]} 510 | }, 511 | 512 | "InstanceID" : { 513 | "Description": "The Instance ID", 514 | "Value" : { "Ref" : "EC2Instance" } 515 | }, 516 | 517 | "APIKeyRef" : { 518 | "Description": "The API Key Reference - not the key itself", 519 | "Value" : { "Ref" : "ApiKey" } 520 | } 521 | } 522 | } 523 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "server", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "server.js", 6 | "author": "", 7 | "dependencies": { 8 | "aws-sdk": "^2.315.0" 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /server/server.js: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | // SPDX-License-Identifier: Apache-2.0 3 | 4 | const AWS = require('aws-sdk'); 5 | 6 | exports.myHandler = function(event, context, callback) { 7 | 8 | var widgetDefinition = { MetricWidget: {} } ; 9 | 10 | widgetDefinition.MetricWidget = event.queryStringParameters.widgetDefinition ; 11 | 12 | let accountId = event.queryStringParameters.accountId ; 13 | 14 | console.log('accountId: ' + accountId); 15 | console.log('widgetDefinition: ' + JSON.stringify(widgetDefinition)); 16 | 17 | let role = event.queryStringParameters.role ; 18 | let thisAcctId = context.invokedFunctionArn.split(":")[4] ; 19 | 20 | if (accountId !== null && accountId !== '' && accountId != thisAcctId) { 21 | 22 | let roleArn = `arn:aws:iam::${accountId}:role/${role}`; 23 | console.log("Assuming role: "+roleArn); 24 | 25 | let sts = new AWS.STS() ; 26 | sts.assumeRole({RoleArn: roleArn, RoleSessionName: 'SnapshotGraphs'}, function(err, data) { 27 | if (err) console.log(err, err.stack); // an error occurred 28 | else { // successful response 29 | console.log(JSON.stringify(data)) 30 | let tempCredentials = new AWS.Credentials(data.Credentials.AccessKeyId, 31 | data.Credentials.SecretAccessKey, 32 | data.Credentials.SessionToken) 33 | getWidget(widgetDefinition, callback, tempCredentials); 34 | } 35 | }); 36 | } else 37 | getWidget(widgetDefinition, callback); 38 | 39 | } 40 | 41 | getWidget = function(widgetDefinition, callback, tempCredentials) { 42 | 43 | let cloudWatch = tempCredentials ? new AWS.CloudWatch({credentials:tempCredentials}) : new AWS.CloudWatch(); 44 | 45 | cloudWatch.getMetricWidgetImage(widgetDefinition, function (err, data) { 46 | if (err) console.log(err, err.stack); // an error occurred 47 | else { 48 | console.log(data.MetricWidgetImage); // successful response 49 | var response = { 50 | statusCode: 200, 51 | headers: { 52 | 'Content-Type' : 'image/png', 53 | 'Access-Control-Allow-Origin' : '*', 54 | 'Access-Control-Allow-Methods' : 'POST, GET, PUT, OPTIONS', 55 | 'Access-Control-Allow-Headers' : 'x-api-key' 56 | }, 57 | body: new Buffer(data.MetricWidgetImage).toString('base64') 58 | }; 59 | callback(err, response); 60 | } 61 | }); 62 | 63 | } 64 | 65 | 66 | --------------------------------------------------------------------------------