├── .github └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── NOTICE ├── README.md ├── event.json ├── ri_expiration_notification_design_serverless.png ├── ri_expiration_notification_design_serverless_deploymodel.png ├── src ├── requirements.txt └── ri_expiration.py ├── template.yaml └── tests └── unit └── __init__.py /.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 you can use, modify, copy, and redistribute this contribution, under the terms of your choice. 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode 3 | 4 | ### Linux ### 5 | *~ 6 | 7 | # temporary files which can be created if a process still has a handle open of a deleted file 8 | .fuse_hidden* 9 | 10 | # KDE directory preferences 11 | .directory 12 | 13 | # Linux trash folder which might appear on any partition or disk 14 | .Trash-* 15 | 16 | # .nfs files are created when an open file is removed but is still being accessed 17 | .nfs* 18 | 19 | ### OSX ### 20 | *.DS_Store 21 | .AppleDouble 22 | .LSOverride 23 | 24 | # Icon must end with two \r 25 | Icon 26 | 27 | # Thumbnails 28 | ._* 29 | 30 | # Files that might appear in the root of a volume 31 | .DocumentRevisions-V100 32 | .fseventsd 33 | .Spotlight-V100 34 | .TemporaryItems 35 | .Trashes 36 | .VolumeIcon.icns 37 | .com.apple.timemachine.donotpresent 38 | 39 | # Directories potentially created on remote AFP share 40 | .AppleDB 41 | .AppleDesktop 42 | Network Trash Folder 43 | Temporary Items 44 | .apdisk 45 | 46 | ### PyCharm ### 47 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 48 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 49 | 50 | # User-specific stuff: 51 | .idea/* 52 | .idea/**/workspace.xml 53 | .idea/**/tasks.xml 54 | .idea/dictionaries 55 | 56 | # Sensitive or high-churn files: 57 | .idea/**/dataSources/ 58 | .idea/**/dataSources.ids 59 | .idea/**/dataSources.xml 60 | .idea/**/dataSources.local.xml 61 | .idea/**/sqlDataSources.xml 62 | .idea/**/dynamic.xml 63 | .idea/**/uiDesigner.xml 64 | 65 | # Gradle: 66 | .idea/**/gradle.xml 67 | .idea/**/libraries 68 | 69 | # CMake 70 | cmake-build-debug/ 71 | 72 | # Mongo Explorer plugin: 73 | .idea/**/mongoSettings.xml 74 | 75 | ## File-based project format: 76 | *.iws 77 | 78 | ## Plugin-specific files: 79 | 80 | # IntelliJ 81 | /out/ 82 | 83 | # mpeltonen/sbt-idea plugin 84 | .idea_modules/ 85 | 86 | # JIRA plugin 87 | atlassian-ide-plugin.xml 88 | 89 | # Cursive Clojure plugin 90 | .idea/replstate.xml 91 | 92 | # Ruby plugin and RubyMine 93 | /.rakeTasks 94 | 95 | # Crashlytics plugin (for Android Studio and IntelliJ) 96 | com_crashlytics_export_strings.xml 97 | crashlytics.properties 98 | crashlytics-build.properties 99 | fabric.properties 100 | 101 | ### PyCharm Patch ### 102 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 103 | 104 | # *.iml 105 | # modules.xml 106 | # .idea/misc.xml 107 | # *.ipr 108 | 109 | # Sonarlint plugin 110 | .idea/sonarlint 111 | 112 | ### Python ### 113 | # Byte-compiled / optimized / DLL files 114 | __pycache__/ 115 | *.py[cod] 116 | *$py.class 117 | 118 | # C extensions 119 | *.so 120 | 121 | # Distribution / packaging 122 | .Python 123 | build/ 124 | develop-eggs/ 125 | dist/ 126 | downloads/ 127 | eggs/ 128 | .eggs/ 129 | lib/ 130 | lib64/ 131 | parts/ 132 | sdist/ 133 | var/ 134 | wheels/ 135 | *.egg-info/ 136 | .installed.cfg 137 | *.egg 138 | 139 | # PyInstaller 140 | # Usually these files are written by a python script from a template 141 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 142 | *.manifest 143 | *.spec 144 | 145 | # Installer logs 146 | pip-log.txt 147 | pip-delete-this-directory.txt 148 | 149 | # Unit test / coverage reports 150 | htmlcov/ 151 | .tox/ 152 | .coverage 153 | .coverage.* 154 | .cache 155 | .pytest_cache/ 156 | nosetests.xml 157 | coverage.xml 158 | *.cover 159 | .hypothesis/ 160 | 161 | # Translations 162 | *.mo 163 | *.pot 164 | 165 | # Flask stuff: 166 | instance/ 167 | .webassets-cache 168 | 169 | # Scrapy stuff: 170 | .scrapy 171 | 172 | # Sphinx documentation 173 | docs/_build/ 174 | 175 | # PyBuilder 176 | target/ 177 | 178 | # Jupyter Notebook 179 | .ipynb_checkpoints 180 | 181 | # pyenv 182 | .python-version 183 | 184 | # celery beat schedule file 185 | celerybeat-schedule.* 186 | 187 | # SageMath parsed files 188 | *.sage.py 189 | 190 | # Environments 191 | .env 192 | .venv 193 | env/ 194 | venv/ 195 | ENV/ 196 | env.bak/ 197 | venv.bak/ 198 | 199 | # Spyder project settings 200 | .spyderproject 201 | .spyproject 202 | 203 | # Rope project settings 204 | .ropeproject 205 | 206 | # mkdocs documentation 207 | /site 208 | 209 | # mypy 210 | .mypy_cache/ 211 | 212 | ### VisualStudioCode ### 213 | .vscode/* 214 | !.vscode/settings.json 215 | !.vscode/tasks.json 216 | !.vscode/launch.json 217 | !.vscode/extensions.json 218 | .history 219 | 220 | ### Windows ### 221 | # Windows thumbnail cache files 222 | Thumbs.db 223 | ehthumbs.db 224 | ehthumbs_vista.db 225 | 226 | # Folder config file 227 | Desktop.ini 228 | 229 | # Recycle Bin used on file shares 230 | $RECYCLE.BIN/ 231 | 232 | # Windows Installer files 233 | *.cab 234 | *.msi 235 | *.msm 236 | *.msp 237 | 238 | # Windows shortcuts 239 | *.lnk 240 | 241 | # Build folder 242 | 243 | */build/* 244 | 245 | # End of https://www.gitignore.io/api/osx,linux,python,windows,pycharm,visualstudiocode 246 | -------------------------------------------------------------------------------- /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/awslabs/aws-reserved-instance-expiration-notification/issues), or [recently closed](https://github.com/awslabs/aws-reserved-instance-expiration-notification/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/awslabs/aws-reserved-instance-expiration-notification/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/awslabs/aws-reserved-instance-expiration-notification/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 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | AWS Reserved Instance Expiration Notification 2 | Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-reserved-instance-expiration-notification 2 | 3 | Python SAM Lambda module for sending email about AWS Reserved Instance whose contract is expiring in 30 days. 4 | 5 | This is a sample template for aws-reserved-instance-expiration-notification. Below is a brief explanation of what we have generated for you: 6 | 7 | ```bash 8 | . 9 | ├── README.md <-- This instructions file 10 | ├── event.json <-- API Gateway Proxy Integration event payload 11 | ├── src <-- Source code for a lambda function 12 | │   ├── ri_expiration.py <-- Lambda function code 13 | │   ├── requirements.txt <-- python library 14 | ├── template.yaml <-- SAM Template 15 | └── tests <-- Unit tests 16 | └── unit 17 | ├── __init__.py 18 | └── test_handler.py 19 | ``` 20 | 21 | ## Requirements 22 | 23 | * AWS CLI already configured with Administrator permission 24 | * [AWS Serverless Application Model installed](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) 25 | * [Docker installed](https://www.docker.com/community-edition) 26 | * [Python 3 installed](https://www.python.org/downloads/) 27 | * [Pandas](https://pandas.pydata.org/) 28 | 29 | ## How to build 30 | 31 | Python SAM Lambda module for sending email about AWS Reserved Instance whose contract is expiring in 30 days. 32 | The monitored services are Amazon EC2, Amazon ElastiCache, Amazon RDS, and Elasticsearch Service. 33 | 34 | ![screenshot](ri_expiration_notification_design_serverless.png) 35 | 36 | Download the source code by using git. 37 | 38 | ```bash 39 | git clone https://github.com/awslabs/aws-reserved-instance-expiration-notification.git 40 | cd aws-reserved-instance-expiration-notification 41 | ``` 42 | 43 | In this instruction, we are going to build reserved instance notification system in Seoul region (ap-northeast-2). 44 | 45 | ```bash 46 | aws configure set default.region ap-northeast-2 47 | ``` 48 | 49 | Replace the sender's email address. You will need to verify this email address via SES later. 50 | 51 | ```python 52 | SENDER = "USER_NAME " 53 | ``` 54 | 55 | Use this command to build the Lambda source code, DynamoDB and generate deployment artifacts that target Lambda's execution environment. 56 | 57 | ```bash 58 | sam build 59 | ``` 60 | 61 | Create an S3 bucket in the location where you want to save the packaged code. If you want to use an existing S3 bucket, skip this step. 62 | 63 | ```bash 64 | Date=$(date +'%d%m%Y-%H%M%S') 65 | aws s3 mb s3://aws-reserved-instance-expiration-notification-$Date 66 | ``` 67 | 68 | Create the Lambda function deployment package by running the following package AWS SAM CLI command at the command prompt. 69 | 70 | ```bash 71 | sam package \ 72 | --template-file .aws-sam/build/template.yaml \ 73 | --output-template-file packaged.yaml \ 74 | --s3-bucket aws-reserved-instance-expiration-notification-$Date 75 | ``` 76 | 77 | In the AWS SAM CLI, use the deploy command to deploy all of the resources that you defined in the template. 78 | 79 | ```bash 80 | sam deploy \ 81 | --template-file packaged.yaml \ 82 | --stack-name ri-exp-app \ 83 | --capabilities CAPABILITY_IAM \ 84 | --region ap-northeast-2 85 | ``` 86 | 87 | Go to [AWS Lambda Console](https://ap-northeast-2.console.aws.amazon.com/lambda), you can see a Lambda Function like "%RIExpNotificationLambdaFunction%" 88 | 89 | ## How to Use 90 | 91 | You can put email addresses into DynamoDB table. 92 | 93 | ```bash 94 | aws dynamodb put-item \ 95 | --table-name ri_exp_mailing \ 96 | --item '{"email":{"S":"user@example.com"}}' 97 | ``` 98 | 99 | Before you can send an email using Amazon SES, you must verify the address or domain that you are sending the email from to prove that you own it. If you do not have production access yet, you also need to verify any email addresses that you send emails to except for email addresses provided by the Amazon SES mailbox simulator. 100 | 101 | ```bash 102 | # we are going to use Amazon SES in N. Virginia. 103 | aws configure set default.region us-east-1 104 | aws ses verify-email-identity --email-address "user@example.com" 105 | ``` 106 | 107 | ## Configuration 108 | 109 | If you want to customize configurations, you can change the values in template.yaml. 110 | 111 | For example, you can change the schedule invoking the Lambda function in **Events** phrase of template.yaml. 112 | 113 | ```yaml 114 | Events: 115 | Schedule1: 116 | Type: Schedule 117 | Properties: 118 | Schedule: cron(0 8 1 * ? *) 119 | ``` 120 | 121 | ## License 122 | 123 | This library is licensed under the Apache 2.0 License. 124 | -------------------------------------------------------------------------------- /event.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /ri_expiration_notification_design_serverless.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-reserved-instance-expiration-notification/018c37f7d547937f6390b5184756d199338ba7d6/ri_expiration_notification_design_serverless.png -------------------------------------------------------------------------------- /ri_expiration_notification_design_serverless_deploymodel.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-reserved-instance-expiration-notification/018c37f7d547937f6390b5184756d199338ba7d6/ri_expiration_notification_design_serverless_deploymodel.png -------------------------------------------------------------------------------- /src/requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | pandas 3 | openpyxl 4 | jinja2 5 | -------------------------------------------------------------------------------- /src/ri_expiration.py: -------------------------------------------------------------------------------- 1 | # Copyright <2019> Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | import json 5 | import boto3 6 | from botocore.exceptions import ClientError 7 | from multiprocessing import Process 8 | from dateutil import relativedelta 9 | from datetime import date, datetime, timedelta 10 | import numpy as np 11 | import pandas as pd 12 | import os 13 | 14 | from email.mime.text import MIMEText 15 | from email.mime.application import MIMEApplication 16 | from email.mime.multipart import MIMEMultipart 17 | 18 | TARGET_REGION = 'ap-northeast-2' 19 | SES_REGION = 'us-east-1' 20 | SENDER = "blah " 21 | 22 | def send_email(info): 23 | RECIPIENT = info['email'] 24 | attachments = info['attach'] 25 | BODY_HTML = info['msg'] 26 | 27 | message = MIMEMultipart() 28 | message['Subject'] = 'Amazon RI Expiration Notification' 29 | message['From'] = SENDER 30 | message['To'] = RECIPIENT 31 | destinations = [] 32 | destinations.append(RECIPIENT) 33 | 34 | # message body 35 | part = MIMEText(BODY_HTML, 'html') 36 | message.attach(part) 37 | 38 | # attachment 39 | for attachment in attachments: 40 | with open(attachment, 'rb') as f: 41 | part = MIMEApplication(f.read()) 42 | part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment)) 43 | message.attach(part) 44 | 45 | client = boto3.client('ses', region_name=SES_REGION) 46 | response = client.send_raw_email( 47 | Source=message['From'], 48 | Destinations=destinations, 49 | RawMessage={ 50 | 'Data': message.as_string() 51 | } 52 | ) 53 | 54 | 55 | def getExpRIList(response: boto3.resources.response, response_name, filter_name, filter_value, select_column=[]): 56 | if len(response[response_name]) > 0: 57 | print("Exist " + response_name) 58 | 59 | next_month = np.datetime64(datetime.utcnow() + relativedelta.relativedelta(days=31)) 60 | ri_list = list(map(lambda a: a.values(), filter(lambda a: a[filter_name] == filter_value, response[response_name]))) 61 | head = response[response_name][0].keys() 62 | df = pd.DataFrame(ri_list, columns=head) 63 | df['StartTime'] = pd.to_datetime(df['StartTime']).dt.tz_convert(None) 64 | df['End'] = df['StartTime'] + pd.to_timedelta(df['Duration'], 's') 65 | will_expire = df[df['End'] <= next_month] 66 | filtered_list = will_expire[select_column].values.tolist() 67 | return filtered_list, will_expire[select_column].columns.to_list(), df 68 | 69 | 70 | def to_excel(df, filename, condition): 71 | writer = pd.ExcelWriter(filename) 72 | row_style = lambda row: pd.Series('background-color: {}'.format('yellow' if condition(row) else 'green'), row.index) 73 | df.style.apply(row_style, axis=1).to_excel(writer, ) 74 | writer.save() 75 | writer.close() 76 | 77 | 78 | def makeMessage(): 79 | # df 80 | next_month = np.datetime64(datetime.utcnow() + relativedelta.relativedelta(days=31)) 81 | 82 | # ec2 83 | ec2_client = boto3.client('ec2', region_name=TARGET_REGION) 84 | ec2_response = ec2_client.describe_reserved_instances(Filters=[{'Name': 'state', 'Values': ['active']}]) 85 | if len(ec2_response['ReservedInstances']) > 0: 86 | print("Exist EC2 Reserved Instance") 87 | 88 | ec2_ri_list = list(map(lambda a: a.values(), ec2_response['ReservedInstances'])) 89 | ec2_head = ec2_response['ReservedInstances'][0].keys() 90 | ec2_df = pd.DataFrame(ec2_ri_list, columns=ec2_head) 91 | ec2_df['Start'] = pd.to_datetime(ec2_df['Start']).dt.tz_convert(None) 92 | ec2_df['End'] = pd.to_datetime(ec2_df['End']).dt.tz_convert(None) 93 | ec2_will_expire = ec2_df[ec2_df['End'] <= next_month] 94 | select_column = ['ReservedInstancesId', 'Start', 'State', 'End', 'InstanceType', 'InstanceCount'] 95 | ec2_head2 = ec2_will_expire[select_column].columns.to_list() 96 | ec2_filtered_list = ec2_will_expire[select_column].values.tolist() 97 | 98 | # rds 99 | rds_client = boto3.client('rds', region_name=TARGET_REGION) 100 | rds_filtered_list, rds_head, rds_df = getExpRIList(rds_client.describe_reserved_db_instances(), 101 | 'ReservedDBInstances', 102 | 'State', 103 | 'active', 104 | ['ReservedDBInstanceId', 'StartTime', 'State', 'End', 'DBInstanceClass', 105 | 'DBInstanceCount']) 106 | 107 | # redshift 108 | red_client = boto3.client('redshift', region_name=TARGET_REGION) 109 | red_filtered_list, red_head, red_df = getExpRIList(red_client.describe_reserved_nodes(), 110 | 'ReservedNodes', 111 | 'State', 112 | 'active', 113 | ['ReservedNodeId', 'StartTime', 'State', 'End', 'NodeType', 'NodeCount']) 114 | 115 | # elasticache 116 | ec_client = boto3.client('elasticache', region_name=TARGET_REGION) 117 | ec_filtered_list, ec_head, ec_df = getExpRIList(ec_client.describe_reserved_cache_nodes(), 118 | 'ReservedCacheNodes', 119 | 'State', 120 | 'active', 121 | ['ReservedCacheNodeId', 'StartTime', 'State', 'End', 'CacheNodeType', 122 | 'CacheNodeCount']) 123 | 124 | # elasticsearch 125 | es_client = boto3.client('es', region_name=TARGET_REGION) 126 | es_filtered_list, es_head, es_df = getExpRIList(es_client.describe_reserved_elasticsearch_instances(), 127 | 'ReservedElasticsearchInstances', 128 | 'State', 129 | 'active', 130 | ['ReservationName', 'ReservedElasticsearchInstanceId', 'StartTime', 131 | 'State', 'End', 'ElasticsearchInstanceType', 132 | 'ElasticsearchInstanceCount']) 133 | 134 | to_excel(ec2_df, '/tmp/ec2_df.xlsx', lambda df: df['End'] <= next_month) 135 | to_excel(rds_df, '/tmp/rds_df.xlsx', lambda df: df['End'] <= next_month) 136 | to_excel(red_df, '/tmp/red_df.xlsx', lambda df: df['End'] <= next_month) 137 | to_excel(ec_df, '/tmp/ec_df.xlsx', lambda df: df['End'] <= next_month) 138 | to_excel(es_df, '/tmp/es_df.xlsx', lambda df: df['End'] <= next_month) 139 | 140 | html = "\ 141 | \ 142 | \ 143 | RI Status\ 144 | \ 156 | \ 157 | " +\ 158 | getHTMLTable("EC2", ec2_head2, ec2_filtered_list) + \ 159 | getHTMLTable("RDS", rds_head, rds_filtered_list) + \ 160 | getHTMLTable("Redshift", red_head, red_filtered_list) + \ 161 | getHTMLTable("ElastiCache", ec_head, ec_filtered_list) + \ 162 | getHTMLTable("ElasticSearch", es_head, es_filtered_list) + \ 163 | "" 164 | return html 165 | 166 | 167 | def getHTMLTable(table_name, header, rows): 168 | html_middle = "

{}

{}
" 169 | table_head, table = "", "" 170 | table_items = [] 171 | end_column = -1 172 | for index, head in enumerate(header): 173 | if head == "End": 174 | table_head += "{}".format(head) 175 | end_column = index 176 | else: 177 | table_head += "{}".format(head) 178 | table_items.append(table_head) 179 | for row in rows: 180 | table_row = "" 181 | for index, item in enumerate(row): 182 | if index == end_column: 183 | table_row += "{}".format(item) 184 | else: 185 | table_row += "{}".format(item) 186 | table_items.append(table_row) 187 | for row in table_items: 188 | table += "{}".format(row) 189 | table = html_middle.format(table_name, table) 190 | return table 191 | 192 | 193 | def save_msg_to_s3(msg, bucket, obj): 194 | s3 = boto3.client('s3') 195 | s3.put_object(Body=msg, Bucket=bucket, Key=obj+"ri_exp.html") 196 | 197 | 198 | def lambda_handler(event, context): 199 | # TODO implement 200 | dn_client = boto3.client('dynamodb', region_name=TARGET_REGION) 201 | dn_response = dn_client.scan(TableName='ri_exp_mailing') 202 | email_list = list(map(lambda a: a['email']['S'], dn_response['Items'])) 203 | 204 | # if there is an email address validation in SES, send a validation email. 205 | ses_client = boto3.client('ses', region_name=SES_REGION) 206 | ses_list = list(filter(lambda a: '.com' in a, ses_client.list_identities()['Identities'])) 207 | for i in email_list: 208 | if i not in ses_list: 209 | try: 210 | response = ses_client.verify_email_address(EmailAddress=i) 211 | except ClientError as e: 212 | print(e.response['Error']['Message']) 213 | else: 214 | print("Validation Email sent! Message ID:"), 215 | print(response['MessageId']) 216 | 217 | msg = makeMessage() 218 | save_msg_to_s3(msg, "ri-exp-contents", datetime.today().strftime("%Y/%m/")) 219 | attach = ['/tmp/ec2_df.xlsx', '/tmp/rds_df.xlsx', '/tmp/red_df.xlsx', '/tmp/ec_df.xlsx', '/tmp/es_df.xlsx'] 220 | infos = list(map(lambda a: {'email': a, 'msg': msg, 'attach': attach}, email_list)) 221 | 222 | procs = [] 223 | for info in infos: 224 | p = Process(target=send_email, args=(info,)) 225 | procs.append(p) 226 | p.start() 227 | 228 | for p in procs: 229 | p.join() 230 | 231 | return { 232 | 'statusCode': 200, 233 | 'body': json.dumps("success", indent=4, sort_keys=True, default=str) 234 | } 235 | -------------------------------------------------------------------------------- /template.yaml: -------------------------------------------------------------------------------- 1 | # Copyright <2019> Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 | # SPDX-License-Identifier: Apache-2.0 3 | 4 | AWSTemplateFormatVersion: '2010-09-09' 5 | Transform: 'AWS::Serverless-2016-10-31' 6 | Description: An AWS Serverless Specification template describing your function. 7 | Resources: 8 | RIExpNotificationLambdaFunction: 9 | Type: 'AWS::Serverless::Function' 10 | Properties: 11 | Handler: ri_expiration.lambda_handler 12 | Runtime: python3.6 13 | CodeUri: ./src/ 14 | Description: '' 15 | MemorySize: 512 16 | Timeout: 120 17 | Role: !GetAtt LambdaReadOnlyExecutionRole.Arn 18 | Events: 19 | Schedule1: 20 | Type: Schedule 21 | Properties: 22 | Schedule: cron(0 8 1 * ? *) 23 | 24 | DynamoDBTable: 25 | Type: 'AWS::DynamoDB::Table' 26 | Properties: 27 | AttributeDefinitions: 28 | - 29 | AttributeName: 'email' 30 | AttributeType: 'S' 31 | KeySchema: 32 | - 33 | AttributeName: "email" 34 | KeyType: "HASH" 35 | TableName: "ri_exp_mailing" 36 | ProvisionedThroughput: 37 | ReadCapacityUnits: "5" 38 | WriteCapacityUnits: "5" 39 | 40 | LambdaReadOnlyExecutionRole: 41 | Type: 'AWS::IAM::Role' 42 | Properties: 43 | ManagedPolicyArns: 44 | - "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" 45 | - "arn:aws:iam::aws:policy/AmazonS3FullAccess" 46 | - "arn:aws:iam::aws:policy/AmazonRedshiftReadOnlyAccess" 47 | - "arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess" 48 | - "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" 49 | - "arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess" 50 | - "arn:aws:iam::aws:policy/AmazonSESFullAccess" 51 | - "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess" 52 | Policies: 53 | - 54 | PolicyName: "ElasticsearchReadOnlyAccess" 55 | PolicyDocument: 56 | Version: "2012-10-17" 57 | Statement: 58 | - #Policy to allow Organizations account description 59 | Effect: "Allow" 60 | Action: 61 | - "es:DescribeReservedElasticsearchInstances" 62 | - "es:ESHttpHead" 63 | - "es:DescribeElaticsearchDomain" 64 | - "es:ESHttpGet" 65 | - "es:ListTags" 66 | - "es:GetUpgradeStatus" 67 | - "es:DescribeElasticsearchDomainConfig" 68 | - "es:GetUpgradeHistory" 69 | Resource: "*" 70 | 71 | AssumeRolePolicyDocument: 72 | Version: "2012-10-17" 73 | Statement: 74 | - 75 | Sid: "AllowLambdaServiceToAssumeRole" 76 | Effect: "Allow" 77 | Action: 78 | - "sts:AssumeRole" 79 | Principal: 80 | Service: 81 | - "lambda.amazonaws.com" 82 | -------------------------------------------------------------------------------- /tests/unit/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/awslabs/aws-reserved-instance-expiration-notification/018c37f7d547937f6390b5184756d199338ba7d6/tests/unit/__init__.py --------------------------------------------------------------------------------