├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── pyproject.toml ├── requirements.txt ├── rightsizer.py ├── src └── rightsizer │ ├── AwsRightSizer.py │ ├── __init__.py │ └── main.py └── tests └── __init__.py /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | 5 | --- 6 | 7 | **Describe the bug** 8 | A clear and concise description of what the bug is. 9 | 10 | **To Reproduce** 11 | Steps to reproduce the behavior: 12 | 1. Go to '...' 13 | 2. Click on '....' 14 | 3. Scroll down to '....' 15 | 4. See error 16 | 17 | **Expected behavior** 18 | A clear and concise description of what you expected to happen. 19 | 20 | **Screenshots** 21 | If applicable, add screenshots to help explain your problem. 22 | 23 | **Desktop/Server (please complete the following information):** 24 | - OS: [e.g. Ubuntu 16.04] 25 | - Python Version [e.g. 3.6.5 - run python --version to get this information] 26 | 27 | **Additional context** 28 | Add any other context about the problem here. 29 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | 5 | --- 6 | 7 | **Is your feature request related to a problem? Please describe.** 8 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 9 | 10 | **Describe the solution you'd like** 11 | A clear and concise description of what you want to happen. 12 | 13 | **Describe alternatives you've considered** 14 | A clear and concise description of any alternative solutions or features you've considered. 15 | 16 | **Additional context** 17 | Add any other context or screenshots about the feature request here. 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | *.pyc 3 | .idea/ 4 | *.csv 5 | dist/ 6 | build/ 7 | *.egg-info/ 8 | *.lock 9 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at gregory.jordan.m@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface, this includes new environment 13 | variables, exposed ports, useful file locations and container parameters. 14 | 3. Increase the version numbers in any examples files and the README.md to the new version that this 15 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 16 | 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you 17 | do not have permission to do that, you may request the second reviewer to merge it for you. 18 | 19 | ## Code of Conduct 20 | 21 | ### Our Pledge 22 | 23 | In the interest of fostering an open and welcoming environment, we as 24 | contributors and maintainers pledge to making participation in our project and 25 | our community a harassment-free experience for everyone, regardless of age, body 26 | size, disability, ethnicity, gender identity and expression, level of experience, 27 | nationality, personal appearance, race, religion, or sexual identity and 28 | orientation. 29 | 30 | ### Our Standards 31 | 32 | Examples of behavior that contributes to creating a positive environment 33 | include: 34 | 35 | * Using welcoming and inclusive language 36 | * Being respectful of differing viewpoints and experiences 37 | * Gracefully accepting constructive criticism 38 | * Focusing on what is best for the community 39 | * Showing empathy towards other community members 40 | 41 | Examples of unacceptable behavior by participants include: 42 | 43 | * The use of sexualized language or imagery and unwelcome sexual attention or 44 | advances 45 | * Trolling, insulting/derogatory comments, and personal or political attacks 46 | * Public or private harassment 47 | * Publishing others' private information, such as a physical or electronic 48 | address, without explicit permission 49 | * Other conduct which could reasonably be considered inappropriate in a 50 | professional setting 51 | 52 | ### Our Responsibilities 53 | 54 | Project maintainers are responsible for clarifying the standards of acceptable 55 | behavior and are expected to take appropriate and fair corrective action in 56 | response to any instances of unacceptable behavior. 57 | 58 | Project maintainers have the right and responsibility to remove, edit, or 59 | reject comments, commits, code, wiki edits, issues, and other contributions 60 | that are not aligned to this Code of Conduct, or to ban temporarily or 61 | permanently any contributor for other behaviors that they deem inappropriate, 62 | threatening, offensive, or harmful. 63 | 64 | ### Scope 65 | 66 | This Code of Conduct applies both within project spaces and in public spaces 67 | when an individual is representing the project or its community. Examples of 68 | representing a project or community include using an official project e-mail 69 | address, posting via an official social media account, or acting as an appointed 70 | representative at an online or offline event. Representation of a project may be 71 | further defined and clarified by project maintainers. 72 | 73 | ### Enforcement 74 | 75 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 76 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 77 | complaints will be reviewed and investigated and will result in a response that 78 | is deemed necessary and appropriate to the circumstances. The project team is 79 | obligated to maintain confidentiality with regard to the reporter of an incident. 80 | Further details of specific enforcement policies may be posted separately. 81 | 82 | Project maintainers who do not follow or enforce the Code of Conduct in good 83 | faith may face temporary or permanent repercussions as determined by other 84 | members of the project's leadership. 85 | 86 | ### Attribution 87 | 88 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 89 | available at [http://contributor-covenant.org/version/1/4][version] 90 | 91 | [homepage]: http://contributor-covenant.org 92 | [version]: http://contributor-covenant.org/version/1/4/ 93 | -------------------------------------------------------------------------------- /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 2018 Jordan Gregory 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 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | IMPORTANT: Please do not create a Pull Request without creating an issue first. 2 | 3 | Any change needs to be discussed before proceeding. Failure to do so may result in the rejection of the pull request. 4 | 5 | Please provide enough information so that others can review your pull request: 6 | 7 | Explain the details for making this change. What existing problem does the pull request solve? 8 | 9 | Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes UI. 10 | 11 | Code formatting 12 | 13 | Closing issues 14 | 15 | Put closes #XXXX in your comment to auto-close the issue that your PR fixes (if such). 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![made-with-python](https://img.shields.io/badge/Made%20with-Python-1f425f.svg)](https://www.python.org/) [![PyPI pyversions](https://img.shields.io/pypi/pyversions/ansicolortags.svg)](https://pypi.python.org/pypi/ansicolortags/) [![PyPI version](https://badge.fury.io/py/awsrightsizer.svg)](https://badge.fury.io/py/awsrightsizer) [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity) [![Open Source Love png2](https://badges.frapsoft.com/os/v2/open-source.png?v=103)](https://github.com/ellerbrock/open-source-badges/) 2 | 3 | # AWS EC2/RDS Instance Right-Sizer 4 | 5 | This tool is designed and written in Python 3.6.5 to help you determine the right AWS EC2/RDS instance type for your servers based on historical usage. 6 | 7 | ## Usage: 8 | 9 | ``` 10 | uUsage: rightsizer.py [OPTIONS] 11 | 12 | rightsizer takes user input and provides an output CSV of suggestions. 13 | 14 | Options: 15 | -p, --profile TEXT Your AWS Credentials Profile. 16 | -k, --access-key TEXT Your AWS Access Key ID. 17 | -s, --secret-key TEXT Your AWS Secret Access Key ID. 18 | -r, --region TEXT The AWS Region to query. 19 | -t, --threshold INTEGER... The Cloudwatch [average, max] CPU usage 20 | threshold. 21 | -q, --query-config INTEGER... The amount of [days, period] to query 22 | Cloudwatch for. 23 | -o, --output TEXT The Name/Location of the file to output. 24 | -e, --ec2-only 25 | -d, --rds-only 26 | -v, --verbose 27 | -h, --help Print help message 28 | 29 | ``` 30 | 31 | ## Installation: 32 | A pip package is available for this tool. This is the recommended way to install and run the tool. Download and run the tool using the steps below: 33 | 34 | 1. ```python3 -m pip install awsrightsizer --user``` 35 | 36 | 2. ```rightsizer [OPTIONS]``` 37 | 38 | ## Upgrading 39 | Upgrading is easy as well with pip, simply issue the following commands: 40 | 41 | 1. ```python3 -m pip install awsrightsizer --upgrade --user``` 42 | 43 | 2. ```rightsizer [OPTIONS]``` 44 | 45 | ## Source Installation: 46 | This tool is best run in a virtual environment. You may need to install a virtual environment tool such as python3-venv or python3-virutalenv via your package manager and/or install one via pip by running ```pip install virtualenv --user```. 47 | 48 | 1. ```git clone https://github.com/gregoryjordanm/awsrightsizer.git``` 49 | 50 | 2. ```cd ./awsrightsizer``` 51 | 52 | 3. ```python3 -m venv venv``` or ```virtualenv -p python3 venv``` 53 | 54 | 4. ```. ./venv/bin/activate``` 55 | 56 | 5. ```pip install -r requirements``` 57 | 58 | 6. ```python rightsizer.py [OPTIONS]``` 59 | 60 | ## Running Example: 61 | 62 | Lets assume for a second that you have already installed the AWS CLI tools for your distribution... 63 | 64 | Lets also assume that you have already run the ```aws configure``` command and have a profile named "dev" on your system that you have already tested and is functioning :) 65 | 66 | To run this tool with your working profile, simply do the following: 67 | 68 | ```rightsizer -p dev``` 69 | 70 | The tool will output a "report_*date*.csv" file in the directory you ran it in. 71 | 72 | Lets now assume that you hate my report name, simply run: 73 | 74 | ```rightsizer -p dev -o your_awesome_new_csv.csv``` 75 | 76 | The tool will now use your_awesome_new_csv.csv is the output file. 77 | 78 | If you don't have an AWS profile set up for some reason (it really does make life easier), then you can use the -k, -s. and -r flags to provide the necessary info. 79 | 80 | ```rightsizer -k XXXXXXXXXXXX -s XXXXXXXXXXXXXXXXXXXXXXXX -r us-east-1``` 81 | 82 | If you don't want to have the tool pull 30 days worth of data, or if you don't want the data periods to be 30 minutes, use the -q flag like so: 83 | 84 | ```rightsizer -p dev -q 15,900``` 85 | 86 | This will tell the tool to query 15 days at 15 minute intervals. 87 | 88 | To run against just your EC2 assets, just issue the -e flag. 89 | 90 | To run against just your RDS assets, just issue the -d flag. 91 | 92 | If you are running this via the source, you will need to add ```python rightsizer.py``` to your command instead of just ```rightsizer```. 93 | 94 | Let me know if you find bugs :) 95 | 96 | ### Attribution: 97 | 98 | This tools is loosely based on the [awsstats](https://github.com/FittedCloud/awsstats) tool by [FittedCloud](https://www.fittedcloud.com/). 99 | 100 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["poetry>=0.12"] 3 | build-backend = "poetry.masonry.api" 4 | 5 | [tool.poetry] 6 | name = "awsrightsizer" 7 | version = "1.1.2" 8 | description = "A Python3 tool to help you determine the correct instance types to use for your running EC2/RDS instances." 9 | authors = ["Jordan Gregory "] 10 | license = "Apache-2.0" 11 | readme = "README.md" 12 | classifiers=[ 13 | 'Development Status :: 5 - Production/Stable', 14 | 'Intended Audience :: System Administrators', 15 | 'License :: OSI Approved :: Apache Software License', 16 | 'Programming Language :: Python :: 3 :: Only' 17 | ] 18 | documentation = "http://awsrightsizer.readthedocs.io" 19 | repository = "https://github.com/Gregory-Development/awsrightsizer/" 20 | packages = [ 21 | { include = "rightsizer", from = "src" } 22 | ] 23 | 24 | [tool.poetry.dependencies] 25 | python = "^3.6" 26 | boto3 = "^1.9" 27 | click = "^7.0" 28 | 29 | [tool.poetry.dev-dependencies] 30 | pytest = "^3.9" 31 | 32 | [tool.poetry.scripts] 33 | rightsizer = 'rightsizer.main:main' -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | boto3==1.9.28 2 | botocore==1.12.28 3 | Click==7.0 4 | docutils==0.14 5 | jmespath==0.9.3 6 | python-dateutil==2.7.3 7 | s3transfer==0.1.13 8 | six==1.11.0 9 | urllib3==1.24.2 10 | -------------------------------------------------------------------------------- /rightsizer.py: -------------------------------------------------------------------------------- 1 | from src.rightsizer.main import main 2 | 3 | 4 | if __name__ == "__main__": 5 | main() 6 | -------------------------------------------------------------------------------- /src/rightsizer/AwsRightSizer.py: -------------------------------------------------------------------------------- 1 | # Standard Library Imports 2 | import logging 3 | from datetime import ( 4 | datetime, 5 | timedelta, 6 | ) 7 | 8 | # Third-Party Imports 9 | import boto3 10 | from botocore.exceptions import ClientError 11 | 12 | # Local Imports 13 | # Placeholder 14 | 15 | 16 | class Main: 17 | def __init__( 18 | self, 19 | thresholdAvg, 20 | thresholdMax, 21 | queryDays, 22 | queryPeriod, 23 | output, 24 | verbose, 25 | accessKey=None, 26 | secretKey=None, 27 | region=None, 28 | profile=None, 29 | ): 30 | self.accessKey = accessKey 31 | self.secretKey = secretKey 32 | self.region = region 33 | self.profile = profile 34 | self.threasholdAvg = thresholdAvg 35 | self.threasholdMax = thresholdMax 36 | self.queryDays = queryDays 37 | self.queryPeriod = queryPeriod 38 | self.output = output 39 | self.verbosity = verbose 40 | self.logger = self._init_logger() 41 | 42 | def _init_logger(self): 43 | l = logging.Logger(__name__) 44 | l.setLevel(self.verbosity) 45 | return l 46 | 47 | def _serialize_datetime(self, t): 48 | """ 49 | A method to serialize AWS datetime objects to be displayed as JSON (future use) 50 | :param t: 51 | :return: (string) the datetime object as a str object 52 | """ 53 | if isinstance(t, datetime): 54 | return t.__str__() 55 | 56 | def _init_connection(self, service): 57 | """ 58 | A method to initialize an AWS service connection with access/secret access keys. 59 | :param service: 60 | :return: (object) the AWS connection object. 61 | """ 62 | try: 63 | s = boto3.Session( 64 | aws_access_key_id='{}'.format(self.accessKey), 65 | aws_secret_access_key='{}'.format(self.secretKey), 66 | region_name='{}'.format(self.region), 67 | ) 68 | c = s.client('{}'.format(service)) 69 | return c 70 | except ClientError as e: 71 | self.logger.error('Error Connecting with the provided credentials. {}'.format(e)) 72 | return [] 73 | except Exception as e: 74 | self.logger.exception('General Exception ... {}'.format(e)) 75 | return [] 76 | 77 | def _init_profile(self, service): 78 | """ 79 | A method to initialize an AWS service connection with an AWS profile. 80 | :param service: 81 | :return: (object) the AWS connection object. 82 | """ 83 | try: 84 | s = boto3.Session( 85 | profile_name='{}'.format(self.profile) 86 | ) 87 | c = s.client('{}'.format(service)) 88 | return c 89 | except ClientError as e: 90 | self.logger.error('Error Connecting with the provided credentials... {}'.format(e)) 91 | return [] 92 | except Exception as e: 93 | self.logger.exception('General Exception ... {}'.format(e)) 94 | return [] 95 | 96 | def getec2suggestions(self): 97 | """ 98 | A method to suggest the right sizing for AWS EC2 Instances. 99 | :return: (dictionary) The dictionary result of the logic. 100 | """ 101 | if self.accessKey is not None: 102 | cwc = self._init_connection('cloudwatch') 103 | ec2c = self._init_connection('ec2') 104 | else: 105 | cwc = self._init_profile('cloudwatch') 106 | ec2c = self._init_profile('ec2') 107 | try: 108 | response = ec2c.describe_instances() 109 | except ClientError as e: 110 | self.logger.error('Failed to describe instances... {}'.format(e)) 111 | return [] 112 | except Exception as e: 113 | self.logger.exception('General Exception... {}'.format(e)) 114 | return [] 115 | 116 | now = datetime.now() 117 | sTime = now - timedelta(days=self.queryDays) 118 | eTime = now.strftime("%Y-%m-%d %H:%M:%S") 119 | 120 | info = [] 121 | 122 | for a in range(0, len(response['Reservations'])): 123 | for b in range(0, len(response['Reservations'][a]['Instances'])): 124 | base = response['Reservations'][a]['Instances'][b] 125 | try: 126 | instanceState = base['State']['Name'] 127 | except KeyError: 128 | self.logger.exception('Instance State Undefined') 129 | return [] 130 | except Exception as e: 131 | self.logger.exception('General Exception ... {}'.format(e)) 132 | return [] 133 | 134 | try: 135 | instanceId = base['InstanceId'] 136 | except KeyError: 137 | self.logger.exception('Instance Id Undefined') 138 | return [] 139 | except Exception as e: 140 | self.logger.exception('General Exception ... {}'.format(e)) 141 | return [] 142 | 143 | try: 144 | instanceType = base['InstanceType'] 145 | except KeyError: 146 | self.logger.exception('Instance Type Undefined') 147 | return [] 148 | except Exception as e: 149 | self.logger.exception('Gerneral Exception ... {}'.format(e)) 150 | return [] 151 | 152 | if instanceState != 'terminated': 153 | try: 154 | for c in range(0, len(base['Tags'])): 155 | if base['Tags'][c]['Key'] == 'Name': 156 | instanceName = base['Tags'][c]['Value'] 157 | except KeyError: 158 | self.logger.info("Instance Name Undefined, Setting to 'Undefined'") 159 | instanceName = 'Undefined' 160 | try: 161 | res = cwc.get_metric_statistics( 162 | Namespace='AWS/EC2', 163 | MetricName='CPUUtilization', 164 | Dimensions=[ 165 | { 166 | 'Name': 'InstanceId', 167 | 'Value': '{}'.format(instanceId) 168 | } 169 | ], 170 | StartTime=sTime, 171 | EndTime=eTime, 172 | Period=self.queryPeriod, 173 | Statistics=[ 174 | 'Average', 175 | ], 176 | Unit='Percent' 177 | ) 178 | for x in range(0, len(res['Datapoints'])): 179 | metrics = [] 180 | cwbase = res['Datapoints'][x] 181 | Average = cwbase['Average'] 182 | metrics.append(Average) 183 | 184 | totalAvg = round((sum(metrics)/len(metrics)), 2) 185 | 186 | # General Purpose Instance Types 187 | 188 | t1types = [ 189 | 'micro', 190 | ] 191 | 192 | t2types = [ 193 | 'nano', 194 | 'micro', 195 | 'small', 196 | 'medium', 197 | 'large', 198 | 'xlarge', 199 | '2xlarge', 200 | ] 201 | 202 | m1types = [ 203 | 'small', 204 | 'medium', 205 | 'large', 206 | 'xlarge', 207 | ] 208 | 209 | m3types = [ 210 | 'medium', 211 | 'large', 212 | 'xlarge', 213 | '2xlarge', 214 | ] 215 | 216 | m4types = [ 217 | 'large', 218 | 'xlarge', 219 | '2xlarge', 220 | '4xlarge', 221 | '10xlarge', 222 | '16xlarge', 223 | ] 224 | 225 | m5types = [ 226 | 'large', 227 | 'xlarge', 228 | '2xlarge', 229 | '4xlarge', 230 | '12xlarge', 231 | '24xlarge', 232 | ] 233 | 234 | m5dtypes = [ 235 | 'large', 236 | 'xlarge', 237 | '2xlarge', 238 | '4xlarge', 239 | '12xlarge', 240 | '24xlarge', 241 | ] 242 | 243 | # Compute Optimized Instance Types 244 | 245 | c1types = [ 246 | 'medium', 247 | 'xlarge', 248 | ] 249 | 250 | cc2types = [ 251 | '8xlarge', 252 | ] 253 | 254 | c3types = [ 255 | 'large', 256 | 'xlarge', 257 | '2xlarge', 258 | '4xlarge', 259 | '8xlarge', 260 | ] 261 | 262 | c4types = [ 263 | 'large', 264 | 'xlarge', 265 | '2xlarge', 266 | '4xlarge', 267 | '8xlarge', 268 | ] 269 | 270 | c5types = [ 271 | 'large', 272 | 'xlarge', 273 | '2xlarge', 274 | '4xlarge', 275 | '9xlarge', 276 | '18xlarge', 277 | ] 278 | 279 | c5dtypes = [ 280 | 'large', 281 | 'xlarge', 282 | '2xlarge', 283 | '4xlarge', 284 | '9xlarge', 285 | '18xlarge', 286 | ] 287 | 288 | # Memory Optimized Instance Types 289 | 290 | cr1types = [ 291 | '8xlarge', 292 | ] 293 | 294 | m2types = [ 295 | 'xlarge', 296 | '2xlarge', 297 | '4xlarge', 298 | ] 299 | 300 | r3types = [ 301 | 'large', 302 | 'xlarge', 303 | '2xlarge', 304 | '4xlarge', 305 | '8xlarge', 306 | ] 307 | 308 | r4types = [ 309 | 'large', 310 | 'xlarge', 311 | '2xlarge', 312 | '4xlarge', 313 | '8xlarge', 314 | '16xlarge', 315 | ] 316 | 317 | r5types = [ 318 | 'large', 319 | 'xlarge', 320 | '2xlarge', 321 | '4xlarge', 322 | '12xlarge', 323 | '24xlarge', 324 | ] 325 | 326 | r5dtypes = [ 327 | 'large', 328 | 'xlarge', 329 | '2xlarge', 330 | '4xlarge', 331 | '12xlarge', 332 | '24xlarge', 333 | ] 334 | 335 | x1types = [ 336 | '16xlarge', 337 | '32xlarge' 338 | ] 339 | 340 | x1etypes = [ 341 | 'xlarge', 342 | '2xlarge', 343 | '4xlarge', 344 | '8xlarge', 345 | '16xlarge', 346 | '32xlarge', 347 | ] 348 | 349 | z1dtypes = [ 350 | 'large', 351 | 'xlarge', 352 | '2xlarge', 353 | '3xlarge', 354 | '6xlarge', 355 | '12xlarge', 356 | ] 357 | 358 | # GPU/Accelerated Compute Optimized Instance Types 359 | 360 | g2types = [ 361 | '2xlarge', 362 | '8xlarge', 363 | ] 364 | 365 | g3types = [ 366 | '4xlarge', 367 | '8xlarge', 368 | '16xlarge', 369 | ] 370 | 371 | p2types = [ 372 | 'xlarge', 373 | '8xlarge', 374 | '16xlarge', 375 | ] 376 | 377 | p3types = [ 378 | '2xlarge', 379 | '8xlarge', 380 | '16xlarge', 381 | ] 382 | 383 | f1types = [ 384 | '2xlarge', 385 | '16xlarge', 386 | ] 387 | 388 | # Storage Optimized Instance Types 389 | 390 | i2types = [ 391 | 'xlarge', 392 | '2xlarge', 393 | '4xlarge', 394 | '8xlarge', 395 | ] 396 | 397 | i3types = [ 398 | 'large', 399 | 'xlarge', 400 | '2xlarge', 401 | '4xlarge', 402 | '8xlarge', 403 | '16xlarge', 404 | 'metal', 405 | ] 406 | 407 | h1types = [ 408 | '2xlarge', 409 | '4xlarge', 410 | '8xlarge', 411 | '16xlarge', 412 | ] 413 | 414 | hs1types = [ 415 | '8xlarge', 416 | ] 417 | 418 | d2types = [ 419 | 'xlarge', 420 | '2xlarge', 421 | '4xlarge', 422 | '8xlarge', 423 | ] 424 | 425 | typesplit = instanceType.split('.') 426 | 427 | # If instance is already t2.nano, keep it the same 428 | 429 | if instanceType == 't2.nano': 430 | suggestedType = 't2.{}'.format(t2types[0]) 431 | 432 | # Suggest Instance Types based on AVG CPU usage keeping general instance type class, current gen only 433 | if typesplit[0] == 't1': 434 | suggestedType = 't2.{}'.format(t2types[0]) 435 | elif typesplit[0] == 't2': 436 | typeindex = t2types.index('{}'.format(typesplit[1])) 437 | if totalAvg <=5: 438 | suggestedType = '{}.{}'.format(typesplit[0], t2types[0]) 439 | elif totalAvg > 5 <= 30: 440 | index = typeindex -1 441 | if index < 0: 442 | suggestedType = '{}.{}'.format(typesplit[0], t2types[0]) 443 | else: 444 | suggestedType = '{}.{}'.format(typesplit[0], t2types[index]) 445 | elif totalAvg > 30 <= 80: 446 | suggestedType = '{}'.format(instanceType) 447 | elif totalAvg > 80: 448 | try: 449 | index = typeindex + 1 450 | suggestedType = '{}.{}'.format(typesplit[0], t2types[index]) 451 | except IndexError: 452 | suggestedType = 'm4.{}'.format(m4types[3]) 453 | elif typesplit[0] == 'm5': 454 | typeindex = m5types.index('{}'.format(typesplit[1])) 455 | if totalAvg <= 5: 456 | suggestedType = '{}.{}'.format(typesplit[0], m5types[0]) 457 | elif totalAvg > 5 <= 30: 458 | index = typeindex -1 459 | if index < 0: 460 | suggestedType = '{}.{}'.format(typesplit[0], m5types[0]) 461 | else: 462 | suggestedType = '{}.{}'.format(typesplit[0], m5types[index]) 463 | elif totalAvg > 30 <= 80: 464 | suggestedType = '{}'.format(instanceType) 465 | elif totalAvg > 80: 466 | try: 467 | index = typeindex + 1 468 | suggestedType = '{}.{}'.format(typesplit[0], m5types[index]) 469 | except IndexError: 470 | suggestedType = 'm5.{}'.format(m5types[5]) 471 | elif typesplit[0] == 'm5d': 472 | typeindex = m5dtypes.index('{}'.format(typesplit[1])) 473 | if totalAvg <= 5: 474 | suggestedType = '{}.{}'.format(typesplit[0], m5dtypes[0]) 475 | elif totalAvg > 5 <= 30: 476 | index = typeindex - 1 477 | if index < 0: 478 | suggestedType = '{}.{}'.format(typesplit[0], m5dtypes[0]) 479 | else: 480 | suggestedType = '{}.{}'.format(typesplit[0], m5dtypes[index]) 481 | elif totalAvg > 30 <= 80: 482 | suggestedType = '{}'.format(instanceType) 483 | elif totalAvg > 80: 484 | try: 485 | index = typeindex + 1 486 | suggestedType = '{}.{}'.format(typesplit[0], m5dtypes[index]) 487 | except IndexError: 488 | suggestedType = 'm5d.{}'.format(m5dtypes[5]) 489 | elif typesplit[0] == 'm4': 490 | typeindex = m4types.index('{}'.format(typesplit[1])) 491 | if totalAvg <= 5: 492 | suggestedType = '{}.{}'.format(typesplit[0], m4types[0]) 493 | elif totalAvg > 5 <= 30: 494 | index = typeindex - 1 495 | if index < 0: 496 | suggestedType = '{}.{}'.format(typesplit[0], m4types[0]) 497 | else: 498 | suggestedType = '{}.{}'.format(typesplit[0], m4types[index]) 499 | elif totalAvg > 30 <= 80: 500 | suggestedType = '{}'.format(instanceType) 501 | elif totalAvg > 80: 502 | try: 503 | index = typeindex + 1 504 | suggestedType = '{}.{}'.format(typesplit[0], m4types[index]) 505 | except IndexError: 506 | suggestedType = 'm5.{}'.format(m5types[5]) 507 | elif typesplit[0] == 'm3': # PrevGen Upgrade to M5 508 | typeindex = m3types.index(typesplit[1]) 509 | if totalAvg <= 5: 510 | suggestedType = 't2.{}*'.format(t2types[2]) 511 | elif totalAvg > 5 <= 30: 512 | index = typeindex - 2 513 | if index < 0: 514 | suggestedType = 't2.{}*'.format(t2types[3]) 515 | else: 516 | suggestedType = 'm5.{}*'.format(m5types[index]) 517 | elif totalAvg > 30 <= 80: 518 | index = typeindex - 1 519 | if index < 0: 520 | suggestedType = 'm5.{}*'.format(m5types[2]) 521 | else: 522 | suggestedType = 'm5.{}*'.format(m5types[index]) 523 | elif totalAvg > 80: 524 | try: 525 | suggestedType = 'm5.{}*'.format(m5types[typeindex]) 526 | except IndexError: 527 | suggestedType = 'm5.{}*'.format(m5types[2]) 528 | elif typesplit[0] == 'm2': # PrevGen Upgrade to R4 529 | typeindex = m2types.index('{}'.format(typesplit[1])) 530 | if totalAvg <= 5: 531 | suggestedType = 'r4.{}*'.format(r4types[0]) 532 | elif totalAvg > 5 <= 30: 533 | index = typeindex - 1 534 | if index < 0: 535 | suggestedType = 'r4.{}*'.format(r4types[0]) 536 | else: 537 | suggestedType = 'r4.{}*'.format(r4types[index]) 538 | elif totalAvg > 30 <= 80: 539 | index = typeindex + 1 540 | suggestedType = 'r4.{}*'.format(r4types[index]) 541 | elif totalAvg > 80: 542 | index = typeindex + 2 543 | try: 544 | suggestedType = 'r4.{}*'.format(r4types[index]) 545 | except IndexError: 546 | suggestedType = 'r4.{}*'.format(r4types[5]) 547 | elif typesplit[0] == 'm1': # PrevGen Upgrade to T2 548 | typeindex = m1types.index('{}'.format(typesplit[1])) 549 | if totalAvg <= 5: 550 | suggestedType = 't2.{}*'.format(t2types[0]) 551 | elif totalAvg > 5 <= 30: 552 | index = typeindex - 1 553 | if index < 0: 554 | suggestedType = 't2.{}*'.format(t2types[0]) 555 | else: 556 | suggestedType = 't2.{}*'.format(t2types[index]) 557 | elif totalAvg > 30 <= 80: 558 | suggestedType = 't2.{}*'.format(t2types[typeindex]) 559 | elif totalAvg > 80: 560 | try: 561 | index = typeindex + 1 562 | suggestedType = 't2.{}*'.format(t2types[index]) 563 | except IndexError: 564 | suggestedType = 'm4.{}*'.format(m4types[3]) 565 | elif typesplit[0] == 'c5': 566 | typeindex = c5types.index('{}'.format(typesplit[1])) 567 | if totalAvg <= 5: 568 | suggestedType = '{}.{}'.format(typesplit[0], c5types[0]) 569 | elif totalAvg > 5 <= 30: 570 | index = typeindex - 1 571 | if index < 0: 572 | suggestedType = '{}.{}'.format(typesplit[0], c5types[0]) 573 | else: 574 | suggestedType = '{}.{}'.format(typesplit[0], c5types[index]) 575 | elif totalAvg > 30 <= 80: 576 | suggestedType = '{}'.format(instanceType) 577 | elif totalAvg > 80: 578 | try: 579 | index = typeindex + 1 580 | suggestedType = '{}.{}'.format(typesplit[0], c5types[index]) 581 | except IndexError: 582 | suggestedType = 'c5.{}'.format(c5types[5]) 583 | elif typesplit[0] == 'c5d': 584 | typeindex = c5dtypes.index('{}'.format(typesplit[1])) 585 | if totalAvg <= 5: 586 | suggestedType = '{}.{}'.format(typesplit[0], c5dtypes[0]) 587 | elif totalAvg > 5 <= 30: 588 | index = typeindex -1 589 | if index < 0: 590 | suggestedType = '{}.{}'.format(typesplit[0], c5dtypes[0]) 591 | else: 592 | suggestedType = '{}.{}'.format(typesplit[0], c5dtypes[index]) 593 | elif totalAvg > 30 <= 80: 594 | suggestedType = '{}'.format(instanceType) 595 | elif totalAvg > 80: 596 | try: 597 | index = typeindex + 1 598 | suggestedType = '{}.{}'.format(typesplit[0], c5dtypes[index]) 599 | except IndexError: 600 | suggestedType = 'c5d.{}'.format(c5dtypes[5]) 601 | elif typesplit[0] == 'c4': 602 | typeindex = c4types.index('{}'.format(typesplit[1])) 603 | if totalAvg <= 5: 604 | suggestedType = '{}.{}'.format(typesplit[0], c4types[0]) 605 | elif totalAvg > 5 <= 30: 606 | index = typeindex - 1 607 | if index < 0: 608 | suggestedType = '{}.{}'.format(typesplit[0], c4types[0]) 609 | else: 610 | suggestedType = '{}.{}'.format(typesplit[0], c4types[index]) 611 | elif totalAvg > 30 <= 80: 612 | suggestedType = '{}'.format(instanceType) 613 | elif totalAvg > 80: 614 | try: 615 | index = typeindex + 1 616 | suggestedType = '{}.{}'.format(typesplit[0], c4types[index]) 617 | except IndexError: 618 | suggestedType = 'c5.{}'.format(c5types[5]) 619 | elif typesplit[0] == 'c3': # PrevGen Upgrade to C5 620 | typeindex = c3types.index('{}'.format(typesplit[1])) 621 | if totalAvg <= 5: 622 | suggestedType = 'c5.{}*'.format(c5types[0]) 623 | elif totalAvg > 5 <= 30: 624 | index = typeindex - 1 625 | if index < 0: 626 | suggestedType = 'c5.{}*'.format(c5types[0]) 627 | else: 628 | suggestedType = 'c5.{}*'.format(c5types[index]) 629 | elif totalAvg > 30 <= 80: 630 | suggestedType = 'c5.{}*'.format(c5types[typeindex]) 631 | elif totalAvg > 80: 632 | try: 633 | index = typeindex + 1 634 | suggestedType = 'c5.{}*'.format(c5types[index]) 635 | except IndexError: 636 | suggestedType = 'c5.{}*'.format(c5types[5]) 637 | elif typesplit[0] == 'cc2': # PrevGen Upgrade to C5 638 | typeindex = cc2types.index('{}'.format(typesplit[1])) 639 | if totalAvg <= 5: 640 | suggestedType = 'c5.{}*'.format(c5types[0]) 641 | elif totalAvg > 5 <= 30: 642 | index = typeindex - 1 643 | if index < 0: 644 | suggestedType = 'c5.{}*'.format(c5types[3]) 645 | else: 646 | suggestedType = 'c5.{}*'.format(c5types[index]) 647 | elif totalAvg > 30 <= 80: 648 | suggestedType = 'c5.{}*'.format(c5types[4]) 649 | elif totalAvg > 80: 650 | try: 651 | index = typeindex + 1 652 | suggestedType = 'c5.{}*'.format(c5types[index]) 653 | except IndexError: 654 | suggestedType = 'c5.{}*'.format(c5types[5]) 655 | elif typesplit[0] == 'cr1': # PrevGen Upgrade to R4 656 | typeindex = m2types.index('{}'.format(typesplit[1])) 657 | if totalAvg <= 30: 658 | suggestedType = 'r4.{}'.format(r4types[0]) 659 | elif totalAvg > 30 <= 80: 660 | suggestedType = 'r4.{}'.format(r4types[4]) 661 | elif totalAvg > 80: 662 | suggestedType = 'r4.{}'.format(r4types[5]) 663 | elif typesplit[0] == 'c1': # PrevGen Upgrade to C5 664 | typeindex = c1types.index('{}'.format(typesplit[1])) 665 | if totalAvg <= 5: 666 | suggestedType = 'c5.{}*'.format(c5types[0]) 667 | elif totalAvg > 5 <= 30: 668 | index = typeindex - 1 669 | if index < 0: 670 | suggestedType = 'c5.{}*'.format(c5types[0]) 671 | else: 672 | suggestedType = 'c5.{}*'.format(c5types[index]) 673 | elif totalAvg > 30 <= 80: 674 | suggestedType = 'c5.{}*'.format(c5types[typeindex]) 675 | elif totalAvg > 80: 676 | try: 677 | index = typeindex + 1 678 | suggestedType = 'c5.{}*'.format(c5types[index]) 679 | except IndexError: 680 | suggestedType = 'c5.{}*'.format(c5types[5]) 681 | elif typesplit[0] == 'x1': 682 | typeindex = x1types.index('{}'.format(typesplit[1])) 683 | if totalAvg <= 5: 684 | suggestedType = '{}.{}'.format(typesplit[0], x1types[0]) 685 | elif totalAvg > 5 <= 30: 686 | index = typeindex - 1 687 | if index < 0: 688 | suggestedType = '{}.{}'.format(typesplit[0], x1types[0]) 689 | else: 690 | suggestedType = '{}.{}'.format(typesplit[0], x1types[index]) 691 | elif totalAvg > 30 <= 80: 692 | suggestedType = '{}'.format(instanceType) 693 | elif totalAvg > 80: 694 | try: 695 | index = typeindex + 1 696 | suggestedType = '{}.{}'.format(typesplit[0], x1types[index]) 697 | except IndexError: 698 | suggestedType = 'x1e.{}'.format(x1etypes[5]) 699 | elif typesplit[0] == 'x1e': 700 | typeindex = x1etypes.index('{}'.format(typesplit[1])) 701 | if totalAvg <= 5: 702 | suggestedType = '{}.{}'.format(typesplit[0], x1etypes[0]) 703 | elif totalAvg > 5 <= 30: 704 | index = typeindex -1 705 | if index < 0: 706 | suggestedType = '{}.{}'.format(typesplit[0], x1etypes[0]) 707 | else: 708 | suggestedType = '{}.{}'.format(typesplit[0], x1etypes[index]) 709 | elif totalAvg > 30 <= 80: 710 | suggestedType = '{}'.format(instanceType) 711 | elif totalAvg > 80: 712 | try: 713 | index = typeindex + 1 714 | suggestedType = '{}.{}'.format(typesplit[0], x1etypes[index]) 715 | except IndexError: 716 | suggestedType = 'x1e.{}'.format(x1etypes[5]) 717 | elif typesplit[0] == 'z1d': 718 | typeindex = z1dtypes.index('{}'.format(typesplit[1])) 719 | if totalAvg <= 5: 720 | suggestedType = '{}.{}'.format(typesplit[0], z1dtypes[0]) 721 | elif totalAvg > 5 <= 30: 722 | index = typeindex - 1 723 | if index < 0: 724 | suggestedType = '{}.{}'.format(typesplit[0], z1dtypes[0]) 725 | else: 726 | suggestedType = '{}.{}'.format(typesplit[0], z1dtypes[index]) 727 | elif totalAvg > 30 <= 80: 728 | suggestedType = '{}'.format(instanceType) 729 | elif totalAvg > 80: 730 | try: 731 | index = typeindex + 1 732 | suggestedType = '{}.{}'.format(typesplit[0], z1dtypes[index]) 733 | except IndexError: 734 | suggestedType = 'x1.{}'.format(x1types[0]) 735 | elif typesplit[0] == 'r5d': 736 | typeindex = r5dtypes.index('{}'.format(typesplit[1])) 737 | if totalAvg <= 5: 738 | suggestedType = '{}.{}'.format(typesplit[0], r5dtypes[0]) 739 | elif totalAvg > 5 <= 30: 740 | index = typeindex - 1 741 | if index < 0: 742 | suggestedType = '{}.{}'.format(typesplit[0], r5dtypes[0]) 743 | else: 744 | suggestedType = '{}.{}'.format(typesplit[0], r5dtypes[index]) 745 | elif totalAvg > 30 <= 80: 746 | suggestedType = '{}'.format(instanceType) 747 | elif totalAvg > 80: 748 | try: 749 | index = typeindex + 1 750 | suggestedType = '{}.{}'.format(typesplit[0], r5dtypes[index]) 751 | except IndexError: 752 | suggestedType = 'x1.{}'.format(x1types[0]) 753 | elif typesplit[0] == 'r5': 754 | typeindex = r5types.index('{}'.format(typesplit[1])) 755 | if totalAvg <= 5: 756 | suggestedType = '{}.{}'.format(typesplit[0], r5types[0]) 757 | elif totalAvg > 5 <= 30: 758 | index = typeindex - 1 759 | if index < 0: 760 | suggestedType = '{}.{}'.format(typesplit[0], r5types[0]) 761 | else: 762 | suggestedType = '{}.{}'.format(typesplit[0], r5types[index]) 763 | elif totalAvg > 30 <= 80: 764 | suggestedType = '{}'.format(instanceType) 765 | elif totalAvg > 80: 766 | try: 767 | index = typeindex + 1 768 | suggestedType = '{}.{}'.format(typesplit[0], r5types[index]) 769 | except IndexError: 770 | suggestedType = 'x1.{}'.format(x1types[0]) 771 | elif typesplit[0] == 'r4': 772 | typeindex = r4types.index('{}'.format(typesplit[1])) 773 | if totalAvg <= 5: 774 | suggestedType = '{}.{}'.format(typesplit[0], r4types[0]) 775 | elif totalAvg > 5 <= 30: 776 | index = typeindex - 1 777 | if index < 0: 778 | suggestedType = '{}.{}'.format(typesplit[0], r4types[0]) 779 | else: 780 | suggestedType = '{}.{}'.format(typesplit[0], r4types[index]) 781 | elif totalAvg > 30 <= 80: 782 | suggestedType = '{}'.format(instanceType) 783 | elif totalAvg > 80: 784 | try: 785 | index = typeindex + 1 786 | suggestedType = '{}.{}'.format(typesplit[0], r4types[index]) 787 | except IndexError: 788 | suggestedType = 'r5.{}'.format(r5types[5]) 789 | elif typesplit[0] == 'r3': # PrevGen Upgrade to R4 790 | typeindex = r3types.index('{}'.format(typesplit[1])) 791 | if totalAvg <= 5: 792 | suggestedType = 'r4.{}*'.format(r4types[0]) 793 | elif totalAvg > 5 <= 30: 794 | index = typeindex - 1 795 | if index < 0: 796 | suggestedType = 'r4.{}*'.format(r4types[0]) 797 | else: 798 | suggestedType = 'r4.{}*'.format(r4types[index]) 799 | elif totalAvg > 30 <= 80: 800 | suggestedType = 'r4.{}*'.format(r4types[typeindex]) 801 | elif totalAvg > 80: 802 | try: 803 | index = typeindex + 1 804 | suggestedType = 'r4.{}*'.format(r4types[index]) 805 | except IndexError: 806 | suggestedType = 'x1.{}*'.format(x1types[0]) 807 | elif typesplit[0] == 'p2': 808 | typeindex = p2types.index('{}'.format(typesplit[1])) 809 | if totalAvg <= 5: 810 | suggestedType = '{}.{}'.format(typesplit[0], p2types[0]) 811 | elif totalAvg > 5 <= 30: 812 | index = typeindex - 1 813 | if index < 0: 814 | suggestedType = '{}.{}'.format(typesplit[0], p2types[0]) 815 | else: 816 | suggestedType = '{}.{}'.format(typesplit[0], p2types[index]) 817 | elif totalAvg > 30 <= 80: 818 | suggestedType = '{}'.format(instanceType) 819 | elif totalAvg > 80: 820 | try: 821 | index = typeindex + 1 822 | suggestedType = '{}.{}'.format(typesplit[0], p2types[index]) 823 | except IndexError: 824 | suggestedType = 'g3.{}'.format(g3types[0]) 825 | elif typesplit[0] == 'p3': 826 | typeindex = p3types.index('{}'.format(typesplit[1])) 827 | if totalAvg <= 5: 828 | suggestedType = '{}.{}'.format(typesplit[0], p3types[0]) 829 | elif totalAvg > 5 <= 30: 830 | index = typeindex - 1 831 | if index < 0: 832 | suggestedType = '{}.{}'.format(typesplit[0], p3types[0]) 833 | else: 834 | suggestedType = '{}.{}'.format(typesplit[0], p3types[index]) 835 | elif totalAvg > 30 <= 80: 836 | suggestedType = '{}'.format(instanceType) 837 | elif totalAvg > 80: 838 | try: 839 | index = typeindex + 1 840 | suggestedType = '{}.{}'.format(typesplit[0], p3types[index]) 841 | except IndexError: 842 | suggestedType = 'g3.{}'.format(g3types[0]) 843 | elif typesplit[0] == 'g3': 844 | typeindex = g3types.index('{}'.format(typesplit[1])) 845 | if totalAvg <= 5: 846 | suggestedType = '{}.{}'.format(typesplit[0], g3types[0]) 847 | elif totalAvg > 5 <= 30: 848 | index = typeindex - 1 849 | if index < 0: 850 | suggestedType = '{}.{}'.format(typesplit[0], g3types[0]) 851 | else: 852 | suggestedType = '{}.{}'.format(typesplit[0], g3types[index]) 853 | elif totalAvg > 30 <= 80: 854 | suggestedType = '{}'.format(instanceType) 855 | elif totalAvg > 80: 856 | try: 857 | index = typeindex + 1 858 | suggestedType = '{}.{}'.format(typesplit[0], g3types[index]) 859 | except IndexError: 860 | suggestedType = 'f1.{}'.format(f1types[1]) 861 | elif typesplit[0] == 'g2': # PrevGen Upgrade to G3 862 | typeindex = g2types.index('{}'.format(typesplit[1])) 863 | if totalAvg <= 5: 864 | suggestedType = 'g3.{}*'.format(g3types[0]) 865 | elif totalAvg > 5 <= 30: 866 | index = typeindex - 1 867 | if index < 0: 868 | suggestedType = 'g3.{}*'.format(g3types[0]) 869 | else: 870 | suggestedType = 'g3.{}*'.format(g3types[index]) 871 | elif totalAvg > 30 <= 80: 872 | suggestedType = 'g3.{}*'.format(typeindex) 873 | elif totalAvg > 80: 874 | try: 875 | index = typeindex + 1 876 | suggestedType = 'g3.{}*'.format(g3types[index]) 877 | except IndexError: 878 | suggestedType = 'f1.{}*'.format(f1types[1]) 879 | elif typesplit[0] == 'f1': 880 | typeindex = f1types.index('{}'.format(typesplit[1])) 881 | if totalAvg <= 5: 882 | suggestedType = '{}.{}'.format(typesplit[0], f1types[0]) 883 | elif totalAvg > 5 <= 30: 884 | index = typeindex - 1 885 | if index < 0: 886 | suggestedType = '{}.{}'.format(typesplit[0], f1types[0]) 887 | else: 888 | suggestedType = '{}.{}'.format(typesplit[0], f1types[index]) 889 | elif totalAvg > 30 <= 80: 890 | suggestedType = '{}'.format(instanceType) 891 | elif totalAvg > 80: 892 | try: 893 | index = typeindex + 1 894 | suggestedType = '{}.{}'.format(typesplit[0], f1types[index]) 895 | except IndexError: 896 | suggestedType = 'f1.{}'.format(f1types[1]) 897 | elif typesplit[0] == 'hs1': # PrevGen Upgrade to d2 898 | typeindex = hs1types.index('{}'.format(typesplit[1])) 899 | if totalAvg <= 5: 900 | suggestedType = 'd2.{}*'.format(d2types[0]) 901 | elif totalAvg > 5 <= 30: 902 | suggestedType = 'd2.{}*'.format(d2types[1]) 903 | elif totalAvg > 30: 904 | suggestedType = 'd2.{}*'.format(d2types[3]) 905 | elif typesplit[0] == 'h1': 906 | typeindex = h1types.index('{}'.format(typesplit[1])) 907 | if totalAvg <= 5: 908 | suggestedType = '{}.{}'.format(typesplit[0], h1types[0]) 909 | elif totalAvg > 5 <= 30: 910 | index = typeindex - 1 911 | if index < 0: 912 | suggestedType = '{}.{}'.format(typesplit[0], h1types[0]) 913 | else: 914 | suggestedType = '{}.{}'.format(typesplit[0], h1types[index]) 915 | elif totalAvg > 30 <= 80: 916 | suggestedType = '{}'.format(instanceType) 917 | elif totalAvg > 80: 918 | try: 919 | index = typeindex + 1 920 | suggestedType = '{}.{}'.format(typesplit[0], h1types[index]) 921 | except IndexError: 922 | suggestedType = 'i3.{}'.format(i3types[6]) 923 | elif typesplit[0] == 'i3': 924 | typeindex = i3types.index('{}'.format(typesplit[1])) 925 | if totalAvg <= 5: 926 | suggestedType = '{}.{}'.format(typesplit[0], i3types[0]) 927 | elif totalAvg > 5 <= 30: 928 | index = typeindex - 1 929 | if index < 0: 930 | suggestedType = '{}.{}'.format(typesplit[0], i3types[0]) 931 | else: 932 | suggestedType = '{}.{}'.format(typesplit[0], i3types[index]) 933 | elif totalAvg > 30 <= 80: 934 | suggestedType = '{}'.format(instanceType) 935 | elif totalAvg > 80: 936 | try: 937 | index = typeindex + 1 938 | suggestedType = '{}.{}'.format(typesplit[0], i3types[index]) 939 | except IndexError: 940 | suggestedType = 'i3.{}'.format(i3types[6]) 941 | elif typesplit[0] == 'i2': # PrevGen Upgread to i3 942 | typeindex = i2types.index('{}'.format(typesplit[1])) 943 | if totalAvg <= 5: 944 | suggestedType = 'i3.{}*'.format(i3types[0]) 945 | elif totalAvg > 5 <= 30: 946 | try: 947 | suggestedType = 'i3.{}*'.format(i3types[typeindex]) 948 | except ValueError: 949 | suggestedType = 'i3.{}*'.format(i3types[0]) 950 | elif totalAvg > 30 <= 80: 951 | suggestedType = 'i3.{}*'.format(i3types[typeindex]) 952 | elif totalAvg > 80: 953 | try: 954 | index = typeindex + 2 955 | suggestedType = 'i3.{}*'.format(i3types[index]) 956 | except IndexError: 957 | suggestedType = 'i3.{}*'.format(i3types[6]) 958 | elif typesplit[0] == 'd2': 959 | typeindex = d2types.index('{}'.format(typesplit[1])) 960 | if totalAvg <= 5: 961 | suggestedType = '{}.{}'.format(typesplit[0], d2types[0]) 962 | elif totalAvg > 5 <= 30: 963 | index = typeindex - 1 964 | if index < 0: 965 | suggestedType = '{}.{}'.format(typesplit[0], d2types[0]) 966 | else: 967 | suggestedType = '{}.{}'.format(typesplit[0], d2types[index]) 968 | elif totalAvg > 30 <= 80: 969 | suggestedType = '{}'.format(instanceType) 970 | elif totalAvg > 80: 971 | try: 972 | index = typeindex + 1 973 | suggestedType = '{}.{}'.format(typesplit[0], d2types[index]) 974 | except IndexError: 975 | suggestedType = 'd2.{}'.format(d2types[3]) 976 | 977 | except ClientError as e: 978 | self.logger.error('Error getting metrics for instance {}...{}'.format(b, e)) 979 | except Exception as e: 980 | self.logger.exception('General Exception ... {}'.format(e)) 981 | 982 | info.append( 983 | { 984 | 'Id': '{}'.format(instanceId), 985 | 'Name': '{}'.format(instanceName), 986 | 'AvgCpu': totalAvg, 987 | 'CurrentType': '{}'.format(instanceType), 988 | 'SuggestedType': '{}'.format(suggestedType) 989 | } 990 | ) 991 | 992 | return info 993 | 994 | def getrdssuggestions(self): 995 | """ 996 | A method to suggest the right sizing for AWS RDS Instances. 997 | :return: (dictionary) The dictionary result of the logic. 998 | """ 999 | if self.accessKey is not None: 1000 | cwc = self._init_connection('cloudwatch') 1001 | rdsc = self._init_connection('rds') 1002 | else: 1003 | cwc = self._init_profile('cloudwatch') 1004 | rdsc = self._init_profile('rds') 1005 | try: 1006 | response = rdsc.describe_db_instances() 1007 | except ClientError as e: 1008 | self.logger.error('Failed to describe rds instances... {}'.format(e)) 1009 | return [] 1010 | except Exception as e: 1011 | self.logger.exception('General Exception ... {}'.format(e)) 1012 | return [] 1013 | 1014 | now = datetime.now() 1015 | sTime = now - timedelta(days=self.queryDays) 1016 | eTime = now.strftime("%Y-%m-%d %H:%M:%S") 1017 | 1018 | info = [] 1019 | 1020 | for a in range(0, len(response['DBInstances'])): 1021 | base = response['DBInstances'][a] 1022 | try: 1023 | DBInstanceStatus = base['DBInstanceStatus'] 1024 | except KeyError: 1025 | self.logger.exception('RDS Instance Statue Undefined') 1026 | return [] 1027 | except Exception as e: 1028 | self.logger.exception('General Exception ... {}'.format(e)) 1029 | return [] 1030 | 1031 | try: 1032 | DBInstanceIdentifier = base['DBInstanceIdentifier'] 1033 | except KeyError: 1034 | self.logger.exception('RDS Instance Id Undefined') 1035 | return [] 1036 | except Exception as e: 1037 | self.logger.exception('General Exception ... {}'.format(e)) 1038 | return [] 1039 | 1040 | try: 1041 | DBInstanceClass = base['DBInstanceClass'] 1042 | except KeyError: 1043 | self.logger.exception('RDS Instance Class Undefined') 1044 | return [] 1045 | except Exception as e: 1046 | self.logger.exception('General Exception ... {}'.format(e)) 1047 | return [] 1048 | 1049 | try: 1050 | DBEngine = base['Engine'] 1051 | except KeyError: 1052 | self.logger.error('RDS DB Engine Undefined') 1053 | DBEngine = 'Undefined' 1054 | except Exception as e: 1055 | self.logger.exception('General Exception ... {}'.format(e)) 1056 | return [] 1057 | 1058 | try: 1059 | DBName = base['DBName'] 1060 | except KeyError: 1061 | self.logger.info("RDS DB Name Undefined, setting to 'Undefined'") 1062 | DBName = 'Undefined' 1063 | except Exception as e: 1064 | self.logger.exception('General Exception ... {}'.format(e)) 1065 | return [] 1066 | if DBInstanceStatus == 'available': 1067 | try: 1068 | res = cwc.get_metric_statistics( 1069 | Namespace='AWS/RDS', 1070 | MetricName='CPUUtilization', 1071 | Dimensions=[ 1072 | { 1073 | 'Name': 'DBInstanceIdentifier', 1074 | 'Value': '{}'.format(DBInstanceIdentifier) 1075 | } 1076 | ], 1077 | StartTime=sTime, 1078 | EndTime=eTime, 1079 | Period=self.queryPeriod, 1080 | Statistics=[ 1081 | 'Average', 1082 | ], 1083 | Unit='Percent' 1084 | ) 1085 | for x in range(0, len(res['Datapoints'])): 1086 | metrics = [] 1087 | cwbase = res['Datapoints'][x] 1088 | Average = cwbase['Average'] 1089 | metrics.append(Average) 1090 | 1091 | totalAvg = round((sum(metrics)/len(metrics)), 2) 1092 | 1093 | # General Purpose DB Instance Types 1094 | 1095 | dbm4types = [ 1096 | 'large', 1097 | 'xlarge', 1098 | '2xlarge', 1099 | '4xlarge', 1100 | '10xlarge', 1101 | '16xlarge', 1102 | ] 1103 | 1104 | dbm3types = [ 1105 | 'medium', 1106 | 'large', 1107 | 'xlarge', 1108 | '2xlarge', 1109 | ] 1110 | 1111 | dbm1types = [ 1112 | 'small', 1113 | 'medium', 1114 | 'large', 1115 | 'xlarge', 1116 | ] 1117 | 1118 | # Memory Optimized DB Instance Types 1119 | 1120 | dbm2types = [ 1121 | 'xlarge', 1122 | '2xlarge', 1123 | '4xlarge', 1124 | ] 1125 | 1126 | dbr4types = [ 1127 | 'large', 1128 | 'xlarge', 1129 | '2xlarge', 1130 | '4xlarge', 1131 | '8xlarge', 1132 | '16xlarge', 1133 | ] 1134 | 1135 | dbr3types = [ 1136 | 'large', 1137 | 'xlarge', 1138 | '2xlarge', 1139 | '4xlarge', 1140 | '8xlarge', 1141 | ] 1142 | 1143 | dbx1etypes = [ 1144 | 'xlarge', 1145 | '2xlarge', 1146 | '4xlarge', 1147 | '8xlarge', 1148 | '16xlarge', 1149 | '32xlarge', 1150 | ] 1151 | 1152 | dbx1types = [ 1153 | '16xlarge', 1154 | '32xlarge', 1155 | ] 1156 | 1157 | # Burstable DB Instance Types 1158 | 1159 | dbt1types = [ 1160 | 'micro' 1161 | ] 1162 | 1163 | dbt2types = [ 1164 | 'micro', 1165 | 'small', 1166 | 'medium', 1167 | 'large', 1168 | 'xlarge', 1169 | '2xlarge', 1170 | ] 1171 | 1172 | typesplit = DBInstanceClass.split('.') 1173 | 1174 | # Suggest Instance Types based on AVG CPU usage keeping general instance type class 1175 | 1176 | if typesplit[1] == 't2': 1177 | typeindex = dbt2types.index('{}'.format(typesplit[2])) 1178 | if totalAvg <= 5: 1179 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbt2types[0]) 1180 | elif totalAvg > 5 <= 30: 1181 | index = typeindex - 1 1182 | if index < 0: 1183 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbt2types[0]) 1184 | else: 1185 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbt2types[index]) 1186 | elif totalAvg > 30 <= 80: 1187 | suggestedType = '{}'.format(DBInstanceClass) 1188 | elif totalAvg > 80: 1189 | try: 1190 | index = typeindex + 1 1191 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbt2types[index]) 1192 | except IndexError: 1193 | suggestedType = '{}.m4.{}'.format(typesplit[0], dbm4types[3]) 1194 | 1195 | elif typesplit[1] == 't1': # PrevGen Upgrade to t2 1196 | suggestedType = '{}.t2.{}*'.format(typesplit[0], dbt2types[0]) 1197 | 1198 | elif typesplit[1] == 'm4': 1199 | typeindex = dbm4types.index('{}'.format(typesplit[2])) 1200 | if totalAvg <= 5: 1201 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbm4types[0]) 1202 | elif totalAvg > 5 <= 30: 1203 | index = typeindex - 1 1204 | if index < 0: 1205 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbm4types[0]) 1206 | else: 1207 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbm4types[index]) 1208 | elif totalAvg > 30 <= 80: 1209 | suggestedType = '{}'.format(DBInstanceClass) 1210 | elif totalAvg > 80: 1211 | try: 1212 | index = typeindex + 1 1213 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbm4types[index]) 1214 | except IndexError: 1215 | suggestedType = '{}.x1e.{}'.format(typesplit[0], dbx1etypes[4]) 1216 | 1217 | elif typesplit[1] == 'm3': 1218 | typeindex = dbm3types.index('{}'.format(typesplit[2])) 1219 | if totalAvg <= 5: 1220 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbm3types[0]) 1221 | elif totalAvg > 5 <= 30: 1222 | index = typeindex - 1 1223 | if index < 0: 1224 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbm3types[0]) 1225 | else: 1226 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbm3types[index]) 1227 | elif totalAvg > 30 <= 80: 1228 | suggestedType = '{}'.format(DBInstanceClass) 1229 | elif totalAvg > 80: 1230 | try: 1231 | index = typeindex + 1 1232 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbm3types[index]) 1233 | except IndexError: 1234 | suggestedType = '{}.m4.{}'.format(typesplit[0], dbm4types[3]) 1235 | 1236 | elif typesplit[1] == 'm2': # PrevGen Upgrade to R3 1237 | typeindex = dbm2types.index('{}'.format(typesplit[2])) 1238 | if totalAvg <= 5: 1239 | suggestedType = '{}.r3.{}'.format(typesplit[0], dbr3types[0]) 1240 | elif totalAvg > 5 <= 30: 1241 | index = typeindex - 1 1242 | if index < 0: 1243 | suggestedType = '{}.r3.{}'.format(typesplit[0], dbr3types[0]) 1244 | else: 1245 | suggestedType = '{}.r3.{}'.format(typesplit[0], dbr3types[index]) 1246 | elif totalAvg > 30 <= 80: 1247 | index = typeindex 1248 | suggestedType = '{}.r3.{}'.format(typesplit[0], dbr3types[index]) 1249 | elif totalAvg > 80: 1250 | try: 1251 | index = typeindex + 1 1252 | suggestedType = '{}.r3.{}'.format(typesplit[0], dbr3types[index]) 1253 | except IndexError: 1254 | suggestedType = '{}.r3.{}'.format(typesplit[0], dbr3types[4]) 1255 | 1256 | elif typesplit[1] == 'm1': # PrevGen Upgrade to t2 1257 | typeindex = dbm1types.index('{}'.format(typesplit[2])) 1258 | if totalAvg <= 5: 1259 | suggestedType = '{}.t2.{}'.format(typesplit[0], dbt2types[0]) 1260 | elif totalAvg > 5 <= 30: 1261 | index = typeindex - 1 1262 | if index < 0: 1263 | suggestedType = '{}.t2.{}'.format(typesplit[0], dbt2types[0]) 1264 | else: 1265 | suggestedType = '{}.t2.{}'.format(typesplit[0], dbt2types[index]) 1266 | elif totalAvg > 30 <= 80: 1267 | index = typeindex + 1 1268 | suggestedType = '{}.t2.{}'.format(typesplit[0], dbt2types[index]) 1269 | elif totalAvg > 80: 1270 | try: 1271 | index = typeindex + 1 1272 | suggestedType = '{}.t2.{}'.format(typesplit[0], dbt2types[index]) 1273 | except IndexError: 1274 | suggestedType = '{}.t2.{}'.format(typesplit[0], dbt2types[3]) 1275 | 1276 | elif typesplit[1] == 'r4': 1277 | typeindex = dbr4types.index('{}'.format(typesplit[2])) 1278 | if totalAvg <= 5: 1279 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbr4types[0]) 1280 | elif totalAvg > 5 <= 30: 1281 | index = typeindex - 1 1282 | if index < 0: 1283 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbr4types[0]) 1284 | else: 1285 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbr4types[index]) 1286 | elif totalAvg > 30 <= 80: 1287 | suggestedType = '{}'.format(DBInstanceClass) 1288 | elif totalAvg > 80: 1289 | try: 1290 | index = typeindex + 1 1291 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbr4types[index]) 1292 | except IndexError: 1293 | suggestedType = '{}.x1e.{}'.format(typesplit[0], dbx1etypes[4]) 1294 | 1295 | elif typesplit[1] == 'r3': 1296 | typeindex = dbr3types.index('{}'.format(typesplit[2])) 1297 | if totalAvg <= 5: 1298 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbr3types[0]) 1299 | elif totalAvg > 5 <= 30: 1300 | index = typeindex - 1 1301 | if index < 0: 1302 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbr3types[0]) 1303 | else: 1304 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbr3types[index]) 1305 | elif totalAvg > 30 <= 80: 1306 | suggestedType = '{}'.format(DBInstanceClass) 1307 | elif totalAvg > 80: 1308 | try: 1309 | index = typeindex + 1 1310 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbr3types[index]) 1311 | except IndexError: 1312 | suggestedType = '{}.r4.{}'.format(typesplit[0], dbr4types[5]) 1313 | 1314 | elif typesplit[1] == 'x1e': 1315 | typeindex = dbx1etypes.index('{}'.format(typesplit[2])) 1316 | if totalAvg <= 5: 1317 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbx1etypes[0]) 1318 | elif totalAvg > 5 <= 30: 1319 | index = typeindex - 1 1320 | if index < 0: 1321 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbx1etypes[0]) 1322 | else: 1323 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbx1etypes[index]) 1324 | elif totalAvg > 30 <= 80: 1325 | suggestedType = '{}'.format(DBInstanceClass) 1326 | elif totalAvg > 80: 1327 | try: 1328 | index = typeindex + 1 1329 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbx1etypes[index]) 1330 | except IndexError: 1331 | suggestedType = '{}.x1e.{}'.format(typesplit[0], dbx1etypes[5]) 1332 | 1333 | elif typesplit[1] == 'x1': 1334 | typeindex = dbx1types.index('{}'.format(typesplit[2])) 1335 | if totalAvg <= 5: 1336 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbx1types[0]) 1337 | elif totalAvg > 5 <= 30: 1338 | index = typeindex -1 1339 | if index < 0: 1340 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbx1types[0]) 1341 | else: 1342 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbx1types[index]) 1343 | elif totalAvg > 30 <= 80: 1344 | suggestedType = '{}'.format(DBInstanceClass) 1345 | elif totalAvg > 80: 1346 | try: 1347 | index = typeindex + 1 1348 | suggestedType = '{}.{}.{}'.format(typesplit[0], typesplit[1], dbx1types[index]) 1349 | except IndexError: 1350 | suggestedType = '{}.x1e.{}'.format(typesplit[0], dbx1etypes[5]) 1351 | 1352 | except ClientError as e: 1353 | self.logger.error('Error getting metrics for instance {}...{}'.format(a, e)) 1354 | except Exception as e: 1355 | self.logger.exception('General Exception ... {}'.format(e)) 1356 | 1357 | info.append( 1358 | { 1359 | 'Id': '{}'.format(DBInstanceIdentifier), 1360 | 'Name': '{}'.format(DBName), 1361 | 'Engine': '{}'.format(DBEngine), 1362 | 'AvgCpu': totalAvg, 1363 | 'CurrentType': '{}'.format(DBInstanceClass), 1364 | 'SuggestedType': '{}'.format(suggestedType) 1365 | } 1366 | ) 1367 | 1368 | return info 1369 | -------------------------------------------------------------------------------- /src/rightsizer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gregory-Development/awsrightsizer/6c9cb993437e9dd45356bf283d80eefbaf83e0d4/src/rightsizer/__init__.py -------------------------------------------------------------------------------- /src/rightsizer/main.py: -------------------------------------------------------------------------------- 1 | # Standard Library Imports 2 | import csv 3 | import sys 4 | from logging import DEBUG, WARNING 5 | from datetime import datetime 6 | 7 | # Third-party Imports 8 | import click 9 | 10 | # Local Imports 11 | from .AwsRightSizer import Main 12 | 13 | 14 | def print_help(ctx, param, value): 15 | if value is False: 16 | return 17 | click.echo(ctx.get_help()) 18 | ctx.exit() 19 | 20 | @click.command() 21 | @click.option('--profile', '-p', 'profile', default='default', required=False, help='Your AWS Credentials Profile.') 22 | @click.option('--access-key', '-k', 'accessKey', default=None, required=False, help='Your AWS Access Key ID.') 23 | @click.option('--secret-key', '-s', 'secretKey', default=None, required=False, help='Your AWS Secret Access Key ID.') 24 | @click.option('--region', '-r', 'region', default=None, required=False, help='The AWS Region to query.') 25 | @click.option('--threshold', '-t', 'threshold', nargs=2, type=int, default=[5, 30], required=False, help='The Cloudwatch [average, max] CPU usage threshold.') 26 | @click.option('--query-config', '-q', 'query', nargs=2, type=int, default=[30, 1800], required=False, help='The amount of [days, period] to query Cloudwatch for.') 27 | @click.option('--output', '-o', 'output', default='report_()'.format(datetime.date(datetime.now())), help='The Name/Location of the file to output.') 28 | @click.option('--ec2-only', '-e', 'ec2only', is_flag=True) 29 | @click.option('--rds-only', '-d', 'rdsonly', is_flag=True) 30 | @click.option('--verbose', '-v', 'verbose', is_flag=True) 31 | @click.option('--help', '-h', is_flag=True, expose_value=False, is_eager=False, callback=print_help, help='Print help message') 32 | @click.pass_context 33 | def main(ctx, profile, accessKey, secretKey, region, threshold, query, output, ec2only, rdsonly, verbose): 34 | """ 35 | rightsizer takes user input and provides an output CSV of suggestions. 36 | """ 37 | if len(sys.argv) <= 1: 38 | print_help(ctx, None, value=True) 39 | 40 | if verbose: 41 | v = DEBUG 42 | else: 43 | v = WARNING 44 | 45 | x = Main( 46 | accessKey=accessKey, 47 | secretKey=secretKey, 48 | region=region, 49 | profile=profile, 50 | thresholdAvg=threshold[0], 51 | thresholdMax=threshold[1], 52 | queryDays=query[0], 53 | queryPeriod=query[1], 54 | output=output, 55 | verbose=v) 56 | 57 | if ec2only: 58 | 59 | if profile: 60 | pf = profile 61 | 62 | else: 63 | pf = region 64 | 65 | extra = { 66 | 'Id': '* - AWS Suggested Upgrade' 67 | } 68 | 69 | with open('{}_ec2_'+'{}'.format(pf, x.output), 'w', newline='') as f: 70 | 71 | fieldnames = [ 72 | 'Id', 73 | 'Name', 74 | 'AvgCpu', 75 | 'CurrentType', 76 | 'SuggestedType' 77 | ] 78 | 79 | w = csv.DictWriter(f, fieldnames) 80 | 81 | w.writeheader() 82 | 83 | for r in x.getec2suggestions(): 84 | 85 | w.writerow(r) 86 | 87 | csv.writer(f).writerow('') 88 | 89 | w.writerow(extra) 90 | 91 | elif rdsonly: 92 | 93 | if profile: 94 | 95 | pf = profile 96 | 97 | else: 98 | 99 | pf = region 100 | 101 | extra = { 102 | 'Id': '* - AWS Suggested Upgrade' 103 | } 104 | 105 | with open('{}_rds_'+'{}'.format(pf, x.output), 'w', newline='') as f: 106 | 107 | fieldnames = [ 108 | 'Id', 109 | 'Name', 110 | 'Engine', 111 | 'AvgCpu', 112 | 'CurrentType', 113 | 'SuggestedType' 114 | ] 115 | 116 | w = csv.DictWriter(f, fieldnames) 117 | 118 | w.writeheader() 119 | 120 | for r in x.getrdssuggestions(): 121 | 122 | w.writerow(r) 123 | 124 | csv.writer(f).writerow('') 125 | 126 | w.writerow(extra) 127 | 128 | else: 129 | 130 | if profile: 131 | 132 | pf = profile 133 | 134 | else: 135 | 136 | pf = region 137 | 138 | extra = { 139 | 'Id': '* - AWS Suggested Upgrade' 140 | } 141 | 142 | with open('{}_ec2_' + '{}'.format(pf, x.output), 'w', newline='') as f: 143 | 144 | fieldnames = [ 145 | 'Id', 146 | 'Name', 147 | 'AvgCpu', 148 | 'CurrentType', 149 | 'SuggestedType' 150 | ] 151 | 152 | w = csv.DictWriter(f, fieldnames) 153 | 154 | w.writeheader() 155 | 156 | for r in x.getec2suggestions(): 157 | 158 | w.writerow(r) 159 | 160 | csv.writer(f).writerow('') 161 | 162 | w.writerow(extra) 163 | 164 | with open('{}_rds_' + '{}'.format(pf, x.output), 'w', newline='') as f: 165 | 166 | fieldnames = [ 167 | 'Id', 168 | 'Name', 169 | 'Engine', 170 | 'AvgCpu', 171 | 'CurrentType', 172 | 'SuggestedType' 173 | ] 174 | 175 | w = csv.DictWriter(f, fieldnames) 176 | 177 | w.writeheader() 178 | 179 | for r in x.getrdssuggestions(): 180 | 181 | w.writerow(r) 182 | 183 | csv.writer(f).writerow('') 184 | 185 | w.writerow(extra) -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gregory-Development/awsrightsizer/6c9cb993437e9dd45356bf283d80eefbaf83e0d4/tests/__init__.py --------------------------------------------------------------------------------