├── LICENSE ├── README.md ├── base ├── README.md ├── ecr.tf ├── main.tf ├── state.tf └── variables.tf ├── diagram.png └── env └── dev ├── README.md ├── autoscale-perf.tf ├── autoscale-time.tf ├── cicd.tf ├── dashboard.tf ├── ecs-event-stream.tf ├── ecs.tf ├── fargate-create.yml ├── logs-logzio.tf ├── logs-logzio.zip ├── main.tf ├── nsg.tf ├── role.tf ├── secretsmanager.tf ├── ssm-parameters.tf └── variables.tf /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 2016 Turner Broadcasting System, Inc. 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Terraform ECS Fargate Background Worker 2 | 3 | A set of Terraform templates used for provisioning a background worker stack on [AWS ECS Fargate][fargate]. This template is similar to the [web app template](https://github.com/turnerlabs/terraform-ecs-fargate) but without the ALB. This means that you get an ECS service without ingress. 4 | 5 | ![diagram](diagram.png) 6 | 7 | The templates are designed to be customized. The optional components can be removed by simply deleting the `.tf` file. 8 | 9 | The templates are used for managing infrastructure concerns and, as such, the templates deploy a [default backend docker image](env/dev/ecs.tf#L26). We recommend using the [fargate CLI](https://github.com/turnerlabs/fargate) for managing application concerns like deploying your actual application images and environment variables on top of this infrastructure. The fargate CLI can be used to deploy applications from your laptop or in CI/CD pipelines. 10 | 11 | ## Components 12 | 13 | ### base 14 | 15 | These components are shared by all environments. 16 | 17 | | Name | Description | Optional | 18 | |------|-------------|:---:| 19 | | [main.tf][bm] | AWS provider, output | | 20 | | [state.tf][bs] | S3 bucket backend for storing Terraform remote state | | 21 | | [ecr.tf][be] | ECR repository for application (all environments share) | || 22 | 23 | 24 | ### env/dev 25 | 26 | These components are for a specific environment. There should be a corresponding directory for each environment 27 | that is needed. 28 | 29 | | Name | Description | Optional | 30 | |------|-------------|:----:| 31 | | [main.tf][edm] | Terrform remote state, AWS provider, output | | 32 | | [ecs.tf][ede] | ECS Cluster, Service, Task Definition, ecsTaskExecutionRole, CloudWatch Log Group | | 33 | | [nsg.tf][edn] | NSG for ALB and Task | | 34 | | [dashboard.tf][edd] | CloudWatch dashboard: CPU, memory metrics | Yes | 35 | | [role.tf][edr] | Application Role for container | Yes | 36 | | [cicd.tf][edc] | IAM user that can be used by CI/CD systems | Yes | 37 | | [autoscale-perf.tf][edap] | Performance-based auto scaling | Yes | 38 | | [autoscale-time.tf][edat] | Time-based auto scaling | Yes | 39 | | [logs-logzio.tf][edll] | Ship container logs to logz.io | Yes | 40 | | [secretsmanager.tf][sm] | Provision a Secrets Manager secret for your app | Yes | 41 | 42 | 43 | ## Usage 44 | 45 | Typically, the base Terraform will only need to be run once, and then should only 46 | need changes very infrequently. After the base is built, each environment can be built. 47 | 48 | ``` 49 | # Move into the base directory 50 | $ cd base 51 | 52 | # Sets up Terraform to run 53 | $ terraform init 54 | 55 | # Executes the Terraform run 56 | $ terraform apply 57 | 58 | # Now, move into the dev environment 59 | $ cd ../env/dev 60 | 61 | # Sets up Terraform to run 62 | $ terraform init 63 | 64 | # Executes the Terraform run 65 | $ terraform apply 66 | ``` 67 | 68 | ## fargate-create 69 | 70 | Alternatively you can use the [fargate-create CLI](https://github.com/turnerlabs/fargate-create) to scaffold new projects based on this template. 71 | 72 | install 73 | ```shell 74 | curl -s get-fargate-create.turnerlabs.io | sh 75 | ``` 76 | 77 | create an input vars file (`terraform.tfvars`) 78 | ```hcl 79 | # app/env to scaffold 80 | app = "my-app" 81 | environment = "dev" 82 | 83 | replicas = "1" 84 | region = "us-east-1" 85 | aws_profile = "default" 86 | saml_role = "admin" 87 | vpc = "vpc-123" 88 | private_subnets = "subnet-123,subnet-456" 89 | public_subnets = "subnet-789,subnet-012" 90 | tags = { 91 | application = "my-app" 92 | environment = "dev" 93 | team = "my-team" 94 | customer = "my-customer" 95 | contact-email = "me@example.com" 96 | } 97 | ``` 98 | 99 | ```shell 100 | $ fargate-create -t git@github.com:turnerlabs/terraform-ecs-fargate-background-worker 101 | ``` 102 | 103 | 104 | ## Additional Information 105 | 106 | + [Base README][base] 107 | 108 | + [Environment `dev` README][env-dev] 109 | 110 | 111 | 112 | [fargate]: https://aws.amazon.com/fargate/ 113 | [bm]: ./base/main.tf 114 | [bs]: ./base/state.tf 115 | [be]: ./base/ecr.tf 116 | [edm]: ./env/dev/main.tf 117 | [ede]: ./env/dev/ecs.tf 118 | [edn]: ./env/dev/nsg.tf 119 | [edd]: ./env/dev/dashboard.tf 120 | [edr]: ./env/dev/role.tf 121 | [edc]: ./env/dev/cicd.tf 122 | [edap]: ./env/dev/autoscale-perf.tf 123 | [edat]: ./env/dev/autoscale-time.tf 124 | [edll]: ./env/dev/logs-logzio.tf 125 | [sm]: ./env/dev/secretsmanager.tf 126 | [base]: ./base/README.md 127 | [env-dev]: ./env/dev/README.md 128 | -------------------------------------------------------------------------------- /base/README.md: -------------------------------------------------------------------------------- 1 | # Base Terraform 2 | 3 | Creates the foundational infrastructure for the application's infrastructure. 4 | These Terraform files will create a [remote state][state] and a [registry][ecr]. 5 | Most other infrastructure pieces will be created within the `environments` directory. 6 | 7 | 8 | ## Included Files 9 | 10 | + `main.tf` 11 | The main entry point for the Terraform run. 12 | 13 | + `variables.tf` 14 | Common variables to use in various Terraform files. 15 | 16 | + `state.tf` 17 | Generate a [remote state][state] bucket in S3 for use with later Terraform runs. 18 | 19 | + `ecr.tf` 20 | Creates an AWS [Elastic Container Registry (ECR)][ecr] for the application. 21 | 22 | 23 | ## Usage 24 | 25 | Typically, the base Terraform will only need to be run once, and then should only 26 | need changes very infrequently. 27 | 28 | ``` 29 | # Sets up Terraform to run 30 | $ terraform init 31 | 32 | # Executes the Terraform run 33 | $ terraform apply 34 | ``` 35 | 36 | 37 | ## Variables 38 | 39 | | Name | Description | Type | Default | Required | 40 | |------|-------------|:----:|:-----:|:-----:| 41 | | app | Name of the application. This value should usually match the application tag below. | string | | yes | 42 | | aws_profile | The AWS profile to use, this would be the same value used in AWS_PROFILE. | string | | yes | 43 | | image_tag_mutability | The tag mutability setting for the repository. | string | IMMUTABLE | | 44 | | region | The AWS region to use for the bucket and registry; typically `us-east-1`. Other possible values: `us-east-2`, `us-west-1`, or `us-west-2`.
Currently, Fargate is only available in `us-east-1`. | string | `us-east-1` | | 45 | | saml_role | The role that will have access to the S3 bucket, this should be a role that all members of the team have access to. | string | | yes | 46 | | tags | A map of the tags to apply to various resources. The required tags are:
+ `application`, name of the app
+ `environment`, the environment being created
+ `team`, team responsible for the application
+ `contact-email`, contact email for the _team_
+ `customer`, who the application was create for | map | `` | yes | 47 | 48 | 49 | ## Outputs 50 | 51 | | Name | Description | 52 | |------|-------------| 53 | | bucket | Returns the name of the S3 bucket that will be used in later Terraform files | 54 | | docker_registry | Returns the name of the ECR registry, this will be used later in various scripts | 55 | 56 | 57 | ## Additional Information 58 | 59 | + [Terraform remote state][state] 60 | 61 | + [Terraform providers][provider] 62 | 63 | + [AWS ECR][ecr] 64 | 65 | 66 | 67 | [state]: https://www.terraform.io/docs/state/remote.html 68 | [provider]: https://www.terraform.io/docs/providers/ 69 | [ecr]: https://aws.amazon.com/ecr/ 70 | -------------------------------------------------------------------------------- /base/ecr.tf: -------------------------------------------------------------------------------- 1 | /* 2 | * ecr.tf 3 | * Creates a Amazon Elastic Container Registry (ECR) for the application 4 | * https://aws.amazon.com/ecr/ 5 | */ 6 | 7 | # The tag mutability setting for the repository (defaults to IMMUTABLE) 8 | variable "image_tag_mutability" { 9 | type = string 10 | default = "IMMUTABLE" 11 | description = "The tag mutability setting for the repository (defaults to IMMUTABLE)" 12 | } 13 | 14 | # create an ECR repo at the app/image level 15 | resource "aws_ecr_repository" "app" { 16 | name = var.app 17 | image_tag_mutability = var.image_tag_mutability 18 | } 19 | 20 | data "aws_caller_identity" "current" { 21 | } 22 | 23 | # grant access to saml users 24 | resource "aws_ecr_repository_policy" "app" { 25 | repository = aws_ecr_repository.app.name 26 | policy = data.aws_iam_policy_document.ecr.json 27 | } 28 | 29 | data "aws_iam_policy_document" "ecr" { 30 | statement { 31 | actions = [ 32 | "ecr:GetDownloadUrlForLayer", 33 | "ecr:BatchGetImage", 34 | "ecr:BatchCheckLayerAvailability", 35 | "ecr:PutImage", 36 | "ecr:InitiateLayerUpload", 37 | "ecr:UploadLayerPart", 38 | "ecr:CompleteLayerUpload", 39 | "ecr:DescribeRepositories", 40 | "ecr:GetRepositoryPolicy", 41 | "ecr:ListImages", 42 | "ecr:DescribeImages", 43 | "ecr:DeleteRepository", 44 | "ecr:BatchDeleteImage", 45 | "ecr:SetRepositoryPolicy", 46 | "ecr:DeleteRepositoryPolicy", 47 | "ecr:GetLifecyclePolicy", 48 | "ecr:PutLifecyclePolicy", 49 | "ecr:DeleteLifecyclePolicy", 50 | "ecr:GetLifecyclePolicyPreview", 51 | "ecr:StartLifecyclePolicyPreview", 52 | ] 53 | 54 | principals { 55 | type = "AWS" 56 | 57 | # Add the saml roles for every member on the "team" 58 | identifiers = [ 59 | "arn:aws:sts::${data.aws_caller_identity.current.account_id}:assumed-role/${var.saml_role}/me@example.com", 60 | ] 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /base/main.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_version = ">= 0.12" 3 | } 4 | 5 | /** 6 | * main.tf 7 | * The main entry point for Terraform run 8 | * See variables.tf for common variables 9 | * See ecr.tf for creation of Elastic Container Registry for all environments 10 | * See state.tf for creation of S3 bucket for remote state 11 | */ 12 | 13 | # Using the AWS Provider 14 | # https://www.terraform.io/docs/providers/ 15 | provider "aws" { 16 | version = ">= 2.23.0" 17 | region = var.region 18 | profile = var.aws_profile 19 | } 20 | 21 | /* 22 | * Outputs 23 | * Results from a successful Terraform run (terraform apply) 24 | * To see results after a successful run, use `terraform output [name]` 25 | */ 26 | 27 | # Returns the name of the ECR registry, this will be used later in various scripts 28 | output "docker_registry" { 29 | value = aws_ecr_repository.app.repository_url 30 | } 31 | 32 | # Returns the name of the S3 bucket that will be used in later Terraform files 33 | output "bucket" { 34 | value = module.tf_remote_state.bucket 35 | } 36 | -------------------------------------------------------------------------------- /base/state.tf: -------------------------------------------------------------------------------- 1 | /* 2 | * state.tf 3 | * Generate a remote state bucket in S3 for use with later Terraform run 4 | * Uses a Turner created Terrafor module; more information at: 5 | * https://github.com/turnerlabs/terraform-remote-state/blob/master/readme.md 6 | * 7 | * To learn more about remote state: 8 | * https://www.terraform.io/docs/state/remote.html 9 | */ 10 | 11 | # s3 bucket for tf remote state 12 | module "tf_remote_state" { 13 | source = "github.com/turnerlabs/terraform-remote-state?ref=v2.2.0" 14 | 15 | role = var.saml_role 16 | application = var.app 17 | tags = var.tags 18 | } 19 | -------------------------------------------------------------------------------- /base/variables.tf: -------------------------------------------------------------------------------- 1 | /* 2 | * variables.tf 3 | * Common variables to use in various Terraform files (*.tf) 4 | */ 5 | 6 | # The AWS region to use for the bucket and registry; typically `us-east-1`. 7 | # Other possible values: `us-east-2`, `us-west-1`, or `us-west-2`. 8 | # Currently, Fargate is only available in `us-east-1`. 9 | variable "region" { 10 | default = "us-east-1" 11 | } 12 | 13 | # The AWS profile to use, this would be the same value used in AWS_PROFILE. 14 | variable "aws_profile" { 15 | } 16 | 17 | # The role that will have access to the S3 bucket, this should be a role that all 18 | # members of the team have access to. 19 | variable "saml_role" { 20 | } 21 | 22 | # Name of the application. This value should usually match the application tag below. 23 | variable "app" { 24 | } 25 | 26 | # A map of the tags to apply to various resources. The required tags are: 27 | # `application`, name of the app; 28 | # `environment`, the environment being created; 29 | # `team`, team responsible for the application; 30 | # `contact-email`, contact email for the _team_; 31 | # and `customer`, who the application was create for. 32 | variable "tags" { 33 | type = map(string) 34 | } 35 | -------------------------------------------------------------------------------- /diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/turnerlabs/terraform-ecs-fargate-background-worker/c2dd073ce3285cec3480d282a0b09c5c49e26891/diagram.png -------------------------------------------------------------------------------- /env/dev/README.md: -------------------------------------------------------------------------------- 1 | # Environment Dev Terraform 2 | 3 | Creates the dev environment's infrastructure. These templates are designed to be customized. 4 | The optional components can be removed by simply deleting the `.tf` file. 5 | 6 | 7 | ## Components 8 | 9 | | Name | Description | Optional | 10 | |------|-------------|:----:| 11 | | [main.tf][edm] | Terrform remote state, AWS provider, output | | 12 | | [ecs.tf][ede] | ECS Cluster, Service, Task Definition, ecsTaskExecutionRole, CloudWatch Log Group | | 13 | | [nsg.tf][edn] | NSG for ALB and Task | | 14 | | [dashboard.tf][edd] | CloudWatch dashboard: CPU, memory, and HTTP-related metrics | Yes | 15 | | [role.tf][edr] | Application Role for container | Yes | 16 | | [cicd.tf][edc] | IAM user that can be used by CI/CD systems | Yes | 17 | | [autoscale-perf.tf][edap] | Performance-based auto scaling | Yes | 18 | | [autoscale-time.tf][edat] | Time-based auto scaling | Yes | 19 | | [logs-logzio.tf][edll] | Ship container logs to logz.io | Yes | 20 | | [secretsmanager.tf][sm] | Provision a Secrets Manager secret for your app | Yes | 21 | | [ssm-parameters.tf][ssm] | Add a CMK KMS key for use with SSM Parameter Store. Also gives ECS task definition role access to read secrets from parameter store. | Yes | 22 | 23 | 24 | ## Usage 25 | 26 | ``` 27 | # Sets up Terraform to run 28 | $ terraform init 29 | 30 | # Executes the Terraform run 31 | $ terraform apply 32 | ``` 33 | 34 | 35 | ## Inputs 36 | 37 | | Name | Description | Type | Default | Required | 38 | |------|-------------|:----:|:-----:|:-----:| 39 | | app | The application's name | string | - | yes | 40 | | aws_profile | The AWS Profile to use | string | - | yes | 41 | | container_name | The name of the container to run | string | `app` | no | 42 | | default_backend_image | The default docker image to deploy with the infrastructure. Note that you can use the fargate CLI for application concerns like deploying actual application images and environment variables on top of the infrastructure provisioned by this template https://github.com/turnerlabs/fargate note that the source for the turner default backend image is here: https://github.com/turnerlabs/turner-defaultbackend | string | `quay.io/turner/turner-defaultbackend:0.2.0` | no | 43 | | ecs_as_cpu_high_threshold_per | If the average CPU utilization over a minute rises to this threshold, the number of containers will be increased (but not above ecs_autoscale_max_instances). | string | `80` | no | 44 | | ecs_as_cpu_low_threshold_per | If the average CPU utilization over a minute drops to this threshold, the number of containers will be reduced (but not below ecs_autoscale_min_instances). | string | `20` | no | 45 | | ecs_autoscale_max_instances | The maximum number of containers that should be running. | string | `8` | no | 46 | | ecs_autoscale_min_instances | The minimum number of containers that should be running. Must be at least 1. For production, consider using at least "2". | string | `1` | no | 47 | | environment | The environment that is being built | string | - | yes | 48 | | logz_token | The auth token to use for sending logs to Logz.io | string | - | yes | 49 | | logz_url | The endpoint to use for sending logs to Logz.io | string | `https://listener.logz.io:8071` | no | 50 | | private_subnets | The private subnets, minimum of 2, that are a part of the VPC(s) | string | - | yes | 51 | | public_subnets | The public subnets, minimum of 2, that are a part of the VPC(s) | string | - | yes | 52 | | region | The AWS region to use for the dev environment's infrastructure Currently, Fargate is only available in `us-east-1`. | string | `us-east-1` | no | 53 | | replicas | How many containers to run | string | `1` | no | 54 | | saml_role | The SAML role to use for adding users to the ECR policy | string | - | yes | 55 | | scale_down_cron | Default scale down at 7 pm every day | string | `cron(0 23 * * ? *)` | no | 56 | | scale_down_max_capacity | The maximum number of containers to scale down to. | string | `0` | no | 57 | | scale_down_min_capacity | The mimimum number of containers to scale down to. Set this and `scale_down_max_capacity` to 0 to turn off service on the `scale_down_cron` schedule. | string | `0` | no | 58 | | scale_up_cron | Default scale up at 7 am weekdays, this is UTC so it doesn't adjust to daylight savings https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html | string | `cron(0 11 ? * MON-FRI *)` | no | 59 | | secrets_saml_users | The users (email addresses) from the saml role to give access | list | - | yes | 60 | | tags | Tags for the infrastructure | map | - | yes | 61 | | vpc | The VPC to use for the Fargate cluster | string | - | yes | 62 | 63 | ## Outputs 64 | 65 | | Name | Description | 66 | |------|-------------| 67 | | aws_profile | Command to set the AWS_PROFILE | 68 | | cicd_keys | The AWS keys for the CICD user to use in a build system | 69 | | deploy | Command to deploy a new task definition to the service using Docker Compose | 70 | | docker_registry | The URL for the docker image repo in ECR | 71 | | scale_out | Command to scale out the number of tasks (container replicas) | 72 | | scale_up | Command to scale up cpu and memory | 73 | | status | Command to view the status of the Fargate service | 74 | 75 | 76 | 77 | [edm]: main.tf 78 | [ede]: ecs.tf 79 | [edn]: nsg.tf 80 | [edd]: dashboard.tf 81 | [edr]: role.tf 82 | [edc]: cicd.tf 83 | [edap]: autoscale-perf.tf 84 | [edat]: autoscale-time.tf 85 | [edll]: logs-logzio.tf 86 | [sm]: ./env/dev/secretsmanager.tf 87 | [alb-docs]: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html 88 | [up]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html 89 | -------------------------------------------------------------------------------- /env/dev/autoscale-perf.tf: -------------------------------------------------------------------------------- 1 | /** 2 | * This module sets up CPU-based autoscaling. The number of containers 3 | * is kept strictly within the range you specify. Within that range, 4 | * the number is gradually increased or decreased to keep CPU utilization 5 | * within its own range. If your app is CPU-bound, the number of 6 | * instances will autoscale with your traffic. 7 | * 8 | * The adjustments are gradual. If you expect a sudden surge of 9 | * traffic for a scheduled event (such as sporting events or elections), 10 | * set the `ecs_autoscale_min_instances` variable to a higher number. 11 | * `ecs_autoscale_max_instances` might also need to be increased, because 12 | * it should never be below ecs_autoscale_min_instances. 13 | * 14 | * To effectively disable autoscaling, set `ecs_autoscale_min_instances` 15 | * and `ecs_autoscale_max_instances` to the same number (your desired 16 | * number of containers). 17 | * 18 | * Note the default value of `ecs_autoscale_min_instances` is 1. For 19 | * production, consider using a higher number. 20 | * 21 | * There should be a [considerable gap](https://en.wikipedia.org/wiki/Deadband) between 22 | * `ecs_as_cpu_low_threshold_per` and 23 | * `ecs_as_cpu_high_threshold_per` so that the number of 24 | * containers is not continually being autoscaled up and down. If 25 | * `ecs_autoscale_min_instances==1`, then 26 | * `ecs_as_cpu_high_threshold_per` should be more than 27 | * twice ecs_as_cpu_low_threshold_per`. 28 | * 29 | * In the CloudWatch section of the AWS Console, you will often see the 30 | * alarms created by this module in an ALARM state, which are displayed in 31 | * red. This is normal and does not indicate a problem. 32 | * On the page listing all the alarms, click the checkbox labelled 33 | * "Hide all AutoScaling alarms". 34 | * 35 | */ 36 | 37 | # If the average CPU utilization over a minute drops to this threshold, 38 | # the number of containers will be reduced (but not below ecs_autoscale_min_instances). 39 | variable "ecs_as_cpu_low_threshold_per" { 40 | default = "20" 41 | } 42 | 43 | # If the average CPU utilization over a minute rises to this threshold, 44 | # the number of containers will be increased (but not above ecs_autoscale_max_instances). 45 | variable "ecs_as_cpu_high_threshold_per" { 46 | default = "80" 47 | } 48 | 49 | resource "aws_cloudwatch_metric_alarm" "cpu_utilization_high" { 50 | alarm_name = "${var.app}-${var.environment}-CPU-Utilization-High-${var.ecs_as_cpu_high_threshold_per}" 51 | comparison_operator = "GreaterThanOrEqualToThreshold" 52 | evaluation_periods = "1" 53 | metric_name = "CPUUtilization" 54 | namespace = "AWS/ECS" 55 | period = "60" 56 | statistic = "Average" 57 | threshold = var.ecs_as_cpu_high_threshold_per 58 | 59 | dimensions = { 60 | ClusterName = aws_ecs_cluster.app.name 61 | ServiceName = aws_ecs_service.app.name 62 | } 63 | 64 | alarm_actions = [aws_appautoscaling_policy.app_up.arn] 65 | } 66 | 67 | resource "aws_cloudwatch_metric_alarm" "cpu_utilization_low" { 68 | alarm_name = "${var.app}-${var.environment}-CPU-Utilization-Low-${var.ecs_as_cpu_low_threshold_per}" 69 | comparison_operator = "LessThanThreshold" 70 | evaluation_periods = "1" 71 | metric_name = "CPUUtilization" 72 | namespace = "AWS/ECS" 73 | period = "60" 74 | statistic = "Average" 75 | threshold = var.ecs_as_cpu_low_threshold_per 76 | 77 | dimensions = { 78 | ClusterName = aws_ecs_cluster.app.name 79 | ServiceName = aws_ecs_service.app.name 80 | } 81 | 82 | alarm_actions = [aws_appautoscaling_policy.app_down.arn] 83 | } 84 | 85 | resource "aws_appautoscaling_policy" "app_up" { 86 | name = "app-scale-up" 87 | service_namespace = aws_appautoscaling_target.app_scale_target.service_namespace 88 | resource_id = aws_appautoscaling_target.app_scale_target.resource_id 89 | scalable_dimension = aws_appautoscaling_target.app_scale_target.scalable_dimension 90 | 91 | step_scaling_policy_configuration { 92 | adjustment_type = "ChangeInCapacity" 93 | cooldown = 60 94 | metric_aggregation_type = "Average" 95 | 96 | step_adjustment { 97 | metric_interval_lower_bound = 0 98 | scaling_adjustment = 1 99 | } 100 | } 101 | } 102 | 103 | resource "aws_appautoscaling_policy" "app_down" { 104 | name = "app-scale-down" 105 | service_namespace = aws_appautoscaling_target.app_scale_target.service_namespace 106 | resource_id = aws_appautoscaling_target.app_scale_target.resource_id 107 | scalable_dimension = aws_appautoscaling_target.app_scale_target.scalable_dimension 108 | 109 | step_scaling_policy_configuration { 110 | adjustment_type = "ChangeInCapacity" 111 | cooldown = 300 112 | metric_aggregation_type = "Average" 113 | 114 | step_adjustment { 115 | metric_interval_upper_bound = 0 116 | scaling_adjustment = -1 117 | } 118 | } 119 | } 120 | 121 | -------------------------------------------------------------------------------- /env/dev/autoscale-time.tf: -------------------------------------------------------------------------------- 1 | /** 2 | * This module sets up time-based autoscaling. 3 | * This could be used to turn off a service durning non-business hours. 4 | */ 5 | 6 | # Default scale up at 7 am weekdays, this is UTC so it doesn't adjust to daylight savings 7 | # https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html 8 | variable "scale_up_cron" { 9 | default = "cron(0 11 ? * MON-FRI *)" 10 | } 11 | 12 | # Default scale down at 7 pm every day 13 | variable "scale_down_cron" { 14 | default = "cron(0 23 * * ? *)" 15 | } 16 | 17 | # The mimimum number of containers to scale down to. 18 | # Set this and `scale_down_max_capacity` to 0 to turn off service on the `scale_down_cron` schedule. 19 | variable "scale_down_min_capacity" { 20 | default = 0 21 | } 22 | 23 | # The maximum number of containers to scale down to. 24 | variable "scale_down_max_capacity" { 25 | default = 0 26 | } 27 | 28 | # Scales service back up to preferred running capacity defined by the 29 | # `ecs_autoscale_min_instances` and `ecs_autoscale_max_instances` variables 30 | resource "aws_appautoscaling_scheduled_action" "app_autoscale_time_up" { 31 | name = "app-autoscale-time-up-${var.app}-${var.environment}" 32 | 33 | service_namespace = aws_appautoscaling_target.app_scale_target.service_namespace 34 | resource_id = aws_appautoscaling_target.app_scale_target.resource_id 35 | scalable_dimension = aws_appautoscaling_target.app_scale_target.scalable_dimension 36 | schedule = var.scale_up_cron 37 | 38 | scalable_target_action { 39 | min_capacity = aws_appautoscaling_target.app_scale_target.min_capacity 40 | max_capacity = aws_appautoscaling_target.app_scale_target.max_capacity 41 | } 42 | } 43 | 44 | # Scales service down to capacity defined by the 45 | # `scale_down_min_capacity` and `scale_down_max_capacity` variables. 46 | resource "aws_appautoscaling_scheduled_action" "app_autoscale_time_down" { 47 | name = "app-autoscale-time-down-${var.app}-${var.environment}" 48 | 49 | service_namespace = aws_appautoscaling_target.app_scale_target.service_namespace 50 | resource_id = aws_appautoscaling_target.app_scale_target.resource_id 51 | scalable_dimension = aws_appautoscaling_target.app_scale_target.scalable_dimension 52 | schedule = var.scale_down_cron 53 | 54 | scalable_target_action { 55 | min_capacity = var.scale_down_min_capacity 56 | max_capacity = var.scale_down_max_capacity 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /env/dev/cicd.tf: -------------------------------------------------------------------------------- 1 | # create ci/cd user with access keys (for build system) 2 | resource "aws_iam_user" "cicd" { 3 | name = "srv_${var.app}_${var.environment}_cicd" 4 | } 5 | 6 | resource "aws_iam_access_key" "cicd_keys" { 7 | user = aws_iam_user.cicd.name 8 | } 9 | 10 | # grant required permissions to deploy 11 | data "aws_iam_policy_document" "cicd_policy" { 12 | # allows user to push/pull to the registry 13 | statement { 14 | sid = "ecr" 15 | 16 | actions = [ 17 | "ecr:GetDownloadUrlForLayer", 18 | "ecr:BatchGetImage", 19 | "ecr:BatchCheckLayerAvailability", 20 | "ecr:PutImage", 21 | "ecr:InitiateLayerUpload", 22 | "ecr:UploadLayerPart", 23 | "ecr:CompleteLayerUpload", 24 | ] 25 | 26 | resources = [ 27 | data.aws_ecr_repository.ecr.arn, 28 | ] 29 | } 30 | 31 | # allows user to deploy to ecs 32 | statement { 33 | sid = "ecs" 34 | 35 | actions = [ 36 | "ecr:GetAuthorizationToken", 37 | "ecs:DescribeServices", 38 | "ecs:DescribeTaskDefinition", 39 | "ecs:UpdateService", 40 | "ecs:RegisterTaskDefinition", 41 | ] 42 | 43 | resources = [ 44 | "*", 45 | ] 46 | } 47 | 48 | # allows user to run ecs task using task execution and app roles 49 | statement { 50 | sid = "approle" 51 | 52 | actions = [ 53 | "iam:PassRole", 54 | ] 55 | 56 | resources = [ 57 | aws_iam_role.app_role.arn, 58 | aws_iam_role.ecsTaskExecutionRole.arn, 59 | ] 60 | } 61 | } 62 | 63 | resource "aws_iam_user_policy" "cicd_user_policy" { 64 | name = "${var.app}_${var.environment}_cicd" 65 | user = aws_iam_user.cicd.name 66 | policy = data.aws_iam_policy_document.cicd_policy.json 67 | } 68 | 69 | data "aws_ecr_repository" "ecr" { 70 | name = var.app 71 | } 72 | 73 | # The AWS keys for the CICD user to use in a build system 74 | output "cicd_keys" { 75 | value = "terraform state show aws_iam_access_key.cicd_keys" 76 | } 77 | 78 | # The URL for the docker image repo in ECR 79 | output "docker_registry" { 80 | value = data.aws_ecr_repository.ecr.repository_url 81 | } 82 | 83 | -------------------------------------------------------------------------------- /env/dev/dashboard.tf: -------------------------------------------------------------------------------- 1 | /** 2 | * This module creates a CloudWatch dashboard for you app, 3 | * showing its CPU and memory utilization. 4 | */ 5 | 6 | resource "aws_cloudwatch_dashboard" "cloudwatch_dashboard" { 7 | dashboard_name = "${var.app}-${var.environment}-fargate" 8 | 9 | dashboard_body = < { 34 | console.log(JSON.stringify(event)); 35 | } 36 | EOF 37 | 38 | } 39 | 40 | data "archive_file" "lambda_zip" { 41 | type = "zip" 42 | source_content = data.template_file.lambda_source.rendered 43 | source_content_filename = "index.js" 44 | output_path = "lambda-${var.app}.zip" 45 | } 46 | 47 | resource "aws_lambda_permission" "ecs_event_stream" { 48 | statement_id = "AllowExecutionFromCloudWatch" 49 | action = "lambda:InvokeFunction" 50 | function_name = aws_lambda_function.ecs_event_stream.arn 51 | principal = "events.amazonaws.com" 52 | source_arn = aws_cloudwatch_event_rule.ecs_event_stream.arn 53 | } 54 | 55 | resource "aws_lambda_function" "ecs_event_stream" { 56 | function_name = "${var.app}-${var.environment}-ecs-event-stream" 57 | role = aws_iam_role.ecs_event_stream.arn 58 | filename = data.archive_file.lambda_zip.output_path 59 | source_code_hash = data.archive_file.lambda_zip.output_base64sha256 60 | handler = "index.handler" 61 | runtime = "nodejs8.10" 62 | tags = var.tags 63 | } 64 | 65 | resource "aws_lambda_alias" "ecs_event_stream" { 66 | name = aws_lambda_function.ecs_event_stream.function_name 67 | description = "latest" 68 | function_name = aws_lambda_function.ecs_event_stream.function_name 69 | function_version = "$LATEST" 70 | } 71 | 72 | resource "aws_iam_role" "ecs_event_stream" { 73 | name = aws_cloudwatch_event_rule.ecs_event_stream.name 74 | 75 | assume_role_policy = <