├── .gitignore ├── LICENSE ├── README.md ├── base ├── README.md ├── ecr.tf ├── main.tf ├── state.tf └── variables.tf ├── diagram.png └── env └── dev ├── README.md ├── 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 /.gitignore: -------------------------------------------------------------------------------- 1 | .terraform 2 | terraform.d 3 | node_modules 4 | terraform.tfstate* 5 | terraform.tfvars -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 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 Scheduled Task 2 | 3 | A set of Terraform templates used for provisioning scheduled tasks on [AWS ECS Fargate](https://aws.amazon.com/fargate/). 4 | 5 | ECS Scheduled Tasks use CloudWatch Event Rules to run Fargate containers. 6 | 7 | ![diagram](diagram.png) 8 | 9 | The templates are designed to be customized. The optional components can be removed by simply deleting the `.tf` file. 10 | 11 | The templates are used for managing infrastructure concerns and, as such, the templates deploy a [hello-world 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. 12 | 13 | ## Components 14 | 15 | ### base 16 | 17 | These components are shared by all environments. 18 | 19 | | Name | Description | Optional | 20 | |------|-------------|:---:| 21 | | [main.tf][bm] | AWS provider, output | | 22 | | [state.tf][bs] | S3 bucket backend for storing Terraform remote state | | 23 | | [ecr.tf][be] | ECR repository for application (all environments share) | || 24 | 25 | 26 | ### env/dev 27 | 28 | These components are for a specific environment. There should be a corresponding directory for each environment 29 | that is needed. 30 | 31 | | Name | Description | Optional | 32 | |------|-------------|:----:| 33 | | [main.tf][edm] | Terrform remote state, AWS provider, output | | 34 | | [ecs.tf][ede] | ECS Cluster, Service, Task Definition, ecsTaskExecutionRole, CloudWatch Log Group | | 35 | | [nsg.tf][edn] | NSG for Task | | 36 | | [role.tf][edr] | Application Role for container | Yes | 37 | | [cicd.tf][edc] | IAM user that can be used by CI/CD systems | Yes | 38 | | [logs-logzio.tf][edll] | Ship container logs to logz.io | Yes | 39 | | [secretsmanager.tf][edsm] | Add a base secret to Secretsmanager | Yes | 40 | 41 | 42 | ## Usage 43 | 44 | Typically, the base Terraform will only need to be run once, and then should only 45 | need changes very infrequently. After the base is built, each environment can be built. 46 | 47 | ``` 48 | # Move into the base directory 49 | $ cd base 50 | 51 | # Sets up Terraform to run 52 | $ terraform init 53 | 54 | # Executes the Terraform run 55 | $ terraform apply 56 | 57 | # Now, move into the dev environment 58 | $ cd ../env/dev 59 | 60 | # Sets up Terraform to run 61 | $ terraform init 62 | 63 | # Executes the Terraform run 64 | $ terraform apply 65 | ``` 66 | 67 | ## fargate-create 68 | 69 | Alternatively you can use the [fargate-create CLI](https://github.com/turnerlabs/fargate-create) to scaffold new projects based on this template. 70 | 71 | install 72 | ```shell 73 | curl -s get-fargate-create.turnerlabs.io | sh 74 | ``` 75 | 76 | create an input vars file (`terraform.tfvars`) 77 | ```hcl 78 | # app/env to scaffold 79 | app = "my-app" 80 | environment = "dev" 81 | schedule_expression = "rate(5 minutes)" 82 | 83 | region = "us-east-1" 84 | aws_profile = "default" 85 | saml_role = "admin" 86 | vpc = "vpc-123" 87 | private_subnets = "subnet-123,subnet-456" 88 | public_subnets = "subnet-789,subnet-012" 89 | tags = { 90 | application = "my-app" 91 | environment = "dev" 92 | team = "my-team" 93 | customer = "my-customer" 94 | contact-email = "me@example.com" 95 | } 96 | ``` 97 | 98 | ```shell 99 | $ fargate-create -t git@github.com:turnerlabs/terraform-ecs-fargate-scheduled-task 100 | ``` 101 | 102 | 103 | ## Additional Information 104 | 105 | + [Base README][base] 106 | 107 | + [Environment `dev` README][env-dev] 108 | 109 | 110 | 111 | [fargate]: https://aws.amazon.com/fargate/ 112 | [bm]: ./base/main.tf 113 | [bs]: ./base/state.tf 114 | [be]: ./base/ecr.tf 115 | [edm]: ./env/dev/main.tf 116 | [ede]: ./env/dev/ecs.tf 117 | [edl]: ./env/dev/lb.tf 118 | [edn]: ./env/dev/nsg.tf 119 | [edlhttp]: ./env/dev/lb-http.tf 120 | [edlhttps]: ./env/dev/lb-https.tf 121 | [edd]: ./env/dev/dashboard.tf 122 | [edr]: ./env/dev/role.tf 123 | [edc]: ./env/dev/cicd.tf 124 | [edap]: ./env/dev/autoscale-perf.tf 125 | [edat]: ./env/dev/autoscale-time.tf 126 | [edll]: ./env/dev/logs-logzio.tf 127 | [edsm]: ./env/dev/secretsmanager.tf 128 | [base]: ./base/README.md 129 | [env-dev]: ./env/dev/README.md 130 | -------------------------------------------------------------------------------- /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-scheduled-task/dcfb285b62c3894269857e8501c9967ff8b7a887/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, Task Definition, ecsTaskExecutionRole, CloudWatch Log Group | | 13 | | [nsg.tf][edn] | NSG for Task | | 14 | | [secretsmanager.tf][edn] | Sets up integration with Secrets Manager | | 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 | | [logs-logzio.tf][edll] | Ship container logs to logz.io | Yes | 18 | | [secretsmanager.tf][edsm] | Add a Secrets Manager secret with a CMK KMS key. Also gives app role and ECS task definition role access to read secrets from Secrets Manager | Yes | 19 | | [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 | 20 | 21 | 22 | ## Usage 23 | 24 | ``` 25 | # Sets up Terraform to run 26 | $ terraform init 27 | 28 | # Executes the Terraform run 29 | $ terraform apply 30 | ``` 31 | 32 | 33 | ## Inputs 34 | 35 | | Name | Description | Type | Default | Required | 36 | |------|-------------|:----:|:-----:|:-----:| 37 | | app | The application's name | string | - | yes | 38 | | aws_profile | The AWS Profile to use | string | - | yes | 39 | | container_name | name of the container in the task definition | string | `app` | no | 40 | | environment | The environment that is being built | string | - | yes | 41 | | logz_token | The auth token to use for sending logs to Logz.io | string | - | yes | 42 | | logz_url | The endpoint to use for sending logs to Logz.io | string | `https://listener.logz.io:8071` | no | 43 | | private_subnets | The private subnets, minimum of 2, that are a part of the VPC(s) | string | - | yes | 44 | | public_subnets | The public subnets, minimum of 2, that are a part of the VPC(s) | string | - | yes | 45 | | 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 | 46 | | saml_role | The SAML role to use for adding users to the ECR policy | string | - | yes | 47 | | schedule_expression | The shedule on which to run the fargate task. Follows the CloudWatch Event Schedule Expression format: https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html | string | - | yes | 48 | | secrets_saml_users | The users (email addresses) from the saml role to give access | list | - | yes | 49 | | tags | Tags for the infrastructure | map | - | yes | 50 | | vpc | The VPC to use for the Fargate cluster | string | - | yes | 51 | 52 | ## Outputs 53 | 54 | | Name | Description | 55 | |------|-------------| 56 | | aws_profile | Command to set the AWS_PROFILE | 57 | | cicd_keys | The AWS keys for the CICD user to use in a build system | 58 | | docker_registry | The URL for the docker image repo in ECR | 59 | | register | Command to register a new task definition for the task | 60 | | status | Command to view the status of the Fargate service | 61 | 62 | 63 | 64 | [edm]: main.tf 65 | [ede]: ecs.tf 66 | [edl]: lb.tf 67 | [edn]: nsg.tf 68 | [edlhttp]: lb-http.tf 69 | [edlhttps]: lb-https.tf 70 | [edd]: dashboard.tf 71 | [edr]: role.tf 72 | [edc]: cicd.tf 73 | [edap]: autoscale-perf.tf 74 | [edat]: autoscale-time.tf 75 | [edll]: logs-logzio.tf 76 | [edsm]: secretsmanager.tf 77 | [ssm]: ssm-parameters.tf 78 | [alb-docs]: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/application-load-balancers.html 79 | [up]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html 80 | -------------------------------------------------------------------------------- /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:DescribeTaskDefinition", 38 | "ecs:RegisterTaskDefinition", 39 | "sts:GetCallerIdentity", 40 | "events:ListTargetsByRule", 41 | "events:PutTargets", 42 | ] 43 | 44 | resources = [ 45 | "*", 46 | ] 47 | } 48 | 49 | # allows user to run ecs task using task execution and app roles 50 | statement { 51 | sid = "approle" 52 | 53 | actions = [ 54 | "iam:PassRole", 55 | ] 56 | 57 | resources = [ 58 | aws_iam_role.app_role.arn, 59 | aws_iam_role.ecsTaskExecutionRole.arn, 60 | aws_iam_role.cloudwatch_events_role.arn, 61 | ] 62 | } 63 | } 64 | 65 | resource "aws_iam_user_policy" "cicd_user_policy" { 66 | name = "${var.app}_${var.environment}_cicd" 67 | user = aws_iam_user.cicd.name 68 | policy = data.aws_iam_policy_document.cicd_policy.json 69 | } 70 | 71 | data "aws_ecr_repository" "ecr" { 72 | name = var.app 73 | } 74 | 75 | # The AWS keys for the CICD user to use in a build system 76 | output "cicd_keys" { 77 | value = "terraform state show aws_iam_access_key.cicd_keys" 78 | } 79 | 80 | # The URL for the docker image repo in ECR 81 | output "docker_registry" { 82 | value = data.aws_ecr_repository.ecr.repository_url 83 | } 84 | 85 | -------------------------------------------------------------------------------- /env/dev/dashboard.tf: -------------------------------------------------------------------------------- 1 | /** 2 | * This module creates a CloudWatch dashboard for your scheduled task. 3 | */ 4 | 5 | resource "aws_cloudwatch_dashboard" "cloudwatch_dashboard" { 6 | dashboard_name = "${local.namespace}-fargate-scheduled-task" 7 | 8 | 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 = "nodejs12.x" 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 = <