diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0c2dc01 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +# Add any directories, files, or patterns you don't want to be tracked by version control. +.git +.terraform +terraform/.terraform* +terraform.tfstate.d +.env +.idea +tf-plan* diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4383e6d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,12 @@ +# Changelog + +All notable changes to this project will be documented in this file. + + +## [1.0.0] - 2024-01-15 + +[1.0.0]: https://github.com/abdullahkhawer/mongodb-cluster-on-aws-ecs/releases/tag/v1.0.0 + +### Features + +- [**breaking**] Develop a Terraform Module for MongoDB to run it on AWS ECS to create a multi-node MongoDB cluster under AWS Auto Scaling group to launch multiple MongoDB nodes as replicas with AWS ECS service registry using awsvpc as network mode, persistent and encrypted AWS EBS volumes of type gp3, AWS S3 bucket for backups storage along with lifecycle rules for data archival and deletion and User Data script to prepare an AWS EC2 instance by setting up wget, unzip, awscli, Docker, ECS agent, rexray/ebs Docker plugin, MongoDB, Mongosh, MongoDB database tools, MongoDB backup and restore scripts, key file for MongoDB Cluster, custom agent for AWS EBS volumes disk usage monitoring, cronjobs for backup at 03:00 AM daily and disk usage monitoring at every minute, soft rlimits and ulimits and disabling transparent huge pages on it and also creating DNS record in AWS Route 53 hosted zone for it. Also, update README accordingly. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index d7fc32c..4527668 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,80 @@ -# mongodb-cluster-on-aws-ecs -Terraform module to deploy a highly available and self healing MongoDB cluster on AWS ECS cluster. +# MongoDB cluster on AWS ECS + +- Founder: Abdullah Khawer (LinkedIn: https://www.linkedin.com/in/abdullah-khawer/) + +## Introduction + +A Terraform module developed to quickly deploy a secure, persistent, highly available, self healing, efficient and cost effective single-node or multi-node MongoDB NoSQL document database cluster on AWS ECS cluster as there is no managed service available for MongoDB on AWS with such features. + +## Key Highlights + +- A single-node or multi-node MongoDB cluster under AWS Auto Scaling group to launch multiple MongoDB nodes as replicas to make it highly available, efficient and self healing with a help of bootstrapping script with some customizations. +- Using AWS ECS service registry with awsvpc as network mode instead of AWS ELB to save cost on networking side and make it more secure. AWS ECS task IPs are updated by the bootstrapping script on an AWS Route 53 hosted zone. +- Persistent and encrypted AWS EBS volumes of type gp3 using rexray/ebs Docker plugin so the data stays secure and reliable. +- AWS S3 bucket for backups storage for disaster recovery along with lifecycle rules for data archival and deletion. +- Custom backup and restore scripts for data migration and disaster recovery capabilities available on each AWS EC2 instance due to a bootstrapping script. +- Each AWS EC2 instance is configured with various customizations like pre-installed wget, unzip, awscli, Docker, ECS agent, MongoDB, Mongosh, MongoDB database tools, key file for MongoDB Cluster, custom agent for AWS EBS volumes disk usage monitoring and cronjobs to take a backup at 03:00 AM daily and to send disk usage metrics to AWS CloudWatch at every minute. +- Each AWS EC2 instance is configured with soft rlimits and ulimits defined and transparent huge pages disabled to make MongoDB database more efficient. + +## Usage Notes + +### Prerequisites + +Following are the resources that should exist already before starting the deployment: + +- 1 secure parameter named `/docker/[ENVIRONMENT_NAME]/MONGODB_USERNAME` under **AWS SSM Parameter Store** having username of MongoDB cluster. +- 1 secure parameter named `/docker/[ENVIRONMENT_NAME]/MONGODB_PASSWORD` under **AWS SSM Parameter Store** having password of MongoDB cluster. +- 1 secure parameter named `/docker/[ENVIRONMENT_NAME]/MONGODB_KEYFILE` under **AWS SSM Parameter Store** having contents of a keyfile created locally with the following commands for MongoDB cluster: + - `openssl rand -base64 756 > mongodb.key` + - `chmod 400 mongodb.key` +- 1 key pair named `[PROJECT]-[ENVIRONMENT_NAME]-mongodb` under **AWS EC2 Key Pairs**. +- 1 private hosted zone under **AWS Route53** with any working domain. +- 1 vpc under **AWS VPC** having at least 1 private subnet or ideally, 3 private and 3 public subnets with name tags (e.g., Private-1-Subnet, Private-2-Subnet, etc). + +## Deployment Instructions + +Simply deploy it from the terraform directory directly or either as a Terraform module by specifying the desired values for the variables. You can check `terraform-usage-example.tf` file as an example. + +## Post Deployment Replica Set Configuration + +Once the deployment is done, log into the MongoDB cluster via its 1st AWS EC2 instance node using AWS SSM Session Manager using the following command: `mongosh "mongodb://[USERNAME]:[PASSWORD]@mongodb1.[ENVIRONMENT_NAME]-local:27017/admin?&retryWrites=false"` + +Then initiate the replica set using the following command: + +``` +rs.initiate({ +_id: "rs0", +members: [ + { _id: 0, host: "mongodb1.[ENVIRONMENT_NAME]-local:27017" }, + { _id: 1, host: "mongodb2.[ENVIRONMENT_NAME]-local:27017" }, + { _id: 2, host: "mongodb3.[ENVIRONMENT_NAME]-local:27017" } +] +}) +``` + +You can now connect to the replica set using the following command: `mongosh "mongodb://[USERNAME]:[PASSWORD]@mongodb1.[ENVIRONMENT_NAME]-local:27017,mongodb2.[ENVIRONMENT_NAME]-local:27017,mongodb3.[ENVIRONMENT_NAME]-local:27017/admin?replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=true"` + +*Note: The sample commands in the above example assumes that the cluster has 3 nodes.* + +## Replica Set Recovery + +If you lost the replica set, you can reconfigure it using the following commands: + +``` +rs.reconfig({ +_id: "rs0", +members: [ + { _id: 0, host: "mongodb1.stage-local:27017" } +] +}, {"force":true}) + +rs.add({ _id: 1, host: "mongodb2.stage-local:27017" }) + +rs.add({ _id: 2, host: "mongodb3.stage-local:27017" }) +``` + +*Note: The sample commands in the above example assumes that the cluster has 3 nodes.* + +#### Warning: You will be billed for the AWS resources created by this framework. + +##### Any contributions, improvements and suggestions will be highly appreciated. 😊 diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..0ec25f7 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +v1.0.0 diff --git a/cliff.toml b/cliff.toml new file mode 100644 index 0000000..077b8f9 --- /dev/null +++ b/cliff.toml @@ -0,0 +1,66 @@ +# configuration file for git-cliff (0.1.0) + +[changelog] +# changelog header +header = """ +# Changelog\n +All notable changes to this project will be documented in this file.\n +""" +# template for the changelog body +# https://tera.netlify.app/docs/#introduction +body = """ +{% set github_project_url = "https://github.com/abdullahkhawer/mongodb-cluster-on-aws-ecs/releases" %} +{% if version %}\ + ## [{{ version | trim_start_matches(pat="v") }}] - {{ timestamp | date(format="%Y-%m-%d") }}\n + [{{ version | trim_start_matches(pat="v") }}]: {{ github_project_url }}/tag/{{ version }} +{% else %}\ + ## [unreleased]\n + [unreleased]: {{ github_project_url }}/-/blob/master/CHANGELOG.md +{% endif %}\ +{% for group, commits in commits | group_by(attribute="group") %} + ### {{ group | upper_first }} + {% for commit in commits %} + - {% if commit.breaking %}[**breaking**] {% endif %}{{ commit.message | upper_first }}\ + {% endfor %} +{% endfor %} +""" +# remove the leading and trailing whitespace from the template +trim = true + +[git] +# parse the commits based on https://www.conventionalcommits.org +conventional_commits = true +# filter out the commits that are not conventional +filter_unconventional = true +# process each line of a commit as an individual commit +split_commits = false +# regex for preprocessing the commit messages +commit_preprocessors = [ + { pattern = '\((\w+\s)?#([0-9]+)\)', replace = "([#${2}](https://github.com/orhun/git-cliff/issues/${2}))"}, +] +# regex for parsing and grouping commits +commit_parsers = [ + { message = "^feat", group = "Features"}, + { message = "^fix", group = "Bug Fixes"}, + { message = "^doc", group = "Documentation"}, + { message = "^perf", group = "Performance"}, + { message = "^refactor", group = "Refactor"}, + { message = "^style", group = "Styling"}, + { message = "^test", group = "Testing"}, + { message = "^chore\\(release\\):", skip = true}, + { message = "^chore", group = "Miscellaneous Tasks"}, + { message = "^ci", group = "CI"}, + { body = ".*security", group = "Security"}, +] +# filter out the commits that are not matched by commit parsers +filter_commits = false +# glob pattern for matching git tags +tag_pattern = "v[0-9]*" +# regex for skipping tags +skip_tags = "v0.1.0-beta.1" +# regex for ignoring tags +ignore_tags = "" +# sort the tags chronologically +date_order = false +# sort the commits inside sections by oldest/newest order +sort_commits = "oldest" diff --git a/scripts/user_data.sh b/scripts/user_data.sh new file mode 100644 index 0000000..3880830 --- /dev/null +++ b/scripts/user_data.sh @@ -0,0 +1,342 @@ +#! /bin/bash +set -x + +# Install wget, unzip and awscli +yum install -y wget +yum install -y unzip + +curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip" +unzip awscliv2.zip +./aws/install +/usr/local/bin/aws --version + +echo "Installed wget, unzip and awscli" + +# Increase soft rlimits +[ -e /etc/security/limits.conf ] && rm -f /etc/security/limits.conf +touch /etc/security/limits.conf + +cat <<'EOT' >> /etc/security/limits.conf +# /etc/security/limits.conf +"* soft nofile 512000" +"* hard nofile 512000" +"* soft nproc 512000" +"* hard nproc 512000" +EOT + +[ -e /etc/security/limits.d/90-nproc.conf ] && rm -f /etc/security/limits.d/90-nproc.conf +touch /etc/security/limits.d/90-nproc.conf + +cat <<'EOT' >> /etc/security/limits.d/90-nproc.conf +# /etc/security/limits.d/90-nproc.conf +"* soft nproc 512000" +"* hard nproc 512000" +EOT + +[ -e /etc/security/limits.d/90-nofile.conf ] && rm -f /etc/security/limits.d/90-nofile.conf +touch /etc/security/limits.d/90-nofile.conf + +cat <<'EOT' >> /etc/security/limits.d/90-nofile.conf +# /etc/security/limits.d/90-nofile.conf +"* soft nofile 512000" +"* hard nofile 512000" +EOT + +[ -e /etc/sysconfig/docker ] && rm -f /etc/sysconfig/docker +touch /etc/sysconfig/docker + +cat <<'EOT' >> /etc/sysconfig/docker +# /etc/sysconfig/docker +# The max number of open files for the daemon itself, and all +# running containers. The default value of 1048576 mirrors the value +# used by the systemd service unit. +DAEMON_MAXFILES=1048576 + +# Additional startup options for the Docker daemon, for example: +# OPTIONS="--ip-forward=true --iptables=true" +# By default we limit the number of open files per container +OPTIONS="--default-ulimit nofile=512000:512000 --default-ulimit nproc=512000:512000" + +# How many seconds the sysvinit script waits for the pidfile to appear +# when starting the daemon. +DAEMON_PIDFILE_TIMEOUT=10 +EOT + +echo "Increased soft rlimits/ulimits" + +# Disable transparent huge pages +[ -e /etc/init.d/disable-transparent-hugepages ] && rm -f /etc/init.d/disable-transparent-hugepages +touch /etc/init.d/disable-transparent-hugepages + +cat <<'EOT' >> /etc/init.d/disable-transparent-hugepages +#!/bin/bash +### BEGIN INIT INFO +# Provides: disable-transparent-hugepages +# Required-Start: $local_fs +# Required-Stop: +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Disable transparent huge pages +# Description: Disable transparent huge pages to improve MongoDB database performance. +### END INIT INFO + +echo 'never' > /sys/kernel/mm/transparent_hugepage/enabled +echo 'never' > /sys/kernel/mm/transparent_hugepage/defrag +EOT + +chmod 755 /etc/init.d/disable-transparent-hugepages + +/etc/init.d/disable-transparent-hugepages start + +chkconfig --add disable-transparent-hugepages + +echo "Disabled transparent huge pages" + +# Create DNS record in AWS Route 53 for this instance +HOST_IP=$(curl http://169.254.169.254/latest/meta-data/local-ipv4); + +/usr/local/bin/aws route53 change-resource-record-sets \ + --hosted-zone-id ${HOSTED_ZONE_ID} \ + --change-batch \ +'{ + "Changes": [ + { + "Action": "UPSERT", + "ResourceRecordSet": { + "Name": "${DNS_NAME}", + "Type": "A", + "TTL": 30, + "ResourceRecords": [ + { + "Value": "'"$HOST_IP"'" + } + ] + } + } + ] +}' + +echo "Created DNS record in AWS Route 53 for this instance" + +# Configure and start ECS agent +cat <<'EOF' >> /etc/ecs/ecs.config +ECS_CLUSTER=${ECS_CLUSTER} +ECS_INSTANCE_ATTRIBUTES=${ECS_INSTANCE_ATTRIBUTES} +EOF + +sed -i '/After=cloud-final.service/d' /usr/lib/systemd/system/ecs.service + +systemctl daemon-reload + +# Verify that the agent is running +until curl -s http://localhost:51678/v1/metadata +do + sleep 1 +done + +echo "Configured and started ECS agent" + +# Install the Docker volume plugin +docker plugin install rexray/ebs REXRAY_PREEMPT=true EBS_REGION=${AWS_REGION} --grant-all-permissions + +echo "Installed rexray/ebs Docker plugin" + +systemctl restart docker +systemctl restart ecs + +echo "Restarted Docker and ECS agent" + +# Install Mongosh +cat <<'EOF' >> /etc/yum.repos.d/mongodb-org-5.0.repo +[mongodb-org-5.0] +name=MongoDB Repository +baseurl=https://repo.mongodb.org/yum/amazon/2/mongodb-org/5.0/x86_64/ +gpgcheck=1 +enabled=1 +gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc +EOF + +yum install -y mongodb-mongosh + +echo "Installed Mongosh" + +# Install MongoDB database tools +wget https://fastdl.mongodb.org/tools/db/mongodb-database-tools-amazon2-x86_64-100.5.1.rpm +yum install -y mongodb-database-tools-amazon2-x86_64-100.5.1.rpm + +echo "Installed MongoDB database tools" + +# Copy key file for MongoDB Cluster +MONGODB_KEYFILE=$(/usr/local/bin/aws ssm get-parameter --name ${MONGODB_KEYFILE_PARAMETER_NAME} --with-decryption --output text --query Parameter.Value) +mkdir -p /usr/bin/keys +echo "$MONGODB_KEYFILE" > /usr/bin/keys/mongodb.key +chmod 400 /usr/bin/keys/mongodb.key +chown 999:999 /usr/bin/keys/mongodb.key + +echo "Copied key file for MongoDB Cluster" + +# Install MongoDB backup script +cat <<'EOF' >> /usr/bin/mongo-backup.sh +#!/bin/bash +set -e + +# Create variables +TIMESTAMP=`date +%F-%H-%M` +BACKUP_S3_BUCKET_NAME=${BACKUP_S3_BUCKET_NAME} +MONGODB_HOST=${DNS_NAME} +MONGODB_USER=$(/usr/local/bin/aws ssm get-parameter --name ${MONGODB_USER_PARAMETER_NAME} --with-decryption --output text --query Parameter.Value) +MONGODB_PASSWORD=$(/usr/local/bin/aws ssm get-parameter --name ${MONGODB_PASSWORD_PARAMETER_NAME} --with-decryption --output text --query Parameter.Value) +MONGO_DATABASES=${MONGO_DATABASES} + +# Create MongoDB databases backup +IFS="," +for DB in $MONGO_DATABASES +do + IFS=":" && Array=($DB) + DB_NAME=$${Array[0]} + COLLECTIONS=$${Array[1]} + if [ $COLLECTIONS = "ALL" ] + then + mongodump --username $MONGODB_USER --password $MONGODB_PASSWORD --authenticationDatabase "admin" --db=$DB_NAME -v mongodb://$MONGODB_HOST:27017 + else + IFS=";" + for COLLECTION in $COLLECTIONS + do + mongodump --username $MONGODB_USER --password $MONGODB_PASSWORD --authenticationDatabase "admin" --db=$DB_NAME --collection=$COLLECTION -v mongodb://$MONGODB_HOST:27017 + done + fi +done + +# Compress backup with timestamp +tar vcf mongodb-$TIMESTAMP.tar dump + +# Upload to S3 +/usr/local/bin/aws s3 cp mongodb-$TIMESTAMP.tar s3://$BACKUP_S3_BUCKET_NAME/backups/mongodb-$TIMESTAMP.tar + +# Delete local files +rm -rf dump +rm -rf mongodb-* + +# Print success message +echo "Data in MongoDB cluster is backed up and stored on S3 successfully." +EOF + +echo "Installed MongoDB backup script" + +# Install MongoDB restore script +cat <<'EOF' >> /usr/bin/mongo-restore.sh +#!/bin/bash +set -e + +if [ -z "$1" ]; then echo "ERROR: Backup File Name from S3 is Empty." && exit 0; fi + +# Create variables +BACKUP_S3_BUCKET_NAME=${BACKUP_S3_BUCKET_NAME} +MONGODB_HOST=${DNS_NAME} +MONGODB_USER=$(/usr/local/bin/aws ssm get-parameter --name ${MONGODB_USER_PARAMETER_NAME} --with-decryption --output text --query Parameter.Value) +MONGODB_PASSWORD=$(/usr/local/bin/aws ssm get-parameter --name ${MONGODB_PASSWORD_PARAMETER_NAME} --with-decryption --output text --query Parameter.Value) + +# Download compressed backup json file from S3 +/usr/local/bin/aws s3 cp s3://$BACKUP_S3_BUCKET_NAME/backups/$1 mongodb-backup.tar + +# Decompress backup json file +tar -xf mongodb-backup.tar dump + +# Restore etcd from backup json file +mongorestore --host=$MONGODB_HOST:27017 --username=$MONGODB_USER --password=$MONGODB_PASSWORD --authenticationDatabase "admin" -v ./dump + +# Delete local files +rm -rf dump +rm -rf mongodb-backup.tar + +# Print success message +echo "Data in MongoDB cluster is restored from S3 successfully." +EOF + +echo "Installed MongoDB restore script" + +# Enable cron for MongoDB backup script +if [ "${ENABLE_BACKUP}" = "YES" ] +then + # Enable cron + crontab -l > tempfile + echo "0 3 * * * /bin/bash /usr/bin/mongo-backup.sh" >> tempfile + crontab tempfile + rm tempfile + + echo "Enabled cron for MongoDB backup script" +fi + +# Install custom agent for EBS disk usage monitoring +cat <<'EOF' >> /usr/bin/send-ebs-disk-usage-on-cloudwatch.sh +#!/bin/bash +set -e + +ASG_NAME=${ASG_NAME} +INSTANCE_ID=$(curl http://169.254.169.254/latest/meta-data/instance-id) +COUNT=1 + +df -h --print-type --type="ext4" --type="xfs" | grep "/" | while read LINE +do + DATA=$(echo ${LINE} | awk '{print $1, $2, $6, $7}') + + IFS=" " && Array=($DATA) + + DEVICE_NAME=$${Array[0]} + DEVICE_NAME_TRIMMED="$${DEVICE_NAME//'/'}" + FILE_SYSTEM=$${Array[1]} + DISK_USED=$${Array[2]} + DISK_USED="$${DISK_USED//%}" + MOUNT_PATH=$${Array[3]} + + if [ -e "/usr/bin/cw-alarm-$${COUNT}.file" ] + then + /usr/local/bin/aws cloudwatch put-metric-data \ + --metric-name disk_used_percent \ + --namespace CustomAgent \ + --unit Percent \ + --value "$DISK_USED" \ + --dimensions \ + AutoScalingGroupName="$ASG_NAME",InstanceID="$INSTANCE_ID",device="$DEVICE_NAME",fstype="$FILE_SYSTEM",path="$MOUNT_PATH" + else + /usr/local/bin/aws cloudwatch put-metric-alarm \ + --alarm-name "${ALARM_NAME_PREFIX}-ebs-volume-$${COUNT}-disk-utilization" \ + --comparison-operator GreaterThanThreshold \ + --evaluation-periods 1 \ + --metric-name disk_used_percent \ + --namespace CustomAgent \ + --period 60 \ + --statistic Maximum \ + --threshold 90 \ + --datapoints-to-alarm 1 \ + --treat-missing-data "${ALARM_TREAT_MISSING_DATA}" \ + --alarm-description "${ALARM_NAME_PREFIX} EBS Volume Disk Utilization" \ + --alarm-actions "${ALARM_SNS_TOPIC}" \ + --ok-actions "${ALARM_SNS_TOPIC}" \ + --dimensions \ + Name="AutoScalingGroupName",Value="$ASG_NAME" \ + Name="InstanceID",Value="$INSTANCE_ID" \ + Name="device",Value="$DEVICE_NAME" \ + Name="fstype",Value="$FILE_SYSTEM" \ + Name="path",Value="$MOUNT_PATH" + + touch "/usr/bin/cw-alarm-$${COUNT}.file" + fi + + COUNT=$((COUNT+1)) +done +EOF + +echo "Installed custom agent for EBS disk usage monitoring" + +# Enable cron for custom agent for EBS disk usage monitoring +if [ "${ENABLE_MONITORING}" = "YES" ] +then + # Enable cron + crontab -l > tempfile + echo "* * * * * /bin/bash /usr/bin/send-ebs-disk-usage-on-cloudwatch.sh" >> tempfile + crontab tempfile + rm tempfile + + echo "Enabled custom agent for EBS disk usage monitoring" +fi diff --git a/templates/container-definition.json.tpl b/templates/container-definition.json.tpl new file mode 100644 index 0000000..f1c3abe --- /dev/null +++ b/templates/container-definition.json.tpl @@ -0,0 +1,22 @@ +[ + { + "name": "${name}", + "image": "${image}", + "cpu": ${cpu}, + "memory": ${memory}, + "privileged": ${privileged}, + "command": ${command}, + "portMappings": ${portMappings}, + "mountPoints": ${mountPoints}, + "secrets": ${secrets}, + "logConfiguration": { + "logDriver": "awslogs", + "options": { + "awslogs-create-group": "true", + "awslogs-group": "${namespace}-${env_name}-${service_name}", + "awslogs-region": "${aws_region}", + "awslogs-stream-prefix": "ecs" + } + } + } +] \ No newline at end of file diff --git a/terraform-usage-example.tf b/terraform-usage-example.tf new file mode 100644 index 0000000..ccefabb --- /dev/null +++ b/terraform-usage-example.tf @@ -0,0 +1,34 @@ +# Note: dummy value is something that has to be replaced even for this example to work. + +module "mongodb-cluster-on-aws-ecs" { + source = "./terraform" + + account_id = "012345678910" # dummy value + aws_region = "eu-west-1" # Europe (Ireland) + namespace = "project" # dummy value + env_name = "dev" + service_name = "mongodb" + vpc_id = "vpc-012345678910abcde" # dummy value + volume_type = "gp3" + volume_size = 20 + volume_iops = 3000 + volume_encrypted = true + volume_encryption_key = "arn:aws:kms:eu-west-1:012345678910:key/0123abcd-01ab-01ab-0123-012345abcdef" # dummy value + cpu = 1648 + memory = 1854 + instance_type = "t3.small" + image = "docker.io/mongo:5.0.6" + hosted_zone_name = "project.net" # dummy value + ec2_key_pair_name = "project-dev-mongodb" # dummy value + number_of_instances = 3 + private_subnet_tag_name = "Private-1*" # dummy value + + # If you want to enable disk usage monitoring + monitoring_enabled = true + alarm_treat_missing_data = "missing" + aws_sns_topic = "arn:aws:sns:eu-west-1:012345678910:AWS_SNS_TOPIC_NAME" + + # If you want to enable backups + backup_enabled = true + mongodb_backup_databases = "admin:ALL" # dummy value +} diff --git a/terraform/cloudwatch.tf b/terraform/cloudwatch.tf new file mode 100644 index 0000000..084d358 --- /dev/null +++ b/terraform/cloudwatch.tf @@ -0,0 +1,43 @@ +resource "aws_cloudwatch_metric_alarm" "ecs_cpu_utilization" { + count = var.monitoring_enabled == true ? var.number_of_instances : 0 + + alarm_name = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}-cpu-utilization" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = "2" + metric_name = "CPUUtilization" + namespace = "AWS/ECS" + period = "300" + statistic = "Average" + threshold = "80" + treat_missing_data = var.alarm_treat_missing_data + alarm_description = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1} Container CPU Utilization" + alarm_actions = [var.aws_sns_topic] + ok_actions = [var.aws_sns_topic] + + dimensions = { + ServiceName = "${var.service_name}${count.index + 1}" + ClusterName = "${var.namespace}-${var.env_name}-${var.service_name}-cluster" + } +} + +resource "aws_cloudwatch_metric_alarm" "ecs_memory_utilization" { + count = var.monitoring_enabled == true ? var.number_of_instances : 0 + + alarm_name = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}-memory-utilization" + comparison_operator = "GreaterThanOrEqualToThreshold" + evaluation_periods = "2" + metric_name = "MemoryUtilization" + namespace = "AWS/ECS" + period = "300" + statistic = "Average" + threshold = "90" + treat_missing_data = var.alarm_treat_missing_data + alarm_description = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1} Container Memory Utilization" + alarm_actions = [var.aws_sns_topic] + ok_actions = [var.aws_sns_topic] + + dimensions = { + ServiceName = "${var.service_name}${count.index + 1}" + ClusterName = "${var.namespace}-${var.env_name}-${var.service_name}-cluster" + } +} diff --git a/terraform/data.tf b/terraform/data.tf new file mode 100644 index 0000000..c04ce7e --- /dev/null +++ b/terraform/data.tf @@ -0,0 +1,34 @@ +data "aws_vpc" "this" { + id = var.vpc_id +} + +data "aws_subnets" "this" { + filter { + name = "vpc-id" + values = [var.vpc_id] + } + + tags = { + Name = var.private_subnet_tag_name + } +} + +data "aws_route53_zone" "this" { + name = var.hosted_zone_name +} + +data "aws_ami" "amzlinux2" { + most_recent = true + + filter { + name = "name" + values = ["amzn2-ami-ecs-hvm-*-x86_64*"] + } + + filter { + name = "virtualization-type" + values = ["hvm"] + } + + owners = ["amazon"] +} diff --git a/terraform/ec2_asg.tf b/terraform/ec2_asg.tf new file mode 100644 index 0000000..cece66e --- /dev/null +++ b/terraform/ec2_asg.tf @@ -0,0 +1,83 @@ +resource "aws_launch_template" "this" { + count = var.number_of_instances + + name = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}-launch-template" + image_id = data.aws_ami.amzlinux2.id + instance_type = var.instance_type + key_name = var.ec2_key_pair_name + ebs_optimized = true + vpc_security_group_ids = [aws_security_group.this.id] + update_default_version = true + + block_device_mappings { + device_name = "/dev/xvda" + + ebs { + volume_type = var.volume_type + volume_size = 30 + iops = var.volume_iops + encrypted = var.volume_encrypted + kms_key_id = var.volume_encryption_key == null ? aws_kms_key.ebs[0].arn : var.volume_encryption_key + } + } + + iam_instance_profile { + name = aws_iam_instance_profile.this.name + } + + monitoring { + enabled = true + } + + user_data = base64encode(templatefile("${path.module}/scripts/user_data.sh", { + ECS_CLUSTER = aws_ecs_cluster.this.name + ECS_INSTANCE_ATTRIBUTES = "{\"name\":\"${var.service_name}${count.index + 1}\"}" + AWS_REGION = var.aws_region + ASG_NAME = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}-asg" + LINE = "$LINE" + ENABLE_MONITORING = var.monitoring_enabled == true ? "YES" : "NO" + ALARM_NAME_PREFIX = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}" + ALARM_TREAT_MISSING_DATA = var.alarm_treat_missing_data + ALARM_SNS_TOPIC = var.aws_sns_topic + HOSTED_ZONE_ID = data.aws_route53_zone.this.zone_id + DNS_NAME = "${var.env_name}-${var.service_name}${count.index + 1}.${var.hosted_zone_name}" + BACKUP_S3_BUCKET_NAME = "${var.namespace}-${var.env_name}-mongodb-backups-bucket" + ENABLE_BACKUP = var.backup_enabled == true && count.index == 0 ? "YES" : "NO" + MONGODB_USER_PARAMETER_NAME = "/docker/${var.env_name}/MONGODB_USERNAME" + MONGODB_PASSWORD_PARAMETER_NAME = "/docker/${var.env_name}/MONGODB_PASSWORD" + MONGODB_KEYFILE_PARAMETER_NAME = "/docker/${var.env_name}/MONGODB_KEYFILE" + MONGO_DATABASES = var.mongodb_backup_databases + })) + + tag_specifications { + resource_type = "instance" + + tags = { + Name = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}" + } + } +} + +resource "aws_autoscaling_group" "this" { + count = var.number_of_instances + + name = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}-asg" + vpc_zone_identifier = [tolist(data.aws_subnets.this.ids)[count.index]] + desired_capacity = 1 + max_size = 1 + min_size = 1 + health_check_type = "EC2" + + launch_template { + id = aws_launch_template.this[count.index].id + version = aws_launch_template.this[count.index].latest_version + } + + instance_refresh { + strategy = "Rolling" + preferences { + min_healthy_percentage = 0 + instance_warmup = 0 + } + } +} \ No newline at end of file diff --git a/terraform/ecs_cluster.tf b/terraform/ecs_cluster.tf new file mode 100644 index 0000000..3e28c40 --- /dev/null +++ b/terraform/ecs_cluster.tf @@ -0,0 +1,8 @@ +resource "aws_ecs_cluster" "this" { + name = "${var.namespace}-${var.env_name}-${var.service_name}" + + setting { + name = "containerInsights" + value = "enabled" + } +} \ No newline at end of file diff --git a/terraform/ecs_service.tf b/terraform/ecs_service.tf new file mode 100644 index 0000000..30fbf0e --- /dev/null +++ b/terraform/ecs_service.tf @@ -0,0 +1,12 @@ +resource "aws_ecs_service" "this" { + count = var.number_of_instances + + name = "${var.service_name}${count.index + 1}" + cluster = aws_ecs_cluster.this.id + launch_type = "EC2" + task_definition = aws_ecs_task_definition.this[count.index].arn + force_new_deployment = false + desired_count = 1 + deployment_maximum_percent = 100 + deployment_minimum_healthy_percent = 0 +} \ No newline at end of file diff --git a/terraform/ecs_task_definition.tf b/terraform/ecs_task_definition.tf new file mode 100644 index 0000000..0a0c33b --- /dev/null +++ b/terraform/ecs_task_definition.tf @@ -0,0 +1,82 @@ +resource "aws_ecs_task_definition" "this" { + count = var.number_of_instances + + family = "${var.service_name}${count.index + 1}-${var.env_name}" + requires_compatibilities = ["EC2"] + task_role_arn = aws_iam_role.task.arn + execution_role_arn = aws_iam_role.task.arn + network_mode = "host" + skip_destroy = false + + placement_constraints { + type = "memberOf" + expression = "attribute:name == ${var.service_name}${count.index + 1}" + } + + volume { + name = "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}-ebs" + + docker_volume_configuration { + scope = "shared" + autoprovision = true + driver = "rexray/ebs" + labels = {} + + driver_opts = { + volumetype = var.volume_type + size = var.volume_size + iops = var.volume_iops + encrypted = var.volume_encrypted + encryptionkey = var.volume_encryption_key == null ? aws_kms_key.ebs[0].arn : var.volume_encryption_key + } + } + } + + volume { + name = "mongodb-keys" + host_path = "/usr/bin/keys" + } + + container_definitions = templatefile("${path.module}/templates/container-definition.json.tpl", { + aws_region = var.aws_region + namespace = var.namespace + env_name = var.env_name + service_name = var.service_name + name = "${var.service_name}${count.index + 1}" + image = var.image + cpu = var.cpu + memory = var.memory + privileged = true + command = var.number_of_instances > 1 ? jsonencode(["--replSet", "rs0", "--keyFile", "/keys/mongodb.key"]) : jsonencode([]) + + portMappings = jsonencode([ + { + "protocol" : "tcp", + "containerPort" : 27017, + "hostPort" : 27017 + } + ]) + + mountPoints = jsonencode([ + { + "containerPath" : "/data/db", + "sourceVolume" : "${var.namespace}-${var.env_name}-${var.service_name}${count.index + 1}-ebs" + }, + { + "containerPath" : "/keys", + "sourceVolume" : "mongodb-keys" + } + ]) + + secrets = jsonencode([ + { + "name" : "MONGO_INITDB_ROOT_USERNAME", + "valueFrom" : "arn:aws:ssm:${var.aws_region}:${var.account_id}:parameter/docker/${var.env_name}/MONGODB_USERNAME" + }, + { + "name" : "MONGO_INITDB_ROOT_PASSWORD", + "valueFrom" : "arn:aws:ssm:${var.aws_region}:${var.account_id}:parameter/docker/${var.env_name}/MONGODB_PASSWORD" + } + ]) + }) +} diff --git a/terraform/iam_ec2.tf b/terraform/iam_ec2.tf new file mode 100644 index 0000000..f0af289 --- /dev/null +++ b/terraform/iam_ec2.tf @@ -0,0 +1,167 @@ +resource "aws_iam_instance_profile" "this" { + name = "${var.namespace}-${var.env_name}-${var.service_name}-ec2-profile" + role = aws_iam_role.this.name +} + +resource "aws_iam_role_policy_attachment" "this" { + count = length(local.ec2_role_policies) + + role = aws_iam_role.this.name + policy_arn = element(local.ec2_role_policies, count.index) +} + +resource "aws_iam_role_policy" "ec2" { + name = "${var.namespace}-${var.env_name}-${var.service_name}-ec2-inline-policy" + role = aws_iam_role.this.id + + policy = <