├── LICENSE ├── README.md └── cloudformation-template.yaml /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 | # Launch PHP and MySQL containers in ECS 2 | 3 | This is a method to deploy 2 environments (PROD and UAT) in ECS with MySQL and PHP containers, along with proper monitoring, logging, backup and data persistency. 4 | 5 | The CloudFormation template and explanation is also posted on the [NETBEARS](https://netbears.com/blog/php-mysql-ecs/) company blog. You might want to check the website out for more tutorials like this. 6 | 7 | ## Run the CloudFormation template with AWS CLI 8 | 9 | ``` 10 | git clone https://github.com/NETBEARS/php-mysql-ecs.git 11 | 12 | aws cloudformation create-stack \ 13 | --stack-name php-mysql-prod-and-uat \ 14 | --template-body file://cloudformation-template.yaml \ 15 | --parameters \ 16 | ParameterKey=Ami,ParameterValue=ami-29f80351 \ 17 | ParameterKey=AsgMaxSize,ParameterValue=6 \ 18 | ParameterKey=AsgMinSize,ParameterValue=2 \ 19 | ParameterKey=CadvisorImage,ParameterValue=google/cadvisor:latest \ 20 | ParameterKey=EmailAlerts,ParameterValue=email_for_alerts@domain.com \ 21 | ParameterKey=InstanceType,ParameterValue=m4.large \ 22 | ParameterKey=KeyName,ParameterValue=YOUR_INSTANCE_KEY \ 23 | ParameterKey=MYSQLDATABASE,ParameterValue=wordpress \ 24 | ParameterKey=MYSQLUSER,ParameterValue=wordpress \ 25 | ParameterKey=MYSQLPASSWORD,ParameterValue=SECRET_PASSWORD \ 26 | ParameterKey=NodeExporterImage,ParameterValue=quay.io/prometheus/node-exporter:latest \ 27 | ParameterKey=PcpImage,ParameterValue=mmitrofan/pcp:latest \ 28 | ParameterKey=ProdWordpressImage,ParameterValue=wordpress:latest \ 29 | ParameterKey=UatWordpressImage,ParameterValue=wordpress:latest \ 30 | ParameterKey=VpcId,ParameterValue=VPC_ID \ 31 | ParameterKey=SubnetID1,ParameterValue=SUBNET_IN_VPC_ID_1 \ 32 | ParameterKey=SubnetID2,ParameterValue=SUBNET_IN_VPC_ID_2 \ 33 | --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM 34 | 35 | ``` 36 | 37 | ## Run the CloudFormation template in the AWS Console 38 | * Login to the AWS console and browse to the CloudFormation section 39 | 8 Select the "cloudformation-template.yaml” file 40 | * Before clicking "Create", make sure that you scroll down and tick the “I acknowledge that AWS CloudFormation might create IAM resources” checkbox 41 | * ...drink coffee... 42 | * Go to the URL in the output section for the environment that you want to access 43 | 44 | ## Resources created 45 | * 1 ECS cluster 46 | * 1 AutoScaling Group 47 | * 2 ECS services for PHP (one for each environment) 48 | * 2 ECS services for MySQL (one for each environment) 49 | * 2 Application Load Balancers (1 for each PHP service in each container) 50 | * 2 Elastic Load Balancers (1 for each MySQL service in each container) 51 | * 4 Elastic File Systems (1 for each container in each environment) 52 | * 1 S3 bucket (for database backup) 53 | * 1 SNS topic (send monitoring alerts) 54 | 55 | 56 | ## Autoscaling 57 | The autoscaling groups uses the following alarms to autoscale automatically based on load: 58 | * CpuUtilization 59 | * MemoryUtilization 60 | 61 | Because of this, you wouldn't have to bother making sure that your hosts can sustain the load. 62 | 63 | ## Alarms 64 | In order to be sure that you have set up the proper limits for your containers, the following alerts have been but into place: 65 | * NetworkInAlarm 66 | * RAMAlarmHigh 67 | * NetworkOutAlarm 68 | * IOWaitAlarmHigh 69 | * StatusAlarm 70 | 71 | These CloudWatch alarms will send an email each time the limits are hit so that you will always be in control of what happens with your stack. 72 | 73 | ## Monitoring 74 | The stack launches 3 monitoring tools on each ECS host inside the cluster: 75 | 76 | * [PCP](http://vectoross.io/) - An on-host performance monitoring framework which exposes hand picked high resolution metrics to every engineer’s browser 77 | * [NodeExporter](https://github.com/prometheus/node_exporter) - Prometheus exporter for hardware and OS metrics exposed by NIX kernels, written in Go with pluggable metric collectors 78 | * [cAdvisor](https://github.com/google/cadvisor) - cAdvisor (Container Advisor) provides container users an understanding of the resource usage and performance characteristics of their running containers. 79 | 80 | To view the monitoring data, all you need to setup is a Prometheus host and a Grafana dashboard and you're all set. 81 | 82 | ## Logging 83 | The stack makes use of AWS [LogGroups](http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatchLogsConcepts.html) and offers you the possibility to store all logs in CloudWatch and view them at any point in time by simply accessing any running Task and clicking on "View Logs in CloudWatch". 84 | 85 | ## Data persistency 86 | The stack makes use of AWS [EFS](https://aws.amazon.com/efs/) system to ensure that even though any container fails it will have access to any data that was previously being handled by the previous container. 87 | 88 | This also ensures that any PHP container (in this case WordPress) that uses a specific storage system for its user-uploaded files, they will be available on any container, regardless of how many are currently running. 89 | 90 | Due to its high-throughput and NFS connectivity mechanisms, it has been successfully used to store data for the (single) MySQL container running for each environment. 91 | 92 | ## Backup 93 | Although the data persistency is full-proof in case of container or host failure, we should still have a backup for the MySQL data, just to be sure. 94 | 95 | Because of this, a cronjob has been set up to run every 3 days on the ECS hosts that connect to each MySQL database and dump the data in an S3 bucket that is created inside the template. 96 | 97 | ## Final notes 98 | Need help implementing this? 99 | 100 | Feel free to contact us using [this form](https://netbears.com/#contact-form). 101 | -------------------------------------------------------------------------------- /cloudformation-template.yaml: -------------------------------------------------------------------------------- 1 | Parameters: 2 | 3 | Ami: 4 | Type: String 5 | Description: http://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-optimized_AMI_launch_latest.html 6 | 7 | AsgMaxSize: 8 | Type: Number 9 | Description: The maximum size of ASG 10 | Default: 6 11 | 12 | AsgMinSize: 13 | Type: Number 14 | Description: The minimum size of ASG 15 | Default: 2 16 | 17 | CadvisorImage: 18 | Type: String 19 | Default: google/cadvisor:latest 20 | 21 | EmailAlerts: 22 | Type: String 23 | Default: email_for_alerts@domain.com 24 | 25 | InstanceType: 26 | Type: String 27 | Default: t2.medium 28 | AllowedValues: 29 | - t2.micro 30 | - t2.medium 31 | - t2.small 32 | - t2.large 33 | - m3.medium 34 | - m3.large 35 | - m3.xlarge 36 | - m3.2xlarge 37 | - m4.large 38 | - m4.xlarge 39 | - m4.2xlarge 40 | - m4.4xlarge 41 | - m4.10xlarge 42 | - c4.large 43 | - c4.xlarge 44 | - c4.2xlarge 45 | - c4.4xlarge 46 | - c4.8xlarge 47 | - c3.large 48 | - c3.xlarge 49 | - c3.2xlarge 50 | - c3.4xlarge 51 | - c3.8xlarge 52 | - r3.large 53 | - r3.xlarge 54 | - r3.2xlarge 55 | - r3.4xlarge 56 | - r3.8xlarge 57 | - i2.xlarge 58 | - i2.2xlarge 59 | - i2.4xlarge 60 | - i2.8xlarge 61 | - g2.2xlarge 62 | - g2.8xlarge 63 | - d2.xlarge 64 | - d2.2xlarge 65 | - d2.4xlarge 66 | - d2.8xlarge 67 | 68 | KeyName: 69 | Type: AWS::EC2::KeyPair::KeyName 70 | Description: Name of an existing EC2 KeyPair to enable SSH access to instances 71 | 72 | MYSQLDATABASE: 73 | Type: String 74 | Default: wordpress 75 | 76 | MYSQLUSER: 77 | Type: String 78 | Default: wordpress 79 | 80 | MYSQLPASSWORD: 81 | Type: String 82 | NoEcho: true 83 | 84 | NodeExporterImage: 85 | Type: String 86 | Default: quay.io/prometheus/node-exporter:latest 87 | 88 | PcpImage: 89 | Type: String 90 | Default: mmitrofan/pcp:latest 91 | 92 | ProdWordpressImage: 93 | Type: String 94 | Default: wordpress 95 | 96 | UatWordpressImage: 97 | Type: String 98 | Default: wordpress 99 | 100 | SubnetID1: 101 | Type: AWS::EC2::Subnet::Id 102 | 103 | SubnetID2: 104 | Type: AWS::EC2::Subnet::Id 105 | 106 | VpcId: 107 | Type: AWS::EC2::VPC::Id 108 | 109 | Resources: 110 | 111 | EcsCluster: 112 | Type: AWS::ECS::Cluster 113 | 114 | Sg: 115 | Type: AWS::EC2::SecurityGroup 116 | Properties: 117 | GroupDescription: 118 | Fn::Sub: ${AWS::StackName}-Sg 119 | VpcId: !Ref VpcId 120 | 121 | SgSSHports: 122 | Type: AWS::EC2::SecurityGroupIngress 123 | Properties: 124 | GroupId: !Ref 'Sg' 125 | IpProtocol: tcp 126 | FromPort: '22' 127 | ToPort: '22' 128 | CidrIp: 0.0.0.0/0 129 | 130 | SgAllTrafficports: 131 | Type: AWS::EC2::SecurityGroupIngress 132 | Properties: 133 | GroupId: !Ref 'Sg' 134 | IpProtocol: tcp 135 | FromPort: '0' 136 | ToPort: '65535' 137 | SourceSecurityGroupId: !Ref 'Sg' 138 | 139 | SgALBAllTrafficports: 140 | Type: AWS::EC2::SecurityGroupIngress 141 | Properties: 142 | GroupId: !Ref 'Sg' 143 | IpProtocol: tcp 144 | FromPort: '0' 145 | ToPort: '65535' 146 | SourceSecurityGroupId: !Ref 'EcsSecurityGroup' 147 | 148 | AlertsTopic: 149 | Type: AWS::SNS::Topic 150 | Properties: 151 | Subscription: 152 | - Endpoint: !Ref EmailAlerts 153 | Protocol: email 154 | TopicName: 155 | Fn::Sub: ${AWS::StackName}-AlertsTopic 156 | 157 | HostRole: 158 | Type: AWS::IAM::Role 159 | Properties: 160 | AssumeRolePolicyDocument: 161 | Statement: 162 | - Effect: Allow 163 | Principal: 164 | Service: 165 | - ec2.amazonaws.com 166 | - autoscaling.amazonaws.com 167 | - ecs-tasks.amazonaws.com 168 | - s3.amazonaws.com 169 | - cloudformation.amazonaws.com 170 | Action: 171 | - sts:AssumeRole 172 | ManagedPolicyArns: 173 | - arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role 174 | Policies: 175 | - PolicyName: 176 | Fn::Sub: ${AWS::StackName}-DescribeAWSPolicy 177 | PolicyDocument: 178 | Statement: 179 | - Effect: Allow 180 | Action: 181 | - autoscaling:DescribeAutoScalingGroups 182 | - autoscaling:CompleteLifecycleAction 183 | - cloudformation:DescribeStacks 184 | - cloudformation:DescribeStackResources 185 | - cloudwatch:GetMetricStatistics 186 | - cloudwatch:ListMetrics 187 | - ec2:DescribeInstances 188 | - ec2:DescribeTags 189 | - ec2:DescribeRegions 190 | - ec2:DescribeSecurityGroups 191 | - ec2:DescribeSpotPriceHistory 192 | - ec2:DescribeAvailabilityZones 193 | - elasticloadbalancing:DescribeLoadBalancers 194 | Resource: "*" 195 | - PolicyName: 196 | Fn::Sub: ${AWS::StackName}-LogsPolicy 197 | PolicyDocument: 198 | Statement: 199 | - Effect: Allow 200 | Action: 201 | - logs:* 202 | Resource: "*" 203 | - PolicyName: 204 | Fn::Sub: ${AWS::StackName}-SendMessagesPolicy 205 | PolicyDocument: 206 | Statement: 207 | - Action: sns:Publish 208 | Resource: 209 | Ref: AlertsTopic 210 | Effect: Allow 211 | - PolicyName: 212 | Fn::Sub: ${AWS::StackName}-DumpBackupS3 213 | PolicyDocument: 214 | Statement: 215 | - Action: s3:* 216 | Resource: !GetAtt MySQLBackup.Arn 217 | Effect: Allow 218 | - Action: s3:* 219 | Resource: !Sub 220 | - ${Bucket}/* 221 | - { Bucket: !GetAtt MySQLBackup.Arn } 222 | Effect: Allow 223 | - PolicyName: 224 | Fn::Sub: ${AWS::StackName}-GetCloudformation 225 | PolicyDocument: 226 | Statement: 227 | - Action: 228 | - cloudformation:DescribeStacks 229 | - cloudformation:DescribeStackEvents 230 | - cloudformation:DescribeStackResource 231 | - cloudformation:DescribeStackResources 232 | - cloudformation:GetTemplate 233 | - cloudformation:List* 234 | Resource: "*" 235 | Effect: Allow 236 | 237 | HostProfile: 238 | Type: AWS::IAM::InstanceProfile 239 | Properties: 240 | Roles: 241 | - Ref: HostRole 242 | 243 | FileSystemMySQLProd: 244 | Type: AWS::EFS::FileSystem 245 | Properties: 246 | PerformanceMode: generalPurpose 247 | 248 | MountTargetMySQLProd1: 249 | Type: AWS::EFS::MountTarget 250 | Properties: 251 | FileSystemId: !Ref FileSystemMySQLProd 252 | SubnetId: !Ref SubnetID1 253 | SecurityGroups: 254 | - !GetAtt Sg.GroupId 255 | 256 | MountTargetMySQLProd2: 257 | Type: AWS::EFS::MountTarget 258 | Properties: 259 | FileSystemId: !Ref FileSystemMySQLProd 260 | SubnetId: !Ref SubnetID2 261 | SecurityGroups: 262 | - !GetAtt Sg.GroupId 263 | 264 | FileSystemMySQLUat: 265 | Type: AWS::EFS::FileSystem 266 | Properties: 267 | PerformanceMode: generalPurpose 268 | 269 | MountTargetMySQLUat1: 270 | Type: AWS::EFS::MountTarget 271 | Properties: 272 | FileSystemId: !Ref FileSystemMySQLUat 273 | SubnetId: !Ref SubnetID1 274 | SecurityGroups: 275 | - !GetAtt Sg.GroupId 276 | 277 | MountTargetMySQLUat2: 278 | Type: AWS::EFS::MountTarget 279 | Properties: 280 | FileSystemId: !Ref FileSystemMySQLUat 281 | SubnetId: !Ref SubnetID2 282 | SecurityGroups: 283 | - !GetAtt Sg.GroupId 284 | 285 | FileSystemWPProd: 286 | Type: AWS::EFS::FileSystem 287 | Properties: 288 | PerformanceMode: generalPurpose 289 | 290 | MountTargetWPProd1: 291 | Type: AWS::EFS::MountTarget 292 | Properties: 293 | FileSystemId: !Ref FileSystemWPProd 294 | SubnetId: !Ref SubnetID1 295 | SecurityGroups: 296 | - !GetAtt Sg.GroupId 297 | 298 | MountTargetWPProd2: 299 | Type: AWS::EFS::MountTarget 300 | Properties: 301 | FileSystemId: !Ref FileSystemWPProd 302 | SubnetId: !Ref SubnetID2 303 | SecurityGroups: 304 | - !GetAtt Sg.GroupId 305 | 306 | FileSystemWPUat: 307 | Type: AWS::EFS::FileSystem 308 | Properties: 309 | PerformanceMode: generalPurpose 310 | 311 | MountTargetWPUat1: 312 | Type: AWS::EFS::MountTarget 313 | Properties: 314 | FileSystemId: !Ref FileSystemWPUat 315 | SubnetId: !Ref SubnetID1 316 | SecurityGroups: 317 | - !GetAtt Sg.GroupId 318 | 319 | MountTargetWPUat2: 320 | Type: AWS::EFS::MountTarget 321 | Properties: 322 | FileSystemId: !Ref FileSystemWPUat 323 | SubnetId: !Ref SubnetID2 324 | SecurityGroups: 325 | - !GetAtt Sg.GroupId 326 | 327 | MySQLBackup: 328 | Type: AWS::S3::Bucket 329 | DeletionPolicy: Retain 330 | 331 | 332 | Asg: 333 | Type: AWS::AutoScaling::AutoScalingGroup 334 | Properties: 335 | VPCZoneIdentifier: 336 | - !Ref SubnetID1 337 | - !Ref SubnetID2 338 | NotificationConfiguration: 339 | TopicARN: 340 | Ref: AlertsTopic 341 | NotificationTypes: 342 | - autoscaling:EC2_INSTANCE_LAUNCH 343 | - autoscaling:EC2_INSTANCE_TERMINATE 344 | - autoscaling:EC2_INSTANCE_LAUNCH_ERROR 345 | - autoscaling:EC2_INSTANCE_TERMINATE_ERROR 346 | HealthCheckGracePeriod: '600' 347 | HealthCheckType: EC2 348 | LaunchConfigurationName: 349 | Ref: Lc 350 | MinSize: 351 | Ref: AsgMinSize 352 | MaxSize: 353 | Ref: AsgMaxSize 354 | DesiredCapacity: 355 | Ref: AsgMinSize 356 | Tags: 357 | - Key: Name 358 | Value: 359 | Fn::Sub: EC2ContainerService-${EcsCluster} 360 | PropagateAtLaunch: true 361 | PropagateAtLaunch: true 362 | - Key: Creator 363 | Value: 364 | Ref: KeyName 365 | PropagateAtLaunch: true 366 | UpdatePolicy: 367 | AutoScalingRollingUpdate: 368 | MinInstancesInService: 369 | Ref: AsgMinSize 370 | PauseTime: PT5M 371 | 372 | Lc: 373 | Type: AWS::AutoScaling::LaunchConfiguration 374 | Properties: 375 | ImageId: 376 | Ref: Ami 377 | BlockDeviceMappings: 378 | - DeviceName: /dev/xvdcy 379 | Ebs: 380 | VolumeSize: 100 381 | VolumeType: gp2 382 | InstanceType: 383 | Ref: InstanceType 384 | IamInstanceProfile: 385 | Ref: HostProfile 386 | KeyName: 387 | Ref: KeyName 388 | SecurityGroups: 389 | - Ref: Sg 390 | UserData: 391 | Fn::Base64: 392 | Fn::Sub: | 393 | #cloud-config 394 | package_upgrade: true 395 | packages: 396 | - aws-cli 397 | - ntp 398 | - nfs-utils 399 | - mysql 400 | - wget 401 | write_files: 402 | - path: /etc/cron.d/db-backup 403 | content: | 404 | 0 0 */3 0 0 root mysqldump --add-drop-table -u ${MYSQLUSER} -p${MYSQLPASSWORD} -h $(aws cloudformation describe-stacks --stack-name ${AWS::StackName} --query "Stacks[0].Outputs[?OutputKey=='MySQLProd'] | [0].OutputValue" --output text) wp > /opt/prod.sql 405 | 30 0 */3 0 0 root mysqldump --add-drop-table -u ${MYSQLUSER} -p${MYSQLPASSWORD} -h $(aws cloudformation describe-stacks --stack-name ${AWS::StackName} --query "Stacks[0].Outputs[?OutputKey=='MySQLUat'] | [0].OutputValue" --output text) wp > /opt/uat.sql 406 | 0 1 */3 0 0 root aws s3 sync /opt/prod.sql s3://${MySQLBackup}/$(HOSTNAME)/$(date)/prod.sql 407 | 30 1 */3 0 0 root aws s3 sync /opt/uat.sql s3://${MySQLBackup}/$(HOSTNAME)/$(date)/uat.sql 408 | permissions: '0600' 409 | - path: /etc/ecs/ecs.config 410 | content: | 411 | ECS_AVAILABLE_LOGGING_DRIVERS=["json-file","gelf","awslogs"] 412 | ECS_CLUSTER=${EcsCluster} 413 | ECS_CONTAINER_STOP_TIMEOUT=125s 414 | ECS_ENGINE_TASK_CLEANUP_WAIT_DURATION=12h 415 | ECS_DISABLE_IMAGE_CLEANUP=false 416 | ECS_ECS_IMAGE_CLEANUP_INTERVAL=15m 417 | ECS_NUM_IMAGES_DELETE_PER_CYCLE=10 418 | runcmd: 419 | - vgextend docker /dev/xvdcy 420 | - lvextend -L+100G /dev/docker/docker-pool 421 | - mkdir -p /mnt/mysql_prod 422 | - mkdir -p /mnt/mysql_uat 423 | - mkdir -p /mnt/wordpress_prod 424 | - mkdir -p /mnt/wordpress_uat 425 | - mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 ${FileSystemMySQLProd}.efs.${AWS::Region}.amazonaws.com:/ /mnt/mysql_prod 426 | - mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 ${FileSystemMySQLUat}.efs.${AWS::Region}.amazonaws.com:/ /mnt/mysql_uat 427 | - mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 ${FileSystemWPProd}.efs.${AWS::Region}.amazonaws.com:/ /mnt/wordpress_prod 428 | - mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 ${FileSystemWPUat}.efs.${AWS::Region}.amazonaws.com:/ /mnt/wordpress_uat 429 | - echo '${FileSystemMySQLProd}.efs.${AWS::Region}.amazonaws.com:/ /mnt/mysql_prod nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 0 0' | tee -a /etc/fstab 430 | - echo '${FileSystemMySQLUat}.efs.${AWS::Region}.amazonaws.com:/ /mnt/mysql_uat nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 0 0' | tee -a /etc/fstab 431 | - echo '${FileSystemWPProd}.efs.${AWS::Region}.amazonaws.com:/ /mnt/wordpress_prod nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 0 0' | tee -a /etc/fstab 432 | - echo '${FileSystemWPUat}.efs.${AWS::Region}.amazonaws.com:/ /mnt/wordpress_uat nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2 0 0' | tee -a /etc/fstab 433 | - stop ecs 434 | - service docker restart 435 | - start ecs 436 | 437 | CpuUtilization: 438 | Type: AWS::AutoScaling::ScalingPolicy 439 | Properties: 440 | AutoScalingGroupName: 441 | Ref: Asg 442 | PolicyType: TargetTrackingScaling 443 | TargetTrackingConfiguration: 444 | TargetValue: 70 445 | PredefinedMetricSpecification: 446 | PredefinedMetricType: ASGAverageCPUUtilization 447 | 448 | MemoryUtilization: 449 | Type: AWS::AutoScaling::ScalingPolicy 450 | Properties: 451 | AutoScalingGroupName: 452 | Ref: Asg 453 | PolicyType: TargetTrackingScaling 454 | TargetTrackingConfiguration: 455 | CustomizedMetricSpecification: 456 | MetricName: MemoryUtilization 457 | Namespace: AWS/ECS 458 | Dimensions: 459 | - Name: ClusterName 460 | Value: 461 | Ref: EcsCluster 462 | Statistic: Maximum 463 | TargetValue: 80 464 | 465 | NetworkInAlarm: 466 | Type: AWS::CloudWatch::Alarm 467 | Properties: 468 | AlarmActions: 469 | - Ref: AlertsTopic 470 | MetricName: NetworkIn 471 | ComparisonOperator: GreaterThanThreshold 472 | AlarmDescription: High network input traffic during 15 minutes 473 | Statistic: Average 474 | Period: '300' 475 | Dimensions: 476 | - Value: 477 | Ref: Asg 478 | Name: AutoScalingGroupName 479 | EvaluationPeriods: '3' 480 | InsufficientDataActions: 481 | - Ref: AlertsTopic 482 | Namespace: AWS/EC2 483 | Threshold: '2400000000' 484 | 485 | RAMAlarmHigh: 486 | Type: AWS::CloudWatch::Alarm 487 | Properties: 488 | AlarmActions: 489 | - Ref: AlertsTopic 490 | MetricName: MemoryUtilization 491 | ComparisonOperator: GreaterThanThreshold 492 | AlarmDescription: Memory utilization > 85% during 15 minutes 493 | Statistic: Average 494 | Period: '300' 495 | Dimensions: 496 | - Value: 497 | Ref: Asg 498 | Name: AutoScalingGroupName 499 | EvaluationPeriods: '3' 500 | InsufficientDataActions: 501 | - Ref: AlertsTopic 502 | Namespace: System/Linux 503 | Threshold: '85' 504 | 505 | NetworkOutAlarm: 506 | Type: AWS::CloudWatch::Alarm 507 | Properties: 508 | AlarmActions: 509 | - Ref: AlertsTopic 510 | MetricName: NetworkOut 511 | ComparisonOperator: GreaterThanThreshold 512 | AlarmDescription: High network output traffic during 15 minutes 513 | Statistic: Average 514 | Period: '300' 515 | Dimensions: 516 | - Value: 517 | Ref: Asg 518 | Name: AutoScalingGroupName 519 | EvaluationPeriods: '3' 520 | InsufficientDataActions: 521 | - Ref: AlertsTopic 522 | Namespace: AWS/EC2 523 | Threshold: '2400000000' 524 | 525 | IOWaitAlarmHigh: 526 | Type: AWS::CloudWatch::Alarm 527 | Properties: 528 | AlarmActions: 529 | - Ref: AlertsTopic 530 | MetricName: IOWait 531 | ComparisonOperator: GreaterThanThreshold 532 | AlarmDescription: Alarm if IOWait > 85% for 15 minutes 533 | Statistic: Average 534 | Period: '300' 535 | Dimensions: 536 | - Value: 537 | Ref: AWS::StackName 538 | Name: StackName 539 | EvaluationPeriods: '3' 540 | InsufficientDataActions: 541 | - Ref: AlertsTopic 542 | Namespace: AWS/EC2 543 | Threshold: '85' 544 | 545 | StatusAlarm: 546 | Type: AWS::CloudWatch::Alarm 547 | Properties: 548 | AlarmActions: 549 | - Ref: AlertsTopic 550 | MetricName: StatusCheckFailed 551 | ComparisonOperator: GreaterThanOrEqualToThreshold 552 | AlarmDescription: Alert if asg has degraded instances 553 | Statistic: Maximum 554 | Period: '60' 555 | Dimensions: 556 | - Value: 557 | Ref: Asg 558 | Name: AutoScalingGroupName 559 | EvaluationPeriods: '2' 560 | InsufficientDataActions: 561 | - Ref: AlertsTopic 562 | Unit: Count 563 | Namespace: AWS/EC2 564 | Threshold: '1' 565 | 566 | LogGroup: 567 | Type: AWS::Logs::LogGroup 568 | Properties: 569 | LogGroupName: 570 | Fn::Sub: ${AWS::StackName}-LogGroup 571 | RetentionInDays: 14 572 | 573 | ProdWordpressTaskDefinition: 574 | Type: AWS::ECS::TaskDefinition 575 | Properties: 576 | ContainerDefinitions: 577 | - Name: wordpress 578 | Image: 579 | Ref: ProdWordpressImage 580 | Memory: 256 581 | PortMappings: 582 | - ContainerPort: 80 583 | MountPoints: 584 | - ContainerPath: /var/www/html/wp-content 585 | SourceVolume: data 586 | Environment: 587 | - Name: WORDPRESS_DB_HOST 588 | Value: !GetAtt ECSELBMySQLProd.DNSName 589 | - Name: WORDPRESS_DB_USER 590 | Value: !Ref MYSQLUSER 591 | - Name: WORDPRESS_DB_PASSWORD 592 | Value: !Ref MYSQLPASSWORD 593 | - Name: WORDPRESS_DB_NAME 594 | Value: !Ref MYSQLDATABASE 595 | - Name: WORDPRESS_TABLE_PREFIX 596 | Value: wp 597 | - Name: WORDPRESS_AUTH_KEY 598 | Value: '9aaeVk9aKb5mkK452aPa1ragaBPxaAsZMaaIxjaaaDEbthax4ZaaJqRaraBOWaZa' 599 | - Name: WORDPRESS_SECURE_AUTH_KEY 600 | Value: 'atoHakFXaaamqkbY32uZaaaiaa3J1FanJQQsv97baa2aRaaaaatUaGwfUBa1Lmdp' 601 | - Name: WORDPRESS_LOGGED_IN_KEY 602 | Value: 'a1aSaaaaybanZwYaaaaaalaRaSdjTHU0FM9OaaNAVIaaaaa6qaa1aajS2Uy2kaEq' 603 | - Name: WORDPRESS_NONCE_KEY 604 | Value: 'mC8aWvM3a5fadaHaGawsaQiBskaaaraaafPZJQdRaatvQtaOakaaaaQZEaNfafaa' 605 | - Name: WORDPRESS_AUTH_SALT 606 | Value: 'EaAwWaansaa3a3aa1LQrf2af5cLEaaZqabpG6K2adQaaaRJRaaaa8ACwaKYXaaV]' 607 | - Name: WORDPRESS_SECURE_AUTH_SALT 608 | Value: 'aauUa7GIpohbabBaza10GalaisfXDaJIa9m43aFCa90lhaxjg3aPaLnnaaaVQaoQ' 609 | - Name: WORDPRESS_LOGGED_IN_SALT 610 | Value: 'saK94aaaaaa4DyoayGAaaOaKaYQaOaKaXQCQWacpa3uabaqF?7sMaauOdaXaopL2' 611 | - Name: WORDPRESS_NONCE_SALT 612 | Value: 'qaVq8rOcahaagaaa9AaoRh7d7SYJka2irwatunaaavaaaH6aKa5IJXaJu4laaaq^' 613 | LogConfiguration: 614 | LogDriver: awslogs 615 | Options: 616 | awslogs-region: 617 | Ref: AWS::Region 618 | awslogs-group: !Ref LogGroup 619 | awslogs-stream-prefix: 620 | Ref: AWS::StackName 621 | Volumes: 622 | - Name: data 623 | Host: 624 | SourcePath: /mnt/wordpress_prod 625 | 626 | UatWordpressTaskDefinition: 627 | Type: AWS::ECS::TaskDefinition 628 | Properties: 629 | ContainerDefinitions: 630 | - Name: wordpress 631 | Image: 632 | Ref: UatWordpressImage 633 | Memory: 256 634 | PortMappings: 635 | - ContainerPort: 80 636 | MountPoints: 637 | - ContainerPath: /var/www/html/wp-content 638 | SourceVolume: data 639 | Environment: 640 | - Name: WORDPRESS_DB_HOST 641 | Value: !GetAtt ECSELBMySQLUat.DNSName 642 | - Name: WORDPRESS_DB_USER 643 | Value: !Ref MYSQLUSER 644 | - Name: WORDPRESS_DB_PASSWORD 645 | Value: !Ref MYSQLPASSWORD 646 | - Name: WORDPRESS_DB_NAME 647 | Value: !Ref MYSQLDATABASE 648 | - Name: WORDPRESS_TABLE_PREFIX 649 | Value: wp 650 | - Name: WORDPRESS_AUTH_KEY 651 | Value: '9aaeVk9aKb5mkK452aPa1ragaBPxaAsZMaaIxjaaaDEbthax4ZaaJqRaraBOWaZa' 652 | - Name: WORDPRESS_SECURE_AUTH_KEY 653 | Value: 'atoHakFXaaamqkbY32uZaaaiaa3J1FanJQQsv97baa2aRaaaaatUaGwfUBa1Lmdp' 654 | - Name: WORDPRESS_LOGGED_IN_KEY 655 | Value: 'a1aSaaaaybanZwYaaaaaalaRaSdjTHU0FM9OaaNAVIaaaaa6qaa1aajS2Uy2kaEq' 656 | - Name: WORDPRESS_NONCE_KEY 657 | Value: 'mC8aWvM3a5fadaHaGawsaQiBskaaaraaafPZJQdRaatvQtaOakaaaaQZEaNfafaa' 658 | - Name: WORDPRESS_AUTH_SALT 659 | Value: 'EaAwWaansaa3a3aa1LQrf2af5cLEaaZqabpG6K2adQaaaRJRaaaa8ACwaKYXaaV]' 660 | - Name: WORDPRESS_SECURE_AUTH_SALT 661 | Value: 'aauUa7GIpohbabBaza10GalaisfXDaJIa9m43aFCa90lhaxjg3aPaLnnaaaVQaoQ' 662 | - Name: WORDPRESS_LOGGED_IN_SALT 663 | Value: 'saK94aaaaaa4DyoayGAaaOaKaYQaOaKaXQCQWacpa3uabaqF?7sMaauOdaXaopL2' 664 | - Name: WORDPRESS_NONCE_SALT 665 | Value: 'qaVq8rOcahaagaaa9AaoRh7d7SYJka2irwatunaaavaaaH6aKa5IJXaJu4laaaq^' 666 | LogConfiguration: 667 | LogDriver: awslogs 668 | Options: 669 | awslogs-region: 670 | Ref: AWS::Region 671 | awslogs-group: !Ref LogGroup 672 | awslogs-stream-prefix: 673 | Ref: AWS::StackName 674 | Volumes: 675 | - Name: data 676 | Host: 677 | SourcePath: /mnt/wordpress_uat 678 | 679 | ApplicationScalingRole: 680 | Type: AWS::IAM::Role 681 | Properties: 682 | AssumeRolePolicyDocument: 683 | Statement: 684 | - Effect: Allow 685 | Principal: 686 | Service: 687 | - application-autoscaling.amazonaws.com 688 | Action: sts:AssumeRole 689 | Policies: 690 | - PolicyName: !Ref AWS::StackName 691 | PolicyDocument: 692 | Statement: 693 | - Effect: Allow 694 | Action: 695 | - "application-autoscaling:*" 696 | - "cloudwatch:DescribeAlarms" 697 | - "cloudwatch:PutMetricAlarm" 698 | - "ecs:DescribeServices" 699 | - "ecs:UpdateService" 700 | Resource: "*" 701 | 702 | ECSServiceRole: 703 | Type: AWS::IAM::Role 704 | Properties: 705 | AssumeRolePolicyDocument: 706 | Statement: 707 | - Effect: Allow 708 | Principal: 709 | Service: [ecs.amazonaws.com] 710 | Action: ['sts:AssumeRole'] 711 | Path: / 712 | Policies: 713 | - PolicyName: ecs-service 714 | PolicyDocument: 715 | Statement: 716 | - Effect: Allow 717 | Action: ['elasticloadbalancing:DeregisterInstancesFromLoadBalancer', 'elasticloadbalancing:DeregisterTargets', 718 | 'elasticloadbalancing:Describe*', 'elasticloadbalancing:RegisterInstancesWithLoadBalancer', 719 | 'elasticloadbalancing:RegisterTargets', 'ec2:Describe*', 'ec2:AuthorizeSecurityGroupIngress'] 720 | Resource: '*' 721 | 722 | ProdWordpressService: 723 | Type: AWS::ECS::Service 724 | DependsOn: ECSALBListenerRuleProd 725 | Properties: 726 | Cluster: !Ref EcsCluster 727 | LoadBalancers: 728 | - ContainerName: wordpress 729 | ContainerPort: '80' 730 | TargetGroupArn: !Ref 'EcsTargetGroupProd' 731 | DeploymentConfiguration: 732 | MaximumPercent: 100 733 | MinimumHealthyPercent: 50 734 | TaskDefinition: !Ref ProdWordpressTaskDefinition 735 | Role: !Ref 'ECSServiceRole' 736 | DesiredCount: !Ref AsgMinSize 737 | 738 | UatWordpressService: 739 | Type: AWS::ECS::Service 740 | DependsOn: ECSALBListenerRuleUat 741 | Properties: 742 | Cluster: !Ref EcsCluster 743 | LoadBalancers: 744 | - ContainerName: wordpress 745 | ContainerPort: '80' 746 | TargetGroupArn: !Ref 'EcsTargetGroupUat' 747 | DeploymentConfiguration: 748 | MaximumPercent: 100 749 | MinimumHealthyPercent: 50 750 | TaskDefinition: !Ref UatWordpressTaskDefinition 751 | Role: !Ref 'ECSServiceRole' 752 | DesiredCount: !Ref AsgMinSize 753 | 754 | EcsSecurityGroup: 755 | Type: AWS::EC2::SecurityGroup 756 | Properties: 757 | GroupDescription: ECS Allowed Ports 758 | VpcId: !Ref VpcId 759 | 760 | EcsSecurityGroupHTTPinbound: 761 | Type: AWS::EC2::SecurityGroupIngress 762 | Properties: 763 | GroupId: !Ref 'EcsSecurityGroup' 764 | IpProtocol: tcp 765 | FromPort: '80' 766 | ToPort: '80' 767 | CidrIp: 0.0.0.0/0 768 | 769 | EcsSecurityGroupHTTPSinbound: 770 | Type: AWS::EC2::SecurityGroupIngress 771 | Properties: 772 | GroupId: !Ref 'EcsSecurityGroup' 773 | IpProtocol: tcp 774 | FromPort: '443' 775 | ToPort: '443' 776 | CidrIp: 0.0.0.0/0 777 | 778 | EcsSecurityGroupECSAllTrafficports: 779 | Type: AWS::EC2::SecurityGroupIngress 780 | Properties: 781 | GroupId: !Ref 'EcsSecurityGroup' 782 | IpProtocol: tcp 783 | FromPort: '0' 784 | ToPort: '65535' 785 | SourceSecurityGroupId: !Ref 'Sg' 786 | 787 | EcsSecurityGroupALBAllTrafficports: 788 | Type: AWS::EC2::SecurityGroupIngress 789 | Properties: 790 | GroupId: !Ref 'EcsSecurityGroup' 791 | IpProtocol: tcp 792 | FromPort: '0' 793 | ToPort: '65535' 794 | SourceSecurityGroupId: !Ref 'EcsSecurityGroup' 795 | 796 | ECSALBProd: 797 | Type: AWS::ElasticLoadBalancingV2::LoadBalancer 798 | Properties: 799 | Name: 800 | Fn::Sub: ${AWS::StackName}-wordpress-prod 801 | LoadBalancerAttributes: 802 | - Key: idle_timeout.timeout_seconds 803 | Value: '30' 804 | Subnets: 805 | - !Ref SubnetID1 806 | - !Ref SubnetID2 807 | SecurityGroups: [ !Ref EcsSecurityGroup ] 808 | 809 | ECSALBUat: 810 | Type: AWS::ElasticLoadBalancingV2::LoadBalancer 811 | Properties: 812 | Name: 813 | Fn::Sub: ${AWS::StackName}-wordpress-uat 814 | LoadBalancerAttributes: 815 | - Key: idle_timeout.timeout_seconds 816 | Value: '30' 817 | Subnets: 818 | - !Ref SubnetID1 819 | - !Ref SubnetID2 820 | SecurityGroups: [ !Ref EcsSecurityGroup ] 821 | 822 | ALBListenerProd: 823 | Type: AWS::ElasticLoadBalancingV2::Listener 824 | DependsOn: ECSServiceRole 825 | Properties: 826 | DefaultActions: 827 | - Type: forward 828 | TargetGroupArn: !Ref 'EcsTargetGroupProd' 829 | LoadBalancerArn: !Ref 'ECSALBProd' 830 | Port: '80' 831 | Protocol: HTTP 832 | 833 | ALBListenerUat: 834 | Type: AWS::ElasticLoadBalancingV2::Listener 835 | DependsOn: ECSServiceRole 836 | Properties: 837 | DefaultActions: 838 | - Type: forward 839 | TargetGroupArn: !Ref 'EcsTargetGroupUat' 840 | LoadBalancerArn: !Ref 'ECSALBUat' 841 | Port: '80' 842 | Protocol: HTTP 843 | 844 | ECSALBListenerRuleProd: 845 | Type: AWS::ElasticLoadBalancingV2::ListenerRule 846 | DependsOn: ALBListenerProd 847 | Properties: 848 | Actions: 849 | - Type: forward 850 | TargetGroupArn: !Ref 'EcsTargetGroupProd' 851 | Conditions: 852 | - Field: path-pattern 853 | Values: [/] 854 | ListenerArn: !Ref 'ALBListenerProd' 855 | Priority: 1 856 | 857 | ECSALBListenerRuleUat: 858 | Type: AWS::ElasticLoadBalancingV2::ListenerRule 859 | DependsOn: ALBListenerUat 860 | Properties: 861 | Actions: 862 | - Type: forward 863 | TargetGroupArn: !Ref 'EcsTargetGroupUat' 864 | Conditions: 865 | - Field: path-pattern 866 | Values: [/] 867 | ListenerArn: !Ref 'ALBListenerUat' 868 | Priority: 1 869 | 870 | EcsTargetGroupProd: 871 | Type: AWS::ElasticLoadBalancingV2::TargetGroup 872 | DependsOn: ECSALBProd 873 | Properties: 874 | HealthCheckIntervalSeconds: 10 875 | HealthCheckPath: / 876 | HealthCheckProtocol: HTTP 877 | HealthCheckTimeoutSeconds: 5 878 | HealthyThresholdCount: 2 879 | Matcher: 880 | HttpCode: '200,301,302,346' 881 | Name: 882 | Fn::Sub: ${AWS::StackName}-wordpress-prod 883 | Port: 80 884 | Protocol: HTTP 885 | UnhealthyThresholdCount: 2 886 | VpcId: !Ref VpcId 887 | 888 | EcsTargetGroupUat: 889 | Type: AWS::ElasticLoadBalancingV2::TargetGroup 890 | DependsOn: ECSALBUat 891 | Properties: 892 | HealthCheckIntervalSeconds: 10 893 | HealthCheckPath: / 894 | HealthCheckProtocol: HTTP 895 | HealthCheckTimeoutSeconds: 5 896 | HealthyThresholdCount: 2 897 | Matcher: 898 | HttpCode: '200,302,346' 899 | Name: 900 | Fn::Sub: ${AWS::StackName}-wordpress-uat 901 | Port: 80 902 | Protocol: HTTP 903 | UnhealthyThresholdCount: 2 904 | VpcId: !Ref VpcId 905 | 906 | ProdMySQLTaskDefinition: 907 | Type: AWS::ECS::TaskDefinition 908 | Properties: 909 | NetworkMode: host 910 | ContainerDefinitions: 911 | - Name: mysql 912 | Image: mysql:5.7 913 | Memory: 256 914 | PortMappings: 915 | - ContainerPort: 3306 916 | MountPoints: 917 | - ContainerPath: /var/lib/mysql 918 | SourceVolume: data 919 | Environment: 920 | - Name: MYSQL_RANDOM_ROOT_PASSWORD 921 | Value: "yes" 922 | - Name: MYSQL_DATABASE 923 | Value: !Ref MYSQLDATABASE 924 | - Name: MYSQL_USER 925 | Value: !Ref MYSQLUSER 926 | - Name: MYSQL_PASSWORD 927 | Value: !Ref MYSQLPASSWORD 928 | LogConfiguration: 929 | LogDriver: awslogs 930 | Options: 931 | awslogs-region: 932 | Ref: AWS::Region 933 | awslogs-group: !Ref LogGroup 934 | awslogs-stream-prefix: 935 | Ref: AWS::StackName 936 | Volumes: 937 | - Name: data 938 | Host: 939 | SourcePath: /mnt/mysql_prod 940 | 941 | UatMySQLTaskDefinition: 942 | Type: AWS::ECS::TaskDefinition 943 | Properties: 944 | NetworkMode: host 945 | ContainerDefinitions: 946 | - Name: mysql 947 | Image: mysql:5.7 948 | Memory: 256 949 | PortMappings: 950 | - ContainerPort: 3306 951 | MountPoints: 952 | - ContainerPath: /var/lib/mysql 953 | SourceVolume: data 954 | Environment: 955 | - Name: MYSQL_RANDOM_ROOT_PASSWORD 956 | Value: "yes" 957 | - Name: MYSQL_DATABASE 958 | Value: !Ref MYSQLDATABASE 959 | - Name: MYSQL_USER 960 | Value: !Ref MYSQLUSER 961 | - Name: MYSQL_PASSWORD 962 | Value: !Ref MYSQLPASSWORD 963 | LogConfiguration: 964 | LogDriver: awslogs 965 | Options: 966 | awslogs-region: 967 | Ref: AWS::Region 968 | awslogs-group: !Ref LogGroup 969 | awslogs-stream-prefix: 970 | Ref: AWS::StackName 971 | Volumes: 972 | - Name: data 973 | Host: 974 | SourcePath: /mnt/mysql_uat 975 | 976 | ECSELBMySQLProd: 977 | Type: AWS::ElasticLoadBalancing::LoadBalancer 978 | Properties: 979 | LoadBalancerName: 980 | Fn::Sub: ${AWS::StackName}-mysql-prod 981 | Subnets: 982 | - !Ref SubnetID1 983 | - !Ref SubnetID2 984 | SecurityGroups: [ !Ref EcsSecurityGroup ] 985 | Scheme: internal 986 | HealthCheck: 987 | Target: TCP:3306 988 | HealthyThreshold: '2' 989 | UnhealthyThreshold: '10' 990 | Interval: '30' 991 | Timeout: '5' 992 | Listeners: 993 | - LoadBalancerPort: '3306' 994 | InstancePort: '3306' 995 | Protocol: TCP 996 | 997 | ECSELBMySQLUat: 998 | Type: AWS::ElasticLoadBalancing::LoadBalancer 999 | Properties: 1000 | LoadBalancerName: 1001 | Fn::Sub: ${AWS::StackName}-mysql-uat 1002 | Subnets: 1003 | - !Ref SubnetID1 1004 | - !Ref SubnetID2 1005 | SecurityGroups: [ !Ref EcsSecurityGroup ] 1006 | Scheme: internal 1007 | HealthCheck: 1008 | Target: TCP:3306 1009 | HealthyThreshold: '2' 1010 | UnhealthyThreshold: '10' 1011 | Interval: '30' 1012 | Timeout: '5' 1013 | Listeners: 1014 | - LoadBalancerPort: '3306' 1015 | InstancePort: '3306' 1016 | Protocol: TCP 1017 | 1018 | ServiceMySQLProd: 1019 | Type: AWS::ECS::Service 1020 | Properties: 1021 | Cluster: !Ref EcsCluster 1022 | LoadBalancers: 1023 | - ContainerName: mysql 1024 | ContainerPort: '3306' 1025 | LoadBalancerName: !Ref 'ECSELBMySQLProd' 1026 | DeploymentConfiguration: 1027 | MaximumPercent: 100 1028 | MinimumHealthyPercent: 50 1029 | TaskDefinition: !Ref ProdMySQLTaskDefinition 1030 | Role: !Ref 'ECSServiceRole' 1031 | DesiredCount: 1 1032 | 1033 | ServiceMySQLUat: 1034 | Type: AWS::ECS::Service 1035 | Properties: 1036 | Cluster: !Ref EcsCluster 1037 | LoadBalancers: 1038 | - ContainerName: mysql 1039 | ContainerPort: '3306' 1040 | LoadBalancerName: !Ref 'ECSELBMySQLUat' 1041 | DeploymentConfiguration: 1042 | MaximumPercent: 100 1043 | MinimumHealthyPercent: 50 1044 | TaskDefinition: !Ref UatMySQLTaskDefinition 1045 | Role: !Ref 'ECSServiceRole' 1046 | DesiredCount: 1 1047 | 1048 | MonitoringTaskDefinition: 1049 | Type: AWS::ECS::TaskDefinition 1050 | Properties: 1051 | NetworkMode: host 1052 | ContainerDefinitions: 1053 | - Name: node-exporter 1054 | Image: 1055 | Ref: NodeExporterImage 1056 | Memory: 256 1057 | PortMappings: 1058 | - ContainerPort: 9100 1059 | LogConfiguration: 1060 | LogDriver: awslogs 1061 | Options: 1062 | awslogs-region: 1063 | Ref: AWS::Region 1064 | awslogs-group: !Ref LogGroup 1065 | awslogs-stream-prefix: 1066 | Ref: AWS::StackName 1067 | - Name: pcp 1068 | Image: 1069 | Ref: PcpImage 1070 | Memory: 256 1071 | Privileged: true 1072 | PortMappings: 1073 | - ContainerPort: 9990 1074 | MountPoints: 1075 | - ContainerPath: /var/lib/docker 1076 | SourceVolume: docker 1077 | ReadOnly: true 1078 | - ContainerPath: /sys 1079 | SourceVolume: sys 1080 | ReadOnly: true 1081 | - ContainerPath: /var/run 1082 | SourceVolume: run 1083 | ReadOnly: false 1084 | - ContainerPath: /rootfs 1085 | SourceVolume: rootfs 1086 | ReadOnly: true 1087 | - ContainerPath: /cgroup 1088 | SourceVolume: cgroup 1089 | ReadOnly: true 1090 | - ContainerPath: /etc/localtime 1091 | SourceVolume: localtime 1092 | ReadOnly: true 1093 | LogConfiguration: 1094 | LogDriver: awslogs 1095 | Options: 1096 | awslogs-region: 1097 | Ref: AWS::Region 1098 | awslogs-group: !Ref LogGroup 1099 | awslogs-stream-prefix: 1100 | Ref: AWS::StackName 1101 | - Name: cadvisor 1102 | Image: 1103 | Ref: CadvisorImage 1104 | Memory: 256 1105 | Privileged: true 1106 | PortMappings: 1107 | - ContainerPort: 8080 1108 | MountPoints: 1109 | - ContainerPath: /var/lib/docker 1110 | SourceVolume: docker 1111 | ReadOnly: true 1112 | - ContainerPath: /sys 1113 | SourceVolume: sys 1114 | ReadOnly: true 1115 | - ContainerPath: /var/run 1116 | SourceVolume: run 1117 | ReadOnly: false 1118 | - ContainerPath: /rootfs 1119 | SourceVolume: rootfs 1120 | ReadOnly: true 1121 | - ContainerPath: /cgroup 1122 | SourceVolume: cgroup 1123 | ReadOnly: true 1124 | LogConfiguration: 1125 | LogDriver: awslogs 1126 | Options: 1127 | awslogs-region: 1128 | Ref: AWS::Region 1129 | awslogs-group: !Ref LogGroup 1130 | awslogs-stream-prefix: 1131 | Ref: AWS::StackName 1132 | Volumes: 1133 | - Name: cgroup 1134 | Host: 1135 | SourcePath: /cgroup 1136 | - Name: docker 1137 | Host: 1138 | SourcePath: /var/lib/docker/ 1139 | - Name: docker-sock 1140 | Host: 1141 | SourcePath: /var/run/docker.sock 1142 | - Name: run 1143 | Host: 1144 | SourcePath: /var/run 1145 | - Name: rootfs 1146 | Host: 1147 | SourcePath: / 1148 | - Name: sys 1149 | Host: 1150 | SourcePath: /sys 1151 | - Name: localtime 1152 | Host: 1153 | SourcePath: /etc/localtime 1154 | 1155 | MonitoringService: 1156 | Type: AWS::ECS::Service 1157 | Properties: 1158 | Cluster: 1159 | Ref: EcsCluster 1160 | TaskDefinition: 1161 | Ref: MonitoringTaskDefinition 1162 | DeploymentConfiguration: 1163 | MaximumPercent: 100 1164 | MinimumHealthyPercent: 0 1165 | DesiredCount: 1166 | Ref: AsgMinSize 1167 | 1168 | 1169 | Outputs: 1170 | 1171 | Asg: 1172 | Value: 1173 | Ref: Asg 1174 | 1175 | EcsCluster: 1176 | Export: 1177 | Name: 1178 | Fn::Sub: ${AWS::StackName}-EcsCluster 1179 | Value: 1180 | Ref: EcsCluster 1181 | 1182 | WebsiteProd: 1183 | Description: WebSiteProd 1184 | Value: !Join ['', ['http://',!GetAtt [ECSALBProd, DNSName]]] 1185 | 1186 | MySQLProd: 1187 | Description: MySQLProd 1188 | Value: !GetAtt ECSELBMySQLProd.DNSName 1189 | 1190 | WebsiteUat: 1191 | Description: WebSiteUat 1192 | Value: !Join ['', ['http://',!GetAtt [ECSALBUat, DNSName]]] 1193 | 1194 | MySQLUat: 1195 | Description: MySQLUat 1196 | Value: !GetAtt ECSELBMySQLUat.DNSName 1197 | --------------------------------------------------------------------------------