├── .gitignore ├── LICENSE ├── README.md ├── alb ├── main.tf ├── outputs.tf └── variables.tf ├── cloudwatch ├── main.tf ├── outputs.tf └── variables.tf ├── dns ├── main.tf ├── output.tf └── variables.tf ├── ec2 ├── main.tf ├── outputs.tf ├── templates │ └── cloud-config.tpl └── variables.tf ├── ecr ├── main.tf ├── outputs.tf ├── resources │ ├── Dockerfile │ ├── image_push.sh │ └── standalone-ha.xml └── variables.tf ├── ecs ├── main.tf ├── outputs.tf ├── templates │ └── task-definition.tpl └── variables.tf ├── iam ├── main.tf ├── outputs.tf ├── resources │ ├── ecs_instance_role.json │ ├── ecs_service_role.json │ └── ecs_service_role_policy.json ├── templates │ └── instance-profile-policy.tpl └── variables.tf ├── main.tf ├── outputs.tf ├── rds ├── main.tf ├── output.tf └── variables.tf ├── variables.tf └── vpc ├── main.tf ├── outputs.tf └── variables.tf /.gitignore: -------------------------------------------------------------------------------- 1 | # Local .terraform directories 2 | **/.terraform/* 3 | 4 | # .tfstate files 5 | *.tfstate 6 | *.tfstate.* 7 | 8 | # Crash log files 9 | crash.log 10 | 11 | # Private variables 12 | private.tfvars 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## keycloak-cluster-aws-rds 2 | 3 | A sample Terraform setup for creating an auto-scaling KeyCloak cluster behind an ALB 4 | 5 | ## What 6 | 7 | This project demonstrates how to launch a cluster of [KeyCloak](https://keycloak.org) instances with a PostgreSQL [RDS](https://aws.amazon.com/rds/) backend within your AWS [VPC](https://aws.amazon.com/vpc/) using [Terraform](https://terraform.io). These modules will deploy KeyCloak within auto-scaling Docker containers deployed on EC2, accessible behind an [ALB](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html). A DNS record for the instance will also be created using [Route 53](https://aws.amazon.com/route53/) and a corresponding certificate for the ALB will be created and applied using [ACM](https://aws.amazon.com/certificate-manager/). 8 | 9 | ## Getting Started 10 | 11 | #### Docker 12 | 13 | This code assumes you have [Docker](https://www.docker.com) installed locally. As part of the Terraform code, a new Docker image is built and pushed to an [AWS ECR](https://aws.amazon.com/ecr/) repository. The reason for this is the standard KeyCloak Docker image does not include support for JDBC_PING as a cluster management protocol. In a non-AWS environment, multicast would be used to locate cluster members. Since AWS does not support multicast, this information is instead stored in an RDS database accessible by cluster members. A custom ```standalone-ha.xml``` file is added to a custom KeyCloak Docker image created by this code to support this functionality. 14 | 15 | ### Terraform 16 | This code has been tested using Terraform 0.12.0. If you are running a newer version of Terraform, you may need to make some changes and tweaks. After cloning this repo, within the source directory run: 17 | 18 | ``` 19 | terraform init 20 | ``` 21 | 22 | This will ensure that the modules are registered and any required providers are downloaded. Now that the build environment is initialized, you must define the values for the variables needed by the Terraform modules. You may either do this as `terraform apply` is run, or you may use a var file. To use a var file (in this case, called `private.tfvars`) simple run: 23 | 24 | ``` 25 | terraform plan -var-file=private.tfvars 26 | ``` 27 | 28 | If everything in the plan looks appropriate, you may apply the Terraform module and begin building out your infrastructure by running: 29 | 30 | ``` 31 | terraform apply -var-file=private.tfvars 32 | ``` 33 | 34 | ## Testing it out 35 | 36 | Once your Terraform build completes, you will see outputs showing the ALB's DNS name, as well as the DNS name created using Route 53. Wait a couple seconds for the ALB to register the backend targets, and then open up a browser to either of those values. You should see the KeyCloak login page appear. Login with the administrator username and password you provided as part of your Terraform variables. You can also login to the AWS CloudWatch console to view the KeyCloak logs. There, you should see 2 instances of KeyCloak operating in a cluster. 37 | 38 | ## Caveats 39 | 40 | A few caveats, particularly related to security... 41 | 42 | #### JDBC_PING vs. S3_PING 43 | 44 | As multicast is not support within AWS, the normal jGroups cluster maintenance protocol will not work. There are two options available to us in the AWS environment: ```S3_PING``` and ```JDBC_PING```. The S3_PING mechanism utilizes a shared S3 bucket for maintaining information on cluster members. The JDBC_PING mechanism uses a backend database for this information. 45 | 46 | While S3_PING may be more convenient and give us easier insight into cluster members, Wildfly does not support grabbing the AWS access key and secret key using the instance metadata. As a result, you are forced to specify the access key and secret key within your Wildfly configuration file. This is less than ideal, as it would require us to run scripts to grab this information when the Docker container starts up, then either set environment variables (very insecure) or update the configuration file on the filesystem (still insecure). 47 | 48 | For this deployment, I am leveraging JDBC_PING rather than S3_PING to reduce some of these security issues. The ping table is maintained in the same database that KeyCloak uses for its user data, provided via RDS. 49 | 50 | #### Route 53 and DNS 51 | 52 | This deployment assumes that you have an existing Route 53 zone setup for your domain. The DNS record for KeyCloak will created in this zone during ```apply```, but the zone itself must exist beforehand. 53 | 54 | #### RDS Credentials 55 | 56 | Due to shortcomings in the way that the KeyCloak Docker image and underlying application server work, RDS credentials are provided as part of the ECS task definition and made available to KeyClok as environment variables. This is less than ideal, but I'm not knowledgeable enough on Terraform to come up with a better way. If you have one, feel free to raise an issue or submit a pull request! 57 | 58 | #### RDS Database Engine 59 | 60 | This code is based off of an RDS instance running PostgreSQL. It's likely that you could change the database engine to MySQL or another database supported by KeyCloak, but this functionality has not been tested. It is also important to note that there is no Multi-AZ capability enabled in this code, nor is there any sort of replication defined. 61 | 62 | ## Questions/Issues 63 | 64 | Find a bug? Have an idea on how to better implement a section of the code? Have a general question? Feel free to raise an issue or submit a pull request! I can't guarantee that I have all the answers, as this project is really just an exercise to help me learn Terraform better. But I'll certainly give it my best shot. -------------------------------------------------------------------------------- /alb/main.tf: -------------------------------------------------------------------------------- 1 | resource "aws_alb_target_group" "main" { 2 | name = "${var.alb_target_group_name}" 3 | port = "${var.alb_target_port}" 4 | protocol = "HTTP" 5 | vpc_id = "${var.vpc_id}" 6 | } 7 | 8 | resource "aws_alb" "main" { 9 | name = "${var.alb_name}" 10 | subnets = "${var.subnet_ids}" 11 | security_groups = "${var.security_groups}" 12 | } 13 | 14 | resource "aws_alb_listener" "front_end_tls" { 15 | load_balancer_arn = "${aws_alb.main.id}" 16 | port = "443" 17 | protocol = "HTTPS" 18 | # port = "80" 19 | # protocol = "HTTP" 20 | 21 | ssl_policy = "ELBSecurityPolicy-2015-05" 22 | certificate_arn = "${var.certificate_arn}" 23 | 24 | default_action { 25 | target_group_arn = "${aws_alb_target_group.main.id}" 26 | type = "forward" 27 | } 28 | } -------------------------------------------------------------------------------- /alb/outputs.tf: -------------------------------------------------------------------------------- 1 | output "alb_dns_name" { 2 | value = "${aws_alb.main.dns_name}" 3 | } 4 | 5 | # output "alb_public_ip" { 6 | # value = "${aws_alb.main.public_ip}" 7 | # } 8 | 9 | output "alb_id" { 10 | value = "${aws_alb.main.id}" 11 | } 12 | 13 | output "alb_arn" { 14 | value = "${aws_alb.main.arn}" 15 | } 16 | 17 | output "alb_zone" { 18 | value = "${aws_alb.main.zone_id}" 19 | } 20 | 21 | output "alb_target_group_arn" { 22 | value = "${aws_alb_target_group.main.id}" 23 | } 24 | 25 | output "alb_listener_front_end_tls" { 26 | value = "${aws_alb_listener.front_end_tls.id}" 27 | } 28 | -------------------------------------------------------------------------------- /alb/variables.tf: -------------------------------------------------------------------------------- 1 | variable "alb_port" { 2 | description = "The port the ALB should listen on" 3 | default = 80 4 | } 5 | 6 | variable "alb_target_port" { 7 | description = "The port the ALB should connect to backend services on on" 8 | default = 8080 9 | } 10 | 11 | variable "alb_protocol" { 12 | description = "The protocol for the ALB" 13 | default = "HTTP" 14 | } 15 | 16 | variable "alb_target_group_name" { 17 | description = "The name for the ALB target group" 18 | default = "keycloak-target-group" 19 | } 20 | 21 | variable "alb_name" { 22 | description = "The name for the ALB" 23 | default = "keycloak-alb" 24 | } 25 | 26 | variable "vpc_id" {} 27 | 28 | variable "subnet_ids" {} 29 | 30 | variable "security_groups" {} 31 | 32 | variable "certificate_arn" {} 33 | -------------------------------------------------------------------------------- /cloudwatch/main.tf: -------------------------------------------------------------------------------- 1 | resource "aws_cloudwatch_log_group" "ecs" { 2 | name = "${var.ecs_log_group_name}" 3 | } 4 | 5 | resource "aws_cloudwatch_log_group" "app" { 6 | name = "${var.app_log_group_name}" 7 | } 8 | -------------------------------------------------------------------------------- /cloudwatch/outputs.tf: -------------------------------------------------------------------------------- 1 | output "app_log_group_arn" { 2 | value = "${aws_cloudwatch_log_group.app.arn}" 3 | } 4 | 5 | output "ecs_log_group_arn" { 6 | value = "${aws_cloudwatch_log_group.ecs.arn}" 7 | } 8 | 9 | output "ecs_log_group_name" { 10 | value = "${aws_cloudwatch_log_group.ecs.name}" 11 | } 12 | 13 | output "app_log_group_name" { 14 | value = "${aws_cloudwatch_log_group.app.name}" 15 | } -------------------------------------------------------------------------------- /cloudwatch/variables.tf: -------------------------------------------------------------------------------- 1 | variable "ecs_log_group_name" { 2 | default = "ecs-group/ecs-agent" 3 | } 4 | 5 | variable "app_log_group_name" { 6 | default = "ecs-group/app-keycloak" 7 | } -------------------------------------------------------------------------------- /dns/main.tf: -------------------------------------------------------------------------------- 1 | data "aws_route53_zone" "main" { 2 | name = "${var.zone_name}" 3 | private_zone = false 4 | } 5 | 6 | resource "aws_route53_record" "cname" { 7 | zone_id = "${data.aws_route53_zone.main.zone_id}" 8 | name = "${var.public_dns_name}" 9 | type = "CNAME" 10 | ttl = "60" 11 | records = ["${var.alb_dns_name}"] 12 | } 13 | 14 | resource "aws_acm_certificate" "main" { 15 | domain_name = "${var.public_dns_name}" 16 | validation_method = "DNS" 17 | } 18 | 19 | resource "aws_route53_record" "validation" { 20 | name = "${aws_acm_certificate.main.domain_validation_options.0.resource_record_name}" 21 | type = "${aws_acm_certificate.main.domain_validation_options.0.resource_record_type}" 22 | zone_id = "${data.aws_route53_zone.main.zone_id}" 23 | records = ["${aws_acm_certificate.main.domain_validation_options.0.resource_record_value}"] 24 | ttl = "60" 25 | } 26 | 27 | resource "aws_acm_certificate_validation" "main" { 28 | certificate_arn = "${aws_acm_certificate.main.arn}" 29 | validation_record_fqdns = "${aws_route53_record.validation.*.fqdn}" 30 | } 31 | -------------------------------------------------------------------------------- /dns/output.tf: -------------------------------------------------------------------------------- 1 | output "acm_certificate_arn" { 2 | value = "${aws_acm_certificate.main.arn}" 3 | } 4 | -------------------------------------------------------------------------------- /dns/variables.tf: -------------------------------------------------------------------------------- 1 | variable "public_dns_name" {} 2 | 3 | variable "zone_name" {} 4 | 5 | variable "alb_dns_name" {} 6 | 7 | variable "alb_zone_id" {} 8 | -------------------------------------------------------------------------------- /ec2/main.tf: -------------------------------------------------------------------------------- 1 | data "aws_ami" "stable_coreos" { 2 | most_recent = true 3 | 4 | filter { 5 | name = "description" 6 | values = ["CoreOS Container Linux stable *"] 7 | } 8 | 9 | filter { 10 | name = "architecture" 11 | values = ["x86_64"] 12 | } 13 | 14 | filter { 15 | name = "virtualization-type" 16 | values = ["hvm"] 17 | } 18 | 19 | owners = ["595879546273"] 20 | } 21 | 22 | resource "aws_autoscaling_group" "app" { 23 | name = "${var.autoscaling_group_name}" 24 | vpc_zone_identifier = "${var.vpc_zone_identifier}" 25 | min_size = "${var.autoscaling_min_size}" 26 | max_size = "${var.autoscaling_max_size}" 27 | desired_capacity = "${var.autoscaling_desired_size}" 28 | launch_configuration = "${aws_launch_configuration.app.name}" 29 | } 30 | 31 | data "template_file" "cloud_config" { 32 | template = "${file("ec2/templates/cloud-config.tpl")}" 33 | 34 | vars = { 35 | aws_region = "${var.aws_region}" 36 | ecs_cluster_name = "${var.ecs_cluster_name}" 37 | ecs_log_level = "${var.ecs_log_level}" 38 | ecs_agent_version = "latest" 39 | ecs_log_group_name = "${var.ecs_log_group_name}" 40 | } 41 | } 42 | 43 | resource "aws_launch_configuration" "app" { 44 | security_groups = [ 45 | "${var.instance_sg_id}", 46 | ] 47 | 48 | key_name = "${var.key_name}" 49 | image_id = "${data.aws_ami.stable_coreos.id}" 50 | instance_type = "${var.instance_type}" 51 | iam_instance_profile = "${var.app_iam_instance_profile_name}" 52 | user_data = "${data.template_file.cloud_config.rendered}" 53 | associate_public_ip_address = true 54 | 55 | lifecycle { 56 | create_before_destroy = true 57 | } 58 | } 59 | 60 | resource "tls_private_key" "genkey" { 61 | algorithm = "RSA" 62 | rsa_bits = 4096 63 | } 64 | 65 | resource "aws_key_pair" "genkey" { 66 | key_name = "${var.key_name}" 67 | public_key = "${tls_private_key.genkey.public_key_openssh}" 68 | } 69 | -------------------------------------------------------------------------------- /ec2/outputs.tf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/devopsutils/keycloak-cluster-aws-rds/7a6e1bcd37bbd2bdcf28cd93ed687c8925dfce2e/ec2/outputs.tf -------------------------------------------------------------------------------- /ec2/templates/cloud-config.tpl: -------------------------------------------------------------------------------- 1 | #cloud-config 2 | coreos: 3 | units: 4 | - name: update-engine.service 5 | command: stop 6 | - name: amazon-ecs-agent.service 7 | command: start 8 | runtime: true 9 | content: | 10 | [Unit] 11 | Description=AWS ECS Agent 12 | Documentation=https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ 13 | Requires=docker.socket 14 | After=docker.socket 15 | 16 | [Service] 17 | Environment=ECS_CLUSTER=${ecs_cluster_name} 18 | Environment=ECS_LOGLEVEL=${ecs_log_level} 19 | Environment=ECS_VERSION=${ecs_agent_version} 20 | Restart=on-failure 21 | RestartSec=30 22 | RestartPreventExitStatus=5 23 | SyslogIdentifier=ecs-agent 24 | ExecStartPre=-/bin/mkdir -p /var/log/ecs /var/ecs-data /etc/ecs 25 | ExecStartPre=-/usr/bin/docker kill ecs-agent 26 | ExecStartPre=-/usr/bin/docker rm ecs-agent 27 | ExecStartPre=/usr/bin/docker pull amazon/amazon-ecs-agent:$${ECS_VERSION} 28 | ExecStart=/usr/bin/docker run --name ecs-agent \ 29 | --volume=/var/run/docker.sock:/var/run/docker.sock \ 30 | --volume=/var/log/ecs:/log \ 31 | --volume=/var/ecs-data:/data \ 32 | --volume=/sys/fs/cgroup:/sys/fs/cgroup:ro \ 33 | --volume=/run/docker/execdriver/native:/var/lib/docker/execdriver/native:ro \ 34 | --publish=127.0.0.1:51678:51678 \ 35 | --env=ECS_LOGFILE=/log/ecs-agent.log \ 36 | --env=ECS_LOGLEVEL=$${ECS_LOGLEVEL} \ 37 | --env=ECS_DATADIR=/data \ 38 | --env=ECS_CLUSTER=$${ECS_CLUSTER} \ 39 | --env=ECS_AVAILABLE_LOGGING_DRIVERS='["awslogs"]' \ 40 | --log-driver=awslogs \ 41 | --log-opt awslogs-region=${aws_region} \ 42 | --log-opt awslogs-group=${ecs_log_group_name} \ 43 | amazon/amazon-ecs-agent:$${ECS_VERSION} 44 | -------------------------------------------------------------------------------- /ec2/variables.tf: -------------------------------------------------------------------------------- 1 | variable "instance_type" { 2 | description = "The ECS instance type" 3 | default = "t2.medium" 4 | } 5 | 6 | variable "autoscaling_group_name" { 7 | description = "The name for the autoscaling group" 8 | default = "asg-keycloak" 9 | } 10 | variable "autoscaling_min_size" { 11 | description = "The minimum number of servers in the autoscaling group" 12 | default = "2" 13 | } 14 | 15 | variable "autoscaling_max_size" { 16 | description = "The maximum number of servers in the autoscaling group" 17 | default = "4" 18 | } 19 | 20 | variable "autoscaling_desired_size" { 21 | description = "The desired number of servers in the autoscaling group" 22 | default = "2" 23 | } 24 | 25 | variable "key_name" {} 26 | 27 | variable "aws_region" {} 28 | 29 | variable "ecs_log_level" {} 30 | 31 | variable "ecs_cluster_name" {} 32 | 33 | variable "vpc_zone_identifier" {} 34 | 35 | variable "app_iam_instance_profile_name" {} 36 | 37 | variable "instance_sg_id" {} 38 | 39 | variable "ecs_log_group_name" {} -------------------------------------------------------------------------------- /ecr/main.tf: -------------------------------------------------------------------------------- 1 | resource "aws_ecr_repository" "main" { 2 | name = "${var.ecr_repository_name}" 3 | } 4 | 5 | resource "null_resource" "build_docker_image" { 6 | 7 | provisioner "local-exec" { 8 | command = "docker image build -t ${var.docker_image_name}:${var.docker_image_tag} ." 9 | # command = "docker image build -t ${aws_ecr_repository.main.repository_url}/${var.docker_image_name}:${var.docker_image_tag} ." 10 | working_dir = "${dirname("${path.module}/resources/Dockerfile")}" 11 | } 12 | } 13 | 14 | resource "null_resource" "tag_and_push_docker_image" { 15 | 16 | provisioner "local-exec" { 17 | command = "sh ./image_push.sh ${var.aws_region} ${var.docker_image_name}:${var.docker_image_tag} ${aws_ecr_repository.main.repository_url}" 18 | working_dir = "${dirname("${path.module}/resources/image_push.sh")}" 19 | } 20 | 21 | depends_on = ["null_resource.build_docker_image"] 22 | } 23 | -------------------------------------------------------------------------------- /ecr/outputs.tf: -------------------------------------------------------------------------------- 1 | output "ecr_repo_url" { 2 | value = "${aws_ecr_repository.main.repository_url}" 3 | } 4 | 5 | output "docker_image_name" { 6 | value = "${var.docker_image_name}:${var.docker_image_tag}" 7 | } -------------------------------------------------------------------------------- /ecr/resources/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM jboss/keycloak:6.0.1 2 | 3 | # COPY ./extract_aws_creds.sh /opt/jboss/tools/extract_aws_creds.sh 4 | # COPY ./custom-docker-entrypoint.sh /opt/jboss/tools/custom-docker-entrypoint.sh 5 | # USER root 6 | 7 | # # Ensure that the necessary utilities are installed 8 | # RUN yum -y install wget 9 | 10 | # # Set the custom scripts as executable 11 | # RUN chmod +x /opt/jboss/tools/extract_aws_creds.sh 12 | # RUN chmod +x /opt/jboss/tools/custom-docker-entrypoint.sh 13 | 14 | # USER 1000 15 | 16 | COPY ./standalone-ha.xml /opt/jboss/keycloak/standalone/configuration/standalone-ha.xml 17 | ENTRYPOINT [ "/opt/jboss/tools/docker-entrypoint.sh" ] 18 | -------------------------------------------------------------------------------- /ecr/resources/image_push.sh: -------------------------------------------------------------------------------- 1 | REGION=$1 2 | IMAGE_NAME=$2 3 | REPO_URL=$3 4 | IMAGE_ID=`docker images $IMAGE_NAME -q` 5 | 6 | echo "REGION=$REGION" 7 | echo "IMAGE_NAME=$IMAGE_NAME" 8 | echo "REPO_URL=$REPO_URL" 9 | echo "IMAGE_ID=$IMAGE_ID" 10 | 11 | echo "Login to ECR..." 12 | eval $(aws ecr get-login --no-include-email --region $REGION) 13 | 14 | echo "Tagging image..." 15 | echo "running command: docker tag $IMAGE_ID $REPO_URL" 16 | docker tag $IMAGE_ID $REPO_URL 17 | 18 | echo "Pushing image..." 19 | # docker push $REPO_URL/$IMAGE_NAME 20 | docker push $REPO_URL 21 | -------------------------------------------------------------------------------- /ecr/resources/standalone-ha.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 129 | h2 130 | 131 | sa 132 | sa 133 | 134 | 135 | 136 | jdbc:postgresql://${env.DB_ADDR:postgres}:${env.DB_PORT:5432}/${env.DB_DATABASE:keycloak}${env.JDBC_PARAMS:} 137 | postgresql 138 | 139 | IdleConnections 140 | 141 | 142 | ${env.DB_USER:keycloak} 143 | ${env.DB_PASSWORD:password} 144 | 145 | 146 | SELECT 1 147 | true 148 | 60000 149 | 150 | 151 | 152 | 153 | org.h2.jdbcx.JdbcDataSource 154 | 155 | 156 | org.postgresql.xa.PGXADataSource 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | false 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | java:jboss/datasources/KeycloakDS 438 | 439 | CREATE TABLE IF NOT EXISTS jgroupsping ( 440 | own_addr VARCHAR(200) NOT NULL, 441 | cluster_name VARCHAR(200) NOT NULL, 442 | ping_data BYTEA DEFAULT NULL, 443 | PRIMARY KEY (own_addr, cluster_name) 444 | ) 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | auth 470 | 471 | 472 | classpath:${jboss.home.dir}/providers/* 473 | 474 | 475 | master 476 | 900 477 | 478 | 2592000 479 | true 480 | true 481 | ${env.KEYCLOAK_WELCOME_THEME:keycloak} 482 | ${env.KEYCLOAK_DEFAULT_THEME:keycloak} 483 | ${jboss.home.dir}/themes 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | jpa 497 | 498 | 499 | basic 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | default 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | ${keycloak.jta.lookup.provider:jboss} 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | ${keycloak.x509cert.lookup.provider:default} 539 | 540 | 541 | 542 | ${keycloak.hostname.provider:request} 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | 579 | 580 | 581 | 582 | 583 | 584 | 585 | 586 | 587 | 588 | 589 | 590 | 591 | 592 | 593 | 594 | 595 | 596 | 597 | 598 | 599 | 600 | 601 | 602 | 603 | 604 | 605 | 606 | 607 | 608 | 609 | 610 | 611 | 612 | 613 | 614 | 615 | 616 | 617 | 618 | 619 | 620 | 621 | 622 | 623 | 624 | 625 | 626 | 627 | 628 | 629 | 630 | 631 | 632 | 633 | 634 | 635 | 636 | 637 | 638 | 639 | 640 | 641 | 642 | 643 | 644 | 645 | 646 | 647 | 648 | 649 | 650 | 651 | 652 | 653 | 654 | 655 | 656 | 657 | 658 | 659 | 660 | 661 | 662 | 663 | 664 | 665 | 666 | 667 | 668 | 669 | 670 | -------------------------------------------------------------------------------- /ecr/variables.tf: -------------------------------------------------------------------------------- 1 | variable "ecr_repository_name" { 2 | description = "Name of the ECR Repository" 3 | default = "keycloak" 4 | } 5 | 6 | variable "docker_image_name" { 7 | description = "Name of the Docker Image" 8 | default = "keycloak-custom" 9 | } 10 | 11 | variable "docker_image_tag" { 12 | description = "The Version Tag for the Docker Image" 13 | default = "6.0.1" 14 | } 15 | 16 | variable "aws_region" {} 17 | -------------------------------------------------------------------------------- /ecs/main.tf: -------------------------------------------------------------------------------- 1 | resource "aws_ecs_cluster" "main" { 2 | name = "${var.ecs_cluster_name}" 3 | } 4 | 5 | data "template_file" "task_definition" { 6 | template = "${file("${path.module}/templates/task-definition.tpl")}" 7 | 8 | vars = { 9 | image_url = "${var.docker_image_url}" 10 | container_name = "${var.container_name}" 11 | log_group_region = "${var.aws_region}" 12 | log_group_name = "${var.app_log_group_name}" 13 | container_port = "${var.docker_container_port}" 14 | host_port = "${var.docker_host_port}" 15 | keycloak_admin_username = "${var.keycloak_admin_username}" 16 | keycloak_admin_password = "${var.keycloak_admin_password}" 17 | database_hostname = "${var.database_hostname}" 18 | database_port = "${var.database_port}" 19 | database_name = "${var.database_name}" 20 | database_username = "${var.database_username}" 21 | database_password = "${var.database_password}" 22 | 23 | } 24 | } 25 | 26 | resource "aws_ecs_task_definition" "main" { 27 | family = "${var.ecs_task_family}" 28 | container_definitions = "${data.template_file.task_definition.rendered}" 29 | } 30 | 31 | resource "aws_ecs_service" "main" { 32 | name = "ecs_service" 33 | cluster = "${aws_ecs_cluster.main.id}" 34 | task_definition = "${aws_ecs_task_definition.main.arn}" 35 | desired_count = "${var.ecs_desired_instances}" 36 | iam_role = "${var.ecs_iam_role_name}" 37 | 38 | load_balancer { 39 | target_group_arn = "${var.alb_target_group_arn}" 40 | container_name = "${var.container_name}" 41 | container_port = "${var.docker_container_port}" 42 | } 43 | 44 | depends_on = [ 45 | "var.alb_listener_front_end", 46 | "var.ecs_service_iam_role_policy" 47 | ] 48 | } 49 | 50 | resource "aws_appautoscaling_target" "ecs_auto_scaling_target" { 51 | min_capacity = 2 52 | max_capacity = 4 53 | resource_id = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.main.name}" 54 | role_arn = "${var.ecs_iam_role_arn}" 55 | scalable_dimension = "ecs:service:DesiredCount" 56 | service_namespace = "ecs" 57 | } 58 | 59 | resource "aws_appautoscaling_policy" "up" { 60 | name = "scale_up" 61 | service_namespace = "ecs" 62 | resource_id = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.main.name}" 63 | scalable_dimension = "ecs:service:DesiredCount" 64 | 65 | step_scaling_policy_configuration { 66 | adjustment_type = "ChangeInCapacity" 67 | cooldown = 60 68 | metric_aggregation_type = "Maximum" 69 | 70 | step_adjustment { 71 | metric_interval_lower_bound = 0 72 | scaling_adjustment = 1 73 | } 74 | } 75 | 76 | depends_on = ["aws_appautoscaling_target.ecs_auto_scaling_target"] 77 | } 78 | 79 | resource "aws_appautoscaling_policy" "down" { 80 | name = "scale_down" 81 | service_namespace = "ecs" 82 | resource_id = "service/${aws_ecs_cluster.main.name}/${aws_ecs_service.main.name}" 83 | scalable_dimension = "ecs:service:DesiredCount" 84 | 85 | step_scaling_policy_configuration { 86 | adjustment_type = "ChangeInCapacity" 87 | cooldown = 60 88 | metric_aggregation_type = "Maximum" 89 | 90 | step_adjustment { 91 | metric_interval_lower_bound = 0 92 | scaling_adjustment = -1 93 | } 94 | } 95 | 96 | depends_on = ["aws_appautoscaling_target.ecs_auto_scaling_target"] 97 | } 98 | 99 | resource "aws_cloudwatch_metric_alarm" "service_cpu_high" { 100 | alarm_name = "cpu_utilization_high" 101 | comparison_operator = "GreaterThanOrEqualToThreshold" 102 | evaluation_periods = "8" 103 | metric_name = "CPUUtilization" 104 | namespace = "AWS/ECS" 105 | period = "60" 106 | statistic = "Average" 107 | threshold = "85" 108 | 109 | dimensions = { 110 | ClusterName = "${aws_ecs_cluster.main.name}" 111 | ServiceName = "${aws_ecs_service.main.name}" 112 | } 113 | 114 | alarm_actions = ["${aws_appautoscaling_policy.up.arn}"] 115 | } 116 | 117 | # Cloudwatch alarm that triggers the autoscaling down policy 118 | resource "aws_cloudwatch_metric_alarm" "service_cpu_low" { 119 | alarm_name = "cpu_utilization_low" 120 | comparison_operator = "LessThanOrEqualToThreshold" 121 | evaluation_periods = "8" 122 | metric_name = "CPUUtilization" 123 | namespace = "AWS/ECS" 124 | period = "60" 125 | statistic = "Average" 126 | threshold = "10" 127 | 128 | dimensions = { 129 | ClusterName = "${aws_ecs_cluster.main.name}" 130 | ServiceName = "${aws_ecs_service.main.name}" 131 | } 132 | 133 | alarm_actions = ["${aws_appautoscaling_policy.down.arn}"] 134 | } -------------------------------------------------------------------------------- /ecs/outputs.tf: -------------------------------------------------------------------------------- 1 | output "ecs_container_name" { 2 | value = "${var.container_name}" 3 | } 4 | 5 | output "ecs_container_image" { 6 | value = "${var.docker_image_url}" 7 | } 8 | -------------------------------------------------------------------------------- /ecs/templates/task-definition.tpl: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "memory":1024, 4 | "networkMode":"awsvpc", 5 | "cpu":512, 6 | "family":"keycloak", 7 | "portMappings": [ 8 | { 9 | "hostPort": ${host_port}, 10 | "containerPort": ${container_port}, 11 | "protocol": "tcp" 12 | } 13 | ], 14 | "essential": true, 15 | "name": "${container_name}", 16 | "image": "${image_url}", 17 | "environment" : [ 18 | { "name" : "KEYCLOAK_USER", "value" : "${keycloak_admin_username}" }, 19 | { "name" : "KEYCLOAK_PASSWORD", "value" : "${keycloak_admin_password}" }, 20 | { "name" : "PROXY_ADDRESS_FORWARDING", "value" : "true" }, 21 | { "name" : "DB_VENDOR", "value" : "postgres" }, 22 | { "name" : "DB_ADDR", "value" : "${database_hostname}" }, 23 | { "name" : "DB_PORT", "value" : "${database_port}" }, 24 | { "name" : "DB_DATABASE", "value" : "${database_name}" }, 25 | { "name" : "DB_USER", "value" : "${database_username}" }, 26 | { "name" : "DB_PASSWORD", "value" : "${database_password}" } 27 | ], 28 | "logConfiguration": { 29 | "logDriver": "awslogs", 30 | "options": { 31 | "awslogs-group": "${log_group_name}", 32 | "awslogs-region": "${log_group_region}" 33 | } 34 | } 35 | } 36 | ] -------------------------------------------------------------------------------- /ecs/variables.tf: -------------------------------------------------------------------------------- 1 | variable "ecs_desired_instances" { 2 | description = "The desired number of instances for ECS" 3 | default = "1" 4 | } 5 | 6 | variable "container_name" { 7 | description = "The name of the ECS container" 8 | default = "keycloak" 9 | } 10 | 11 | variable "docker_image_url" {} 12 | 13 | variable "docker_container_port" { 14 | description = "The Docker container port" 15 | default = 8080 16 | } 17 | 18 | variable "docker_host_port" { 19 | description = "The Docker host port" 20 | default = 0 21 | } 22 | 23 | variable "ecs_cluster_name" {} 24 | 25 | variable "ecs_task_family" { 26 | description = "The ECS task family name" 27 | default = "keycloak_task_family" 28 | } 29 | 30 | variable "keycloak_admin_username" { 31 | description = "KeyCloak Admin Username" 32 | } 33 | 34 | variable "keycloak_admin_password" { 35 | description = "KeyCloak Admin Password" 36 | } 37 | 38 | variable "app_log_group_name" {} 39 | 40 | variable "aws_region" {} 41 | 42 | variable "ecs_iam_role_name" {} 43 | 44 | variable "ecs_iam_role_arn" {} 45 | 46 | variable "alb_target_group_arn" {} 47 | 48 | variable "ecs_service_iam_role_policy" {} 49 | 50 | variable "alb_listener_front_end" {} 51 | 52 | variable "database_hostname" {} 53 | 54 | variable "database_port" {} 55 | 56 | variable "database_name" {} 57 | 58 | variable "database_username" {} 59 | 60 | variable "database_password" {} 61 | -------------------------------------------------------------------------------- /iam/main.tf: -------------------------------------------------------------------------------- 1 | resource "aws_iam_role" "ecs_service" { 2 | name = "ecs_service_role" 3 | 4 | assume_role_policy = "${file("iam/resources/ecs_service_role.json")}" 5 | } 6 | 7 | resource "aws_iam_role_policy" "ecs_service" { 8 | name = "ecs_service_role_policy" 9 | role = "${aws_iam_role.ecs_service.name}" 10 | 11 | policy = "${file("iam/resources/ecs_service_role_policy.json")}" 12 | } 13 | 14 | resource "aws_iam_instance_profile" "app" { 15 | name = "ecs_app_instance_profile" 16 | role = "${aws_iam_role.app_instance.name}" 17 | } 18 | 19 | resource "aws_iam_role" "app_instance" { 20 | name = "ecs_app_instance_role" 21 | 22 | assume_role_policy = "${file("iam/resources/ecs_instance_role.json")}" 23 | } 24 | 25 | data "template_file" "instance_profile" { 26 | template = "${file("iam/templates/instance-profile-policy.tpl")}" 27 | 28 | vars = { 29 | app_log_group_arn = "${var.app_log_group_arn}" 30 | ecs_log_group_arn = "${var.ecs_log_group_arn}" 31 | } 32 | } 33 | 34 | resource "aws_iam_role_policy" "instance" { 35 | name = "ecs_instance_role_policy" 36 | role = "${aws_iam_role.app_instance.name}" 37 | policy = "${data.template_file.instance_profile.rendered}" 38 | } 39 | -------------------------------------------------------------------------------- /iam/outputs.tf: -------------------------------------------------------------------------------- 1 | output "app_iam_instance_profile_name" { 2 | value = "${aws_iam_instance_profile.app.name}" 3 | } 4 | 5 | output "ecs_iam_role_name" { 6 | value = "${aws_iam_role.ecs_service.name}" 7 | } 8 | 9 | output "ecs_iam_role_arm" { 10 | value = "${aws_iam_role.ecs_service.arn}" 11 | } 12 | 13 | output "ecs_service_iam_role_policy" { 14 | value = "${aws_iam_role.ecs_service.id}" 15 | } -------------------------------------------------------------------------------- /iam/resources/ecs_instance_role.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "", 6 | "Effect": "Allow", 7 | "Principal": { 8 | "Service": [ 9 | "ec2.amazonaws.com", 10 | "ecs.amazonaws.com" 11 | ] 12 | }, 13 | "Action": "sts:AssumeRole" 14 | } 15 | ] 16 | } -------------------------------------------------------------------------------- /iam/resources/ecs_service_role.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2008-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "", 6 | "Effect": "Allow", 7 | "Principal": { 8 | "Service": "ecs.amazonaws.com" 9 | }, 10 | "Action": "sts:AssumeRole" 11 | } 12 | ] 13 | } -------------------------------------------------------------------------------- /iam/resources/ecs_service_role_policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "ec2:Describe*", 8 | "elasticloadbalancing:DeregisterInstancesFromLoadBalancer", 9 | "elasticloadbalancing:DeregisterTargets", 10 | "elasticloadbalancing:Describe*", 11 | "elasticloadbalancing:RegisterInstancesWithLoadBalancer", 12 | "elasticloadbalancing:RegisterTargets" 13 | ], 14 | "Resource": "*" 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /iam/templates/instance-profile-policy.tpl: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Sid": "ecsInstanceRole", 6 | "Effect": "Allow", 7 | "Action": [ 8 | "ecs:DeregisterContainerInstance", 9 | "ecs:DiscoverPollEndpoint", 10 | "ecs:Poll", 11 | "ecs:RegisterContainerInstance", 12 | "ecs:Submit*", 13 | "ecs:StartTelemetrySession", 14 | "ecr:BatchCheckLayerAvailability", 15 | "ecr:BatchGetImage", 16 | "ecr:GetDownloadUrlForLayer", 17 | "ecr:GetAuthorizationToken" 18 | ], 19 | "Resource": [ 20 | "*" 21 | ] 22 | }, 23 | { 24 | "Sid": "allowLoggingToCloudWatch", 25 | "Effect": "Allow", 26 | "Action": [ 27 | "logs:CreateLogStream", 28 | "logs:PutLogEvents" 29 | ], 30 | "Resource": [ 31 | "${app_log_group_arn}", 32 | "${ecs_log_group_arn}" 33 | ] 34 | } 35 | ] 36 | } 37 | -------------------------------------------------------------------------------- /iam/variables.tf: -------------------------------------------------------------------------------- 1 | variable "app_log_group_arn" {} 2 | 3 | variable "ecs_log_group_arn" {} 4 | -------------------------------------------------------------------------------- /main.tf: -------------------------------------------------------------------------------- 1 | provider "aws" { 2 | region = "${var.aws_region}" 3 | } 4 | 5 | module "vpc" { 6 | source = "./vpc" 7 | 8 | admin_cidr_ingress = "${var.admin_cidr_ingress}" 9 | 10 | } 11 | 12 | module "cloudwatch" { 13 | source = "./cloudwatch" 14 | } 15 | 16 | module "iam" { 17 | source = "./iam" 18 | 19 | app_log_group_arn = "${module.cloudwatch.app_log_group_arn}" 20 | ecs_log_group_arn = "${module.cloudwatch.ecs_log_group_arn}" 21 | } 22 | 23 | module "ec2" { 24 | source = "./ec2" 25 | 26 | aws_region = "${var.aws_region}" 27 | key_name = "${var.key_name}" 28 | ecs_log_level = "${var.ecs_log_level}" 29 | ecs_cluster_name = "${var.ecs_cluster_name}" 30 | vpc_zone_identifier = "${module.vpc.vpc_zone_identifier}" 31 | app_iam_instance_profile_name = "${module.iam.app_iam_instance_profile_name}" 32 | instance_sg_id = "${module.vpc.instance_sg_id}" 33 | ecs_log_group_name = "${module.cloudwatch.ecs_log_group_name}" 34 | } 35 | 36 | module "alb" { 37 | source = "./alb" 38 | 39 | vpc_id = "${module.vpc.vpc_id}" 40 | subnet_ids = "${module.vpc.public_subnet_ids}" 41 | security_groups = "${module.vpc.security_groups}" 42 | certificate_arn = "${module.dns.acm_certificate_arn}" 43 | 44 | } 45 | 46 | module "rds" { 47 | source = "./rds" 48 | 49 | vpc_id = "${module.vpc.vpc_id}" 50 | public_subnet_ids = "${module.vpc.public_subnet_ids}" 51 | private_subnet_ids = "${module.vpc.private_subnet_ids}" 52 | public_subnet_cidr = "${module.vpc.public_subnet_cidr}" 53 | private_subnet_cidr = "${module.vpc.private_subnet_cidr}" 54 | instance_security_group = "${module.vpc.instance_sg_id}" 55 | } 56 | 57 | module "ecr" { 58 | source = "./ecr" 59 | 60 | aws_region = "${var.aws_region}" 61 | } 62 | 63 | module "ecs" { 64 | source = "./ecs" 65 | 66 | docker_image_url = "${module.ecr.ecr_repo_url}:latest" 67 | keycloak_admin_username = "${var.keycloak_admin_username}" 68 | keycloak_admin_password = "${var.keycloak_admin_password}" 69 | app_log_group_name = "${module.cloudwatch.app_log_group_name}" 70 | aws_region = "${var.aws_region}" 71 | ecs_iam_role_name = "${module.iam.ecs_iam_role_name}" 72 | ecs_iam_role_arn = "${module.iam.ecs_iam_role_arm}" 73 | alb_target_group_arn = "${module.alb.alb_target_group_arn}" 74 | ecs_cluster_name = "${var.ecs_cluster_name}" 75 | ecs_service_iam_role_policy = "${module.iam.ecs_service_iam_role_policy}" 76 | alb_listener_front_end = "${module.alb.alb_listener_front_end_tls}" 77 | 78 | database_hostname = "${module.rds.database_hostname}" 79 | database_port = "${module.rds.database_port}" 80 | database_name = "${module.rds.database_name}" 81 | database_username = "${module.rds.database_username}" 82 | database_password = "${module.rds.database_password}" 83 | } 84 | 85 | module "dns" { 86 | source = "./dns" 87 | 88 | zone_name = "${var.zone_name}" 89 | public_dns_name = "${var.public_dns_name}" 90 | alb_dns_name = "${module.alb.alb_dns_name}" 91 | alb_zone_id = "${module.alb.alb_zone}" 92 | } 93 | 94 | -------------------------------------------------------------------------------- /outputs.tf: -------------------------------------------------------------------------------- 1 | output "alb_public_dns" { 2 | value = "${module.alb.alb_dns_name}" 3 | } 4 | 5 | output "public_dns_name" { 6 | value = "${var.public_dns_name}" 7 | } 8 | 9 | output "ecr_repository_url" { 10 | value = "${module.ecr.ecr_repo_url}" 11 | } 12 | 13 | output "docker_image_name" { 14 | value = "${module.ecr.docker_image_name}" 15 | } 16 | -------------------------------------------------------------------------------- /rds/main.tf: -------------------------------------------------------------------------------- 1 | resource "aws_security_group" "keycloakdb_sg" { 2 | 3 | name = "keycloakdb_sg" 4 | description = "Security group for connecting to the KeyCloak database instance" 5 | 6 | vpc_id = "${var.vpc_id}" 7 | 8 | # Only PostgreSQL traffic inbound 9 | ingress { 10 | from_port = 5432 11 | to_port = 5432 12 | protocol = "tcp" 13 | security_groups = ["${var.instance_security_group}"] 14 | } 15 | 16 | # egress { 17 | # from_port = 80 18 | # to_port = 80 19 | # protocol = "tcp" 20 | # cidr_blocks = ["0.0.0.0/0"] 21 | # } 22 | 23 | egress { 24 | from_port = 443 25 | to_port = 443 26 | protocol = "tcp" 27 | cidr_blocks = ["0.0.0.0/0"] 28 | } 29 | } 30 | 31 | resource "aws_db_subnet_group" "main" { 32 | 33 | name = "keycloak_db_sng" 34 | subnet_ids = concat("${var.public_subnet_ids}", "${var.private_subnet_ids}") 35 | 36 | } 37 | resource "aws_db_instance" "keycloakdb" { 38 | 39 | allocated_storage = "${var.rds_storage_gigabytes}" 40 | backup_retention_period = "${var.rds_backup_retention_days}" 41 | 42 | db_subnet_group_name = "${aws_db_subnet_group.main.name}" 43 | 44 | engine = "${var.rds_engine}" 45 | engine_version = "${var.rds_engine_version}" 46 | multi_az = "${var.rds_multi_az}" 47 | instance_class = "${var.instance_type}" 48 | 49 | identifier = "${var.rds_name}" 50 | name = "${var.rds_name}" 51 | 52 | username = "${var.rds_username}" 53 | password = "${var.rds_password}" 54 | 55 | publicly_accessible = false 56 | storage_encrypted = true 57 | 58 | vpc_security_group_ids = ["${aws_security_group.keycloakdb_sg.id}"] 59 | 60 | skip_final_snapshot = true 61 | } 62 | -------------------------------------------------------------------------------- /rds/output.tf: -------------------------------------------------------------------------------- 1 | output "database_hostname" { 2 | value = "${aws_db_instance.keycloakdb.address}" 3 | } 4 | 5 | output "database_port" { 6 | value = "${aws_db_instance.keycloakdb.port}" 7 | } 8 | 9 | output "database_username" { 10 | value = "${var.rds_username}" 11 | } 12 | 13 | output "database_password" { 14 | value = "${var.rds_password}" 15 | } 16 | 17 | output "database_name" { 18 | value = "${aws_db_instance.keycloakdb.name}" 19 | } -------------------------------------------------------------------------------- /rds/variables.tf: -------------------------------------------------------------------------------- 1 | variable "instance_type" { 2 | description = "The RDS instance type" 3 | default = "db.t2.small" 4 | } 5 | 6 | variable "rds_engine" { 7 | description = "The RDS engine to use" 8 | default = "postgres" 9 | } 10 | 11 | variable "rds_engine_version" { 12 | default = "9.6.3" 13 | } 14 | 15 | variable "rds_username" { 16 | description = "The username for the RDS account" 17 | default = "rdsuser" 18 | } 19 | 20 | variable "rds_password" { 21 | description = "The password for the RDS account" 22 | default="Password123!" 23 | } 24 | 25 | variable "rds_storage_gigabytes" { 26 | description = "The amount of RDS storage to provision, in gigabytes" 27 | default = 10 28 | } 29 | 30 | variable "rds_multi_az" { 31 | description = "The RDS multi-availability zone flag" 32 | default = false 33 | } 34 | 35 | variable "rds_name" { 36 | description = "Name of the database" 37 | default = "keycloakdb" 38 | } 39 | 40 | variable "rds_backup_retention_days" { 41 | description = "RDS backup retention period, in days" 42 | default = 3 43 | } 44 | 45 | variable "vpc_id" {} 46 | 47 | variable "public_subnet_ids" {} 48 | 49 | variable "private_subnet_ids" {} 50 | 51 | variable "public_subnet_cidr" {} 52 | 53 | variable "private_subnet_cidr" {} 54 | 55 | variable "instance_security_group" {} 56 | -------------------------------------------------------------------------------- /variables.tf: -------------------------------------------------------------------------------- 1 | variable "aws_region" { 2 | description = "The AWS region for creating the infrastructure" 3 | default = "us-east-1" 4 | } 5 | 6 | variable "key_name" { 7 | description = "Name of the AWS key pair to use" 8 | } 9 | 10 | variable "ecs_cluster_name" { 11 | default = "ecs_cluster" 12 | } 13 | 14 | variable "ecs_log_level" { 15 | description = "The ECS log level" 16 | default = "info" 17 | } 18 | 19 | variable "admin_cidr_ingress" { 20 | 21 | } 22 | 23 | variable "keycloak_admin_username" { 24 | description = "KeyCloak Admin Username" 25 | } 26 | 27 | variable "keycloak_admin_password" { 28 | description = "KeyCloak Admin Password" 29 | } 30 | 31 | variable "public_dns_name" { 32 | description = "The public-facing DNS name" 33 | } 34 | 35 | variable "zone_name" { 36 | description = "The DNS zone name" 37 | } 38 | -------------------------------------------------------------------------------- /vpc/main.tf: -------------------------------------------------------------------------------- 1 | data "aws_availability_zones" "available" {} 2 | 3 | resource "aws_vpc" "primary_vpc" { 4 | cidr_block = "${var.vpc_cidr_block}" 5 | enable_dns_hostnames = true 6 | } 7 | 8 | resource "aws_subnet" "public" { 9 | count = "${var.availability_zone_count}" 10 | cidr_block = "${cidrsubnet(aws_vpc.primary_vpc.cidr_block, 8, count.index)}" 11 | availability_zone = "${data.aws_availability_zones.available.names[count.index]}" 12 | vpc_id = "${aws_vpc.primary_vpc.id}" 13 | 14 | tags = { 15 | Name = "Public Subnet" 16 | } 17 | } 18 | 19 | resource "aws_subnet" "private" { 20 | cidr_block = "${var.private_subnet_cidr_block}" 21 | availability_zone = "${data.aws_availability_zones.available.names[1]}" 22 | vpc_id = "${aws_vpc.primary_vpc.id}" 23 | 24 | tags = { 25 | Name = "Private Subnet" 26 | } 27 | } 28 | 29 | resource "aws_internet_gateway" "main" { 30 | vpc_id = "${aws_vpc.primary_vpc.id}" 31 | } 32 | 33 | resource "aws_route_table" "main" { 34 | vpc_id = "${aws_vpc.primary_vpc.id}" 35 | 36 | route { 37 | cidr_block = "0.0.0.0/0" 38 | gateway_id = "${aws_internet_gateway.main.id}" 39 | } 40 | } 41 | 42 | resource "aws_route_table_association" "main" { 43 | count = "${var.availability_zone_count}" 44 | subnet_id = "${element(aws_subnet.public.*.id, count.index)}" 45 | route_table_id = "${aws_route_table.main.id}" 46 | } 47 | 48 | resource "aws_security_group" "alb_sg" { 49 | description = "The security group used to grant access to the ALB" 50 | 51 | vpc_id = "${aws_vpc.primary_vpc.id}" 52 | 53 | # ingress { 54 | # protocol = "tcp" 55 | # from_port = 80 56 | # to_port = 80 57 | # cidr_blocks = ["0.0.0.0/0"] 58 | # } 59 | 60 | ingress { 61 | protocol = "tcp" 62 | from_port = 443 63 | to_port = 443 64 | cidr_blocks = ["0.0.0.0/0"] 65 | } 66 | 67 | egress { 68 | from_port = 0 69 | to_port = 0 70 | protocol = "-1" 71 | 72 | cidr_blocks = [ 73 | "0.0.0.0/0", 74 | ] 75 | } 76 | } 77 | 78 | resource "aws_security_group" "instance_sg" { 79 | description = "The security group allowing SSH administrative access to the instances" 80 | vpc_id = "${aws_vpc.primary_vpc.id}" 81 | 82 | ingress { 83 | protocol = "tcp" 84 | from_port = 22 85 | to_port = 22 86 | 87 | cidr_blocks = [ 88 | "${var.admin_cidr_ingress}", 89 | ] 90 | } 91 | 92 | ingress { 93 | protocol = "tcp" 94 | from_port = 32768 95 | to_port = 61000 96 | 97 | security_groups = [ 98 | "${aws_security_group.alb_sg.id}", 99 | ] 100 | } 101 | 102 | egress { 103 | from_port = 5432 104 | to_port = 5432 105 | protocol = "tcp" 106 | cidr_blocks = ["${aws_subnet.private.cidr_block}"] 107 | } 108 | 109 | egress { 110 | from_port = 0 111 | to_port = 0 112 | protocol = "-1" 113 | cidr_blocks = ["0.0.0.0/0"] 114 | } 115 | 116 | } 117 | -------------------------------------------------------------------------------- /vpc/outputs.tf: -------------------------------------------------------------------------------- 1 | # output "vpc_arn" { 2 | # value = "${aws_vpc.primary_vpc.vpc_arn}" 3 | # } 4 | 5 | output "vpc_id" { 6 | value = "${aws_vpc.primary_vpc.id}" 7 | } 8 | 9 | output "vpc_zone_identifier" { 10 | value = "${aws_subnet.public.*.id}" 11 | } 12 | 13 | output "instance_sg_id" { 14 | value = "${aws_security_group.instance_sg.id}" 15 | } 16 | 17 | output "public_subnet_ids" { 18 | value = "${aws_subnet.public.*.id}" 19 | } 20 | 21 | output "private_subnet_ids" { 22 | value = "${aws_subnet.private.*.id}" 23 | } 24 | 25 | output "public_subnet_cidr" { 26 | value = "${var.public_subnet_cidr_block}" 27 | } 28 | 29 | output "private_subnet_cidr" { 30 | value = "${var.private_subnet_cidr_block}" 31 | } 32 | 33 | output "security_groups" { 34 | value = ["${aws_security_group.alb_sg.id}"] 35 | } 36 | 37 | output "private_subnet_group_name" { 38 | value = "${aws_subnet.private}" 39 | } -------------------------------------------------------------------------------- /vpc/variables.tf: -------------------------------------------------------------------------------- 1 | variable "availability_zone_count" { 2 | description = "The number of availability zones to be leveraged within the VPC" 3 | default = "2" 4 | } 5 | 6 | variable "vpc_cidr_block" { 7 | description = "The CIDR block for the VPC to use" 8 | default = "10.0.0.0/16" 9 | } 10 | 11 | variable "public_subnet_cidr_block" { 12 | description = "The CIDR block for the public subnet within the VPC" 13 | default = "10.0.0.0/24" 14 | } 15 | 16 | variable "private_subnet_cidr_block" { 17 | description = "The CIDR block for the private subnet within the VPC" 18 | default = "10.0.10.0/24" 19 | } 20 | 21 | variable "admin_cidr_ingress" {} 22 | --------------------------------------------------------------------------------