1
0
mirror of https://github.com/ebosas/microservices.git synced 2025-02-16 18:34:37 +02:00

Combine Fargate and EC2 services

This commit is contained in:
ebosas 2021-11-13 14:31:05 +02:00
parent 6deb667242
commit da53ff6e38
12 changed files with 127 additions and 869 deletions

View File

@ -11,10 +11,10 @@ Parameters:
EnvironmentName: EnvironmentName:
Type: String Type: String
Default: production Default: production
DeploymentType: LaunchType:
Type: String Type: String
Default: fargate Default: fargate
AllowedValues: [ecs, fargate] AllowedValues: [fargate, ec2]
Resources: Resources:
@ -234,7 +234,7 @@ Resources:
ActionMode: CREATE_UPDATE ActionMode: CREATE_UPDATE
RoleArn: !GetAtt CloudFormationDeployRole.Arn RoleArn: !GetAtt CloudFormationDeployRole.Arn
StackName: !Sub ${EnvironmentName}-Cluster StackName: !Sub ${EnvironmentName}-Cluster
TemplatePath: !Sub Source::deployments/cluster-${DeploymentType}.yml TemplatePath: !Sub Source::deployments/cluster-${LaunchType}.yml
Capabilities: CAPABILITY_IAM Capabilities: CAPABILITY_IAM
ParameterOverrides: !Sub | ParameterOverrides: !Sub |
{ {

View File

@ -11,10 +11,10 @@ Parameters:
EnvironmentName: EnvironmentName:
Type: String Type: String
Default: production Default: production
DeploymentType: LaunchType:
Type: String Type: String
Default: fargate Default: fargate
AllowedValues: [ecs, fargate] AllowedValues: [fargate, ec2]
Resources: Resources:
@ -166,7 +166,7 @@ Resources:
# ActionMode: CREATE_UPDATE # ActionMode: CREATE_UPDATE
# RoleArn: !GetAtt CloudFormationDeployRole.Arn # RoleArn: !GetAtt CloudFormationDeployRole.Arn
# StackName: !Sub ${EnvironmentName}-Cluster # StackName: !Sub ${EnvironmentName}-Cluster
# TemplatePath: !Sub Source::deployments/cluster-${DeploymentType}.yml # TemplatePath: !Sub Source::deployments/cluster-${LaunchType}.yml
# Capabilities: CAPABILITY_IAM # Capabilities: CAPABILITY_IAM
# ParameterOverrides: !Sub | # ParameterOverrides: !Sub |
# { # {
@ -191,12 +191,13 @@ Resources:
# ActionMode: CREATE_UPDATE # ActionMode: CREATE_UPDATE
# RoleArn: !GetAtt CloudFormationDeployRole.Arn # RoleArn: !GetAtt CloudFormationDeployRole.Arn
# StackName: !Sub ${EnvironmentName}-Server-Service # StackName: !Sub ${EnvironmentName}-Server-Service
# TemplatePath: !Sub Source::deployments/services-${DeploymentType}/server.yml # TemplatePath: Source::deployments/services/server.yml
# Capabilities: CAPABILITY_IAM # Capabilities: CAPABILITY_IAM
# ParameterOverrides: !Sub | # ParameterOverrides: !Sub |
# { # {
# "ServiceName": "server", # "ServiceName": "server",
# "EnvironmentName": "${EnvironmentName}", # "EnvironmentName": "${EnvironmentName}",
# "LaunchType": "${LaunchType}",
# "ImageUrl": "amazon/amazon-ecs-sample" # "ImageUrl": "amazon/amazon-ecs-sample"
# } # }
# InputArtifacts: # InputArtifacts:
@ -212,12 +213,13 @@ Resources:
# ActionMode: CREATE_UPDATE # ActionMode: CREATE_UPDATE
# RoleArn: !GetAtt CloudFormationDeployRole.Arn # RoleArn: !GetAtt CloudFormationDeployRole.Arn
# StackName: !Sub ${EnvironmentName}-Cache-Service # StackName: !Sub ${EnvironmentName}-Cache-Service
# TemplatePath: !Sub Source::deployments/services-${DeploymentType}/cache.yml # TemplatePath: Source::deployments/services/cache.yml
# Capabilities: CAPABILITY_IAM # Capabilities: CAPABILITY_IAM
# ParameterOverrides: !Sub | # ParameterOverrides: !Sub |
# { # {
# "ServiceName": "cache", # "ServiceName": "cache",
# "EnvironmentName": "${EnvironmentName}", # "EnvironmentName": "${EnvironmentName}",
# "LaunchType": "${LaunchType}",
# "ImageUrl": "amazon/amazon-ecs-sample" # "ImageUrl": "amazon/amazon-ecs-sample"
# } # }
# InputArtifacts: # InputArtifacts:
@ -233,13 +235,14 @@ Resources:
ActionMode: CREATE_UPDATE ActionMode: CREATE_UPDATE
RoleArn: !GetAtt CloudFormationDeployRole.Arn RoleArn: !GetAtt CloudFormationDeployRole.Arn
StackName: !Sub ${EnvironmentName}-Database-Service StackName: !Sub ${EnvironmentName}-Database-Service
TemplatePath: !Sub Source::deployments/services-${DeploymentType}/database.yml TemplatePath: Source::deployments/services/database.yml
Capabilities: CAPABILITY_IAM Capabilities: CAPABILITY_IAM
# Don't have an image at this point, using a sample image # Using a sample image at this point
ParameterOverrides: !Sub | ParameterOverrides: !Sub |
{ {
"ServiceName": "database", "ServiceName": "database",
"EnvironmentName": "${EnvironmentName}", "EnvironmentName": "${EnvironmentName}",
"LaunchType": "${LaunchType}",
"ImageUrl": "amazon/amazon-ecs-sample" "ImageUrl": "amazon/amazon-ecs-sample"
} }
InputArtifacts: InputArtifacts:
@ -262,7 +265,7 @@ Resources:
# ActionMode: CREATE_UPDATE # ActionMode: CREATE_UPDATE
# RoleArn: !GetAtt CloudFormationDeployRole.Arn # RoleArn: !GetAtt CloudFormationDeployRole.Arn
# StackName: !Sub ${EnvironmentName}-Server-Pipeline # StackName: !Sub ${EnvironmentName}-Server-Pipeline
# TemplatePath: Source::deployments/pipeline-service.yml # TemplatePath: Source::deployments/service-pipeline.yml
# Capabilities: CAPABILITY_IAM # Capabilities: CAPABILITY_IAM
# ParameterOverrides: !Sub | # ParameterOverrides: !Sub |
# { # {
@ -286,7 +289,7 @@ Resources:
# ActionMode: CREATE_UPDATE # ActionMode: CREATE_UPDATE
# RoleArn: !GetAtt CloudFormationDeployRole.Arn # RoleArn: !GetAtt CloudFormationDeployRole.Arn
# StackName: !Sub ${EnvironmentName}-Cache-Pipeline # StackName: !Sub ${EnvironmentName}-Cache-Pipeline
# TemplatePath: Source::deployments/pipeline-service.yml # TemplatePath: Source::deployments/service-pipeline.yml
# Capabilities: CAPABILITY_IAM # Capabilities: CAPABILITY_IAM
# ParameterOverrides: !Sub | # ParameterOverrides: !Sub |
# { # {
@ -310,7 +313,7 @@ Resources:
ActionMode: CREATE_UPDATE ActionMode: CREATE_UPDATE
RoleArn: !GetAtt CloudFormationDeployRole.Arn RoleArn: !GetAtt CloudFormationDeployRole.Arn
StackName: !Sub ${EnvironmentName}-Database-Pipeline StackName: !Sub ${EnvironmentName}-Database-Pipeline
TemplatePath: Source::deployments/pipeline-service.yml TemplatePath: Source::deployments/service-pipeline.yml
Capabilities: CAPABILITY_IAM Capabilities: CAPABILITY_IAM
ParameterOverrides: !Sub | ParameterOverrides: !Sub |
{ {
@ -441,18 +444,18 @@ Resources:
Resource: "*" Resource: "*"
#-----------------------------------------------------------------------------# #-----------------------------------------------------------------------------#
# Parameter Store # SSM Parameter Store
#-----------------------------------------------------------------------------# #-----------------------------------------------------------------------------#
SSMArtifactBucket: SSMArtifactBucket:
Type: AWS::SSM::Parameter Type: AWS::SSM::Parameter
Properties: Properties:
Name: /microservices/artifact_bucket Name: /Microservices/ArtifactBucket
Type: String Type: String
Value: !Ref ArtifactBucket Value: !Ref ArtifactBucket
SSMCodePipelineServiceRoleArn: SSMCodePipelineServiceRoleArn:
Type: AWS::SSM::Parameter Type: AWS::SSM::Parameter
Properties: Properties:
Name: /microservices/codepipeline_service_role_arn Name: /Microservices/CodePipelineServiceRoleArn
Type: String Type: String
Value: !GetAtt CodePipelineServiceRole.Arn Value: !GetAtt CodePipelineServiceRole.Arn

View File

@ -11,10 +11,10 @@ Parameters:
EnvironmentName: EnvironmentName:
Type: String Type: String
Default: production Default: production
DeploymentType: LaunchType:
Type: String Type: String
Default: fargate Default: fargate
AllowedValues: [ecs, fargate] AllowedValues: [fargate, ec2]
Resources: Resources:
# Create ECR respositories to hold built docker images # Create ECR respositories to hold built docker images
@ -314,7 +314,7 @@ Resources:
ActionMode: CREATE_UPDATE ActionMode: CREATE_UPDATE
RoleArn: !GetAtt CloudFormationDeployRole.Arn RoleArn: !GetAtt CloudFormationDeployRole.Arn
StackName: !Sub ${EnvironmentName}-Cluster StackName: !Sub ${EnvironmentName}-Cluster
TemplatePath: !Sub Source::deployments/cluster-${DeploymentType}.yml TemplatePath: !Sub Source::deployments/cluster-${LaunchType}.yml
Capabilities: CAPABILITY_IAM Capabilities: CAPABILITY_IAM
ParameterOverrides: !Sub | ParameterOverrides: !Sub |
{ {
@ -384,11 +384,12 @@ Resources:
ActionMode: CREATE_UPDATE ActionMode: CREATE_UPDATE
RoleArn: !GetAtt CloudFormationDeployRole.Arn RoleArn: !GetAtt CloudFormationDeployRole.Arn
StackName: !Sub ${EnvironmentName}-ServerService StackName: !Sub ${EnvironmentName}-ServerService
TemplatePath: !Sub Source::deployments/services-${DeploymentType}/server.yml TemplatePath: Source::deployments/services/server.yml
Capabilities: CAPABILITY_IAM Capabilities: CAPABILITY_IAM
ParameterOverrides: !Sub | ParameterOverrides: !Sub |
{ {
"EnvironmentName": "${EnvironmentName}", "EnvironmentName": "${EnvironmentName}",
"LaunchType": "${LaunchType}",
"ImageUrl": { "ImageUrl": {
"Fn::GetParam" : ["BuildOutput", "build.json", "ImageServerUri"] "Fn::GetParam" : ["BuildOutput", "build.json", "ImageServerUri"]
} }
@ -408,11 +409,12 @@ Resources:
ActionMode: CREATE_UPDATE ActionMode: CREATE_UPDATE
RoleArn: !GetAtt CloudFormationDeployRole.Arn RoleArn: !GetAtt CloudFormationDeployRole.Arn
StackName: !Sub ${EnvironmentName}-CacheService StackName: !Sub ${EnvironmentName}-CacheService
TemplatePath: !Sub Source::deployments/services-${DeploymentType}/cache.yml TemplatePath: Source::deployments/services/cache.yml
Capabilities: CAPABILITY_IAM Capabilities: CAPABILITY_IAM
ParameterOverrides: !Sub | ParameterOverrides: !Sub |
{ {
"EnvironmentName": "${EnvironmentName}", "EnvironmentName": "${EnvironmentName}",
"LaunchType": "${LaunchType}",
"ImageUrl": { "ImageUrl": {
"Fn::GetParam" : ["BuildOutput", "build.json", "ImageCacheUri"] "Fn::GetParam" : ["BuildOutput", "build.json", "ImageCacheUri"]
} }
@ -432,11 +434,12 @@ Resources:
ActionMode: CREATE_UPDATE ActionMode: CREATE_UPDATE
RoleArn: !GetAtt CloudFormationDeployRole.Arn RoleArn: !GetAtt CloudFormationDeployRole.Arn
StackName: !Sub ${EnvironmentName}-DatabaseService StackName: !Sub ${EnvironmentName}-DatabaseService
TemplatePath: !Sub Source::deployments/services-${DeploymentType}/database.yml TemplatePath: Source::deployments/services/database.yml
Capabilities: CAPABILITY_IAM Capabilities: CAPABILITY_IAM
ParameterOverrides: !Sub | ParameterOverrides: !Sub |
{ {
"EnvironmentName": "${EnvironmentName}", "EnvironmentName": "${EnvironmentName}",
"LaunchType": "${LaunchType}",
"ImageUrl": { "ImageUrl": {
"Fn::GetParam" : ["BuildOutput", "build.json", "ImageDatabaseUri"] "Fn::GetParam" : ["BuildOutput", "build.json", "ImageDatabaseUri"]
} }

View File

@ -3,18 +3,11 @@ Parameters:
Type: String Type: String
GitHubBranch: GitHubBranch:
Type: String Type: String
# GitHubToken:
# Type: String
# NoEcho: true
GitHubUser: GitHubUser:
Type: String Type: String
EnvironmentName: EnvironmentName:
Type: String Type: String
Default: production Default: production
# DeploymentType:
# Type: String
# Default: fargate
# AllowedValues: [ecs, fargate]
ServiceName: ServiceName:
Type: String Type: String
Description: The name of the service Description: The name of the service
@ -25,10 +18,10 @@ Parameters:
Default: \[BuildAll\] Default: \[BuildAll\]
ArtifactBucket: ArtifactBucket:
Type: AWS::SSM::Parameter::Value<String> Type: AWS::SSM::Parameter::Value<String>
Default: /microservices/artifact_bucket Default: /Microservices/ArtifactBucket
CodePipelineServiceRoleArn: CodePipelineServiceRoleArn:
Type: AWS::SSM::Parameter::Value<String> Type: AWS::SSM::Parameter::Value<String>
Default: /microservices/codepipeline_service_role_arn Default: /Microservices/CodePipelineServiceRoleArn
Resources: Resources:
@ -71,8 +64,6 @@ Resources:
Value: !Ref ServiceName Value: !Ref ServiceName
- Name: REPO_URI - Name: REPO_URI
Value: !Sub ${Repository.RepositoryUri} Value: !Sub ${Repository.RepositoryUri}
- Name: ARTIFACT_BUCKET
Value: !Ref ArtifactBucket
Triggers: Triggers:
Webhook: true Webhook: true
FilterGroups: FilterGroups:
@ -85,15 +76,6 @@ Resources:
- Type: COMMIT_MESSAGE - Type: COMMIT_MESSAGE
Pattern: !Ref TriggerPattern Pattern: !Ref TriggerPattern
ExcludeMatchedPattern: false ExcludeMatchedPattern: false
# - - Type: EVENT
# Pattern: PUSH
# ExcludeMatchedPattern: false
# - Type: HEAD_REF
# Pattern: !Sub ^refs/heads/${GitHubBranch}$
# ExcludeMatchedPattern: false
# - Type: FILE_PATH
# Pattern: ^(cmd/server/|internal/|web/|server.Dockerfile)
# ExcludeMatchedPattern: false
ServiceRole: !Ref CodeBuildServiceRole ServiceRole: !Ref CodeBuildServiceRole
TimeoutInMinutes: 10 TimeoutInMinutes: 10
@ -112,7 +94,7 @@ Resources:
Targets: Targets:
- Arn: !Sub arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${Pipeline} - Arn: !Sub arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${Pipeline}
RoleArn: !GetAtt CloudWatchEventRole.Arn RoleArn: !GetAtt CloudWatchEventRole.Arn
Id: server-pipeline Id: !Sub ${ServiceName}-pipeline
Pipeline: Pipeline:
Type: AWS::CodePipeline::Pipeline Type: AWS::CodePipeline::Pipeline

View File

@ -1,237 +0,0 @@
AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy a service into an ECS cluster behind a public load balancer.
Parameters:
EnvironmentName:
Type: String
Default: production
Description: The name of the environment to add this service to
ServiceName:
Type: String
Default: cache
Description: A name for the service
ImageUrl:
Type: String
Description: The url of a docker image that contains the application process that
will handle the traffic for this service
ContainerCpu:
Type: Number
Default: 256
Description: How much CPU to give the container. 1024 is 1 CPU
ContainerMemory:
Type: Number
Default: 230
Description: How much memory in megabytes to give the container
DesiredCount:
Type: Number
Default: 1
Description: How many copies of the service task to run
Role:
Type: String
Default: ""
Description: (Optional) An IAM role to give the service's containers if the code within needs to
access other AWS resources like S3 buckets, DynamoDB tables, etc
Conditions:
HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ]
Resources:
# A log group for storing the stdout logs from this service's containers
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub ${EnvironmentName}-service-${ServiceName}
# The task definition. This is a simple metadata description of what
# container to run, and what resource requirements it has.
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory'
TaskRoleArn:
Fn::If:
- 'HasCustomRole'
- !Ref 'Role'
- !Ref "AWS::NoValue"
ContainerDefinitions:
- Name: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory'
# Image: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/microservices/${ServiceName}:latest
Image: !Ref ImageUrl
LogConfiguration:
LogDriver: 'awslogs'
Options:
awslogs-group: !Sub ${EnvironmentName}-service-${ServiceName}
awslogs-region: !Ref 'AWS::Region'
awslogs-stream-prefix: !Ref 'ServiceName'
Environment:
- Name: RABBIT_URL
Value: '{{resolve:ssm:/Microservices/RabbitUrl}}'
- Name: REDIS_URL
Value: '{{resolve:ssm:/Microservices/RedisUrl}}'
# The service. The service is a resource which allows you to run multiple
# copies of a type of task, and gather up their logs and metrics, as well
# as monitor the number of running tasks and replace any that have crashed
Service:
Type: AWS::ECS::Service
Properties:
ServiceName: !Ref 'ServiceName'
Cluster:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition'
PlacementStrategies:
- Field: memory
Type: binpack
# Enable autoscaling for this service
ScalableTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget
DependsOn: Service
Properties:
ServiceNamespace: 'ecs'
ScalableDimension: 'ecs:service:DesiredCount'
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
MinCapacity: 1
MaxCapacity: 10
RoleARN:
Fn::ImportValue: !Sub ${EnvironmentName}:AutoscalingRole
# Create scaling policies for the service
ScaleDownPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
DependsOn: ScalableTarget
Properties:
PolicyName:
Fn::Join:
- '/'
- - scale
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
- down
PolicyType: StepScaling
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
ScalableDimension: 'ecs:service:DesiredCount'
ServiceNamespace: 'ecs'
StepScalingPolicyConfiguration:
AdjustmentType: 'ChangeInCapacity'
StepAdjustments:
- MetricIntervalUpperBound: 0
ScalingAdjustment: -1
MetricAggregationType: 'Average'
Cooldown: 60
ScaleUpPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
DependsOn: ScalableTarget
Properties:
PolicyName:
Fn::Join:
- '/'
- - scale
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
- up
PolicyType: StepScaling
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
ScalableDimension: 'ecs:service:DesiredCount'
ServiceNamespace: 'ecs'
StepScalingPolicyConfiguration:
AdjustmentType: 'ChangeInCapacity'
StepAdjustments:
- MetricIntervalLowerBound: 0
MetricIntervalUpperBound: 15
ScalingAdjustment: 1
- MetricIntervalLowerBound: 15
MetricIntervalUpperBound: 25
ScalingAdjustment: 2
- MetricIntervalLowerBound: 25
ScalingAdjustment: 3
MetricAggregationType: 'Average'
Cooldown: 60
# Create alarms to trigger these policies
LowCpuUsageAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName:
Fn::Join:
- '-'
- - low-cpu
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
AlarmDescription:
Fn::Join:
- ' '
- - "Low CPU utilization for service"
- !Ref 'ServiceName'
- "in environment"
- !Ref 'EnvironmentName'
MetricName: CPUUtilization
Namespace: AWS/ECS
Dimensions:
- Name: ServiceName
Value: !Ref 'ServiceName'
- Name: ClusterName
Value:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
Statistic: Average
Period: 60
EvaluationPeriods: 1
Threshold: 20
ComparisonOperator: LessThanOrEqualToThreshold
AlarmActions:
- !Ref ScaleDownPolicy
HighCpuUsageAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName:
Fn::Join:
- '-'
- - high-cpu
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
AlarmDescription:
Fn::Join:
- ' '
- - "High CPU utilization for service"
- !Ref 'ServiceName'
- "in environment"
- !Ref 'EnvironmentName'
MetricName: CPUUtilization
Namespace: AWS/ECS
Dimensions:
- Name: ServiceName
Value: !Ref 'ServiceName'
- Name: ClusterName
Value:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
Statistic: Average
Period: 60
EvaluationPeriods: 1
Threshold: 70
ComparisonOperator: GreaterThanOrEqualToThreshold
AlarmActions:
- !Ref ScaleUpPolicy

View File

@ -1,237 +0,0 @@
AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy a service into an ECS cluster behind a public load balancer.
Parameters:
EnvironmentName:
Type: String
Default: production
Description: The name of the environment to add this service to
ServiceName:
Type: String
Default: database
Description: A name for the service
ImageUrl:
Type: String
Description: The url of a docker image that contains the application process that
will handle the traffic for this service
ContainerCpu:
Type: Number
Default: 256
Description: How much CPU to give the container. 1024 is 1 CPU
ContainerMemory:
Type: Number
Default: 230
Description: How much memory in megabytes to give the container
DesiredCount:
Type: Number
Default: 1
Description: How many copies of the service task to run
Role:
Type: String
Default: ""
Description: (Optional) An IAM role to give the service's containers if the code within needs to
access other AWS resources like S3 buckets, DynamoDB tables, etc
Conditions:
HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ]
Resources:
# A log group for storing the stdout logs from this service's containers
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub ${EnvironmentName}-service-${ServiceName}
# The task definition. This is a simple metadata description of what
# container to run, and what resource requirements it has.
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory'
TaskRoleArn:
Fn::If:
- 'HasCustomRole'
- !Ref 'Role'
- !Ref "AWS::NoValue"
ContainerDefinitions:
- Name: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory'
# Image: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/microservices/${ServiceName}:latest
Image: !Ref ImageUrl
LogConfiguration:
LogDriver: 'awslogs'
Options:
awslogs-group: !Sub ${EnvironmentName}-service-${ServiceName}
awslogs-region: !Ref 'AWS::Region'
awslogs-stream-prefix: !Ref 'ServiceName'
Environment:
- Name: RABBIT_URL
Value: '{{resolve:ssm:/Microservices/RabbitUrl}}'
- Name: POSTGRES_URL
Value: '{{resolve:ssm:/Microservices/PostgresUrl}}'
# The service. The service is a resource which allows you to run multiple
# copies of a type of task, and gather up their logs and metrics, as well
# as monitor the number of running tasks and replace any that have crashed
Service:
Type: AWS::ECS::Service
Properties:
ServiceName: !Ref 'ServiceName'
Cluster:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition'
PlacementStrategies:
- Field: memory
Type: binpack
# Enable autoscaling for this service
ScalableTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget
DependsOn: Service
Properties:
ServiceNamespace: 'ecs'
ScalableDimension: 'ecs:service:DesiredCount'
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
MinCapacity: 1
MaxCapacity: 10
RoleARN:
Fn::ImportValue: !Sub ${EnvironmentName}:AutoscalingRole
# Create scaling policies for the service
ScaleDownPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
DependsOn: ScalableTarget
Properties:
PolicyName:
Fn::Join:
- '/'
- - scale
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
- down
PolicyType: StepScaling
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
ScalableDimension: 'ecs:service:DesiredCount'
ServiceNamespace: 'ecs'
StepScalingPolicyConfiguration:
AdjustmentType: 'ChangeInCapacity'
StepAdjustments:
- MetricIntervalUpperBound: 0
ScalingAdjustment: -1
MetricAggregationType: 'Average'
Cooldown: 60
ScaleUpPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
DependsOn: ScalableTarget
Properties:
PolicyName:
Fn::Join:
- '/'
- - scale
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
- up
PolicyType: StepScaling
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
ScalableDimension: 'ecs:service:DesiredCount'
ServiceNamespace: 'ecs'
StepScalingPolicyConfiguration:
AdjustmentType: 'ChangeInCapacity'
StepAdjustments:
- MetricIntervalLowerBound: 0
MetricIntervalUpperBound: 15
ScalingAdjustment: 1
- MetricIntervalLowerBound: 15
MetricIntervalUpperBound: 25
ScalingAdjustment: 2
- MetricIntervalLowerBound: 25
ScalingAdjustment: 3
MetricAggregationType: 'Average'
Cooldown: 60
# Create alarms to trigger these policies
LowCpuUsageAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName:
Fn::Join:
- '-'
- - low-cpu
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
AlarmDescription:
Fn::Join:
- ' '
- - "Low CPU utilization for service"
- !Ref 'ServiceName'
- "in environment"
- !Ref 'EnvironmentName'
MetricName: CPUUtilization
Namespace: AWS/ECS
Dimensions:
- Name: ServiceName
Value: !Ref 'ServiceName'
- Name: ClusterName
Value:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
Statistic: Average
Period: 60
EvaluationPeriods: 1
Threshold: 20
ComparisonOperator: LessThanOrEqualToThreshold
AlarmActions:
- !Ref ScaleDownPolicy
HighCpuUsageAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName:
Fn::Join:
- '-'
- - high-cpu
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
AlarmDescription:
Fn::Join:
- ' '
- - "High CPU utilization for service"
- !Ref 'ServiceName'
- "in environment"
- !Ref 'EnvironmentName'
MetricName: CPUUtilization
Namespace: AWS/ECS
Dimensions:
- Name: ServiceName
Value: !Ref 'ServiceName'
- Name: ClusterName
Value:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
Statistic: Average
Period: 60
EvaluationPeriods: 1
Threshold: 70
ComparisonOperator: GreaterThanOrEqualToThreshold
AlarmActions:
- !Ref ScaleUpPolicy

View File

@ -1,299 +0,0 @@
AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy a service into an ECS cluster behind a public load balancer.
Parameters:
EnvironmentName:
Type: String
Default: production
Description: The name of the environment to add this service to
ServiceName:
Type: String
Default: server
Description: A name for the service
ImageUrl:
Type: String
Description: The url of a docker image that contains the application process that
will handle the traffic for this service
ContainerPort:
Type: Number
Default: 80
Description: What port number the application inside the docker container is binding to
ContainerCpu:
Type: Number
Default: 256
Description: How much CPU to give the container. 1024 is 1 CPU
ContainerMemory:
Type: Number
Default: 230
Description: How much memory in megabytes to give the container
Path:
Type: String
Default: "*"
Description: A path on the public load balancer that this service
should be connected to. Use * to send all load balancer
traffic to this service.
Priority:
Type: Number
Default: 1
Description: The priority for the routing rule added to the load balancer.
This only applies if your have multiple services which have been
assigned to different paths on the load balancer.
DesiredCount:
Type: Number
Default: 1
Description: How many copies of the service task to run
Role:
Type: String
Default: ""
Description: (Optional) An IAM role to give the service's containers if the code within needs to
access other AWS resources like S3 buckets, DynamoDB tables, etc
Conditions:
HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ]
Resources:
# A log group for storing the stdout logs from this service's containers
LogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub ${EnvironmentName}-service-${ServiceName}
# The task definition. This is a simple metadata description of what
# container to run, and what resource requirements it has.
TaskDefinition:
Type: AWS::ECS::TaskDefinition
Properties:
Family: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory'
TaskRoleArn:
Fn::If:
- 'HasCustomRole'
- !Ref 'Role'
- !Ref "AWS::NoValue"
ContainerDefinitions:
- Name: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory'
# Image: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/microservices/${ServiceName}:latest
Image: !Ref ImageUrl
PortMappings:
- ContainerPort: !Ref 'ContainerPort'
LogConfiguration:
LogDriver: 'awslogs'
Options:
awslogs-group: !Sub ${EnvironmentName}-service-${ServiceName}
awslogs-region: !Ref 'AWS::Region'
awslogs-stream-prefix: !Ref 'ServiceName'
Environment:
- Name: RABBIT_URL
Value: '{{resolve:ssm:/Microservices/RabbitUrl}}'
- Name: REDIS_URL
Value: '{{resolve:ssm:/Microservices/RedisUrl}}'
- Name: SERVER_ADDR
Value: 0.0.0.0:80
# The service. The service is a resource which allows you to run multiple
# copies of a type of task, and gather up their logs and metrics, as well
# as monitor the number of running tasks and replace any that have crashed
Service:
Type: AWS::ECS::Service
DependsOn: LoadBalancerRule
Properties:
ServiceName: !Ref 'ServiceName'
Cluster:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition'
PlacementStrategies:
- Field: memory
Type: binpack
LoadBalancers:
- ContainerName: !Ref 'ServiceName'
ContainerPort: !Ref 'ContainerPort'
TargetGroupArn: !Ref 'TargetGroup'
# A target group. This is used for keeping track of all the tasks, and
# what IP addresses / port numbers they have. You can query it yourself,
# to use the addresses yourself, but most often this target group is just
# connected to an application load balancer, or network load balancer, so
# it can automatically distribute traffic across all the targets.
TargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
HealthCheckIntervalSeconds: 6
HealthCheckPath: /
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 2
Name: !Ref 'ServiceName'
Port: 80
Protocol: HTTP
UnhealthyThresholdCount: 2
TargetGroupAttributes:
- Key: deregistration_delay.timeout_seconds
Value: 60
VpcId:
Fn::ImportValue: !Sub ${EnvironmentName}:VpcId
# Create a rule on the load balancer for routing traffic to the target group
LoadBalancerRule:
Type: AWS::ElasticLoadBalancingV2::ListenerRule
Properties:
Actions:
- TargetGroupArn: !Ref 'TargetGroup'
Type: 'forward'
Conditions:
- Field: path-pattern
Values: [!Ref 'Path']
ListenerArn:
Fn::ImportValue: !Sub ${EnvironmentName}:PublicListener
Priority: !Ref 'Priority'
# Enable autoscaling for this service
ScalableTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget
DependsOn: Service
Properties:
ServiceNamespace: 'ecs'
ScalableDimension: 'ecs:service:DesiredCount'
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
MinCapacity: 1
MaxCapacity: 10
RoleARN:
Fn::ImportValue: !Sub ${EnvironmentName}:AutoscalingRole
# Create scaling policies for the service
ScaleDownPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
DependsOn: ScalableTarget
Properties:
PolicyName:
Fn::Join:
- '/'
- - scale
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
- down
PolicyType: StepScaling
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
ScalableDimension: 'ecs:service:DesiredCount'
ServiceNamespace: 'ecs'
StepScalingPolicyConfiguration:
AdjustmentType: 'ChangeInCapacity'
StepAdjustments:
- MetricIntervalUpperBound: 0
ScalingAdjustment: -1
MetricAggregationType: 'Average'
Cooldown: 60
ScaleUpPolicy:
Type: AWS::ApplicationAutoScaling::ScalingPolicy
DependsOn: ScalableTarget
Properties:
PolicyName:
Fn::Join:
- '/'
- - scale
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
- up
PolicyType: StepScaling
ResourceId:
Fn::Join:
- '/'
- - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName'
ScalableDimension: 'ecs:service:DesiredCount'
ServiceNamespace: 'ecs'
StepScalingPolicyConfiguration:
AdjustmentType: 'ChangeInCapacity'
StepAdjustments:
- MetricIntervalLowerBound: 0
MetricIntervalUpperBound: 15
ScalingAdjustment: 1
- MetricIntervalLowerBound: 15
MetricIntervalUpperBound: 25
ScalingAdjustment: 2
- MetricIntervalLowerBound: 25
ScalingAdjustment: 3
MetricAggregationType: 'Average'
Cooldown: 60
# Create alarms to trigger these policies
LowCpuUsageAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName:
Fn::Join:
- '-'
- - low-cpu
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
AlarmDescription:
Fn::Join:
- ' '
- - "Low CPU utilization for service"
- !Ref 'ServiceName'
- "in environment"
- !Ref 'EnvironmentName'
MetricName: CPUUtilization
Namespace: AWS/ECS
Dimensions:
- Name: ServiceName
Value: !Ref 'ServiceName'
- Name: ClusterName
Value:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
Statistic: Average
Period: 60
EvaluationPeriods: 1
Threshold: 20
ComparisonOperator: LessThanOrEqualToThreshold
AlarmActions:
- !Ref ScaleDownPolicy
HighCpuUsageAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
AlarmName:
Fn::Join:
- '-'
- - high-cpu
- !Ref 'EnvironmentName'
- !Ref 'ServiceName'
AlarmDescription:
Fn::Join:
- ' '
- - "High CPU utilization for service"
- !Ref 'ServiceName'
- "in environment"
- !Ref 'EnvironmentName'
MetricName: CPUUtilization
Namespace: AWS/ECS
Dimensions:
- Name: ServiceName
Value: !Ref 'ServiceName'
- Name: ClusterName
Value:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
Statistic: Average
Period: 60
EvaluationPeriods: 1
Threshold: 70
ComparisonOperator: GreaterThanOrEqualToThreshold
AlarmActions:
- !Ref ScaleUpPolicy

View File

@ -1,5 +1,5 @@
AWSTemplateFormatVersion: '2010-09-09' AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy a service on AWS Fargate, accessible via a public load balancer. Description: Deploy a service into a Fargate/ECS cluster behind a public load balancer.
Parameters: Parameters:
EnvironmentName: EnvironmentName:
Type: String Type: String
@ -9,6 +9,10 @@ Parameters:
Type: String Type: String
Default: cache Default: cache
Description: A name for the service Description: A name for the service
LaunchType:
Type: String
Default: fargate
AllowedValues: [fargate, ec2]
ImageUrl: ImageUrl:
Type: String Type: String
Description: The url of a docker image that contains the application process that Description: The url of a docker image that contains the application process that
@ -28,11 +32,13 @@ Parameters:
Role: Role:
Type: String Type: String
Default: "" Default: ""
Description: (Optional) An IAM role to give the service's containers if the code within needs to Description: (Optional) An IAM role to give the service's containers if the code within
access other AWS resources like S3 buckets, DynamoDB tables, etc needs to access other AWS resources like S3 buckets, DynamoDB tables, etc
Conditions: Conditions:
HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ] HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ]
Fargate: !Equals [ !Ref LaunchType, 'fargate' ]
EC2: !Equals [ !Ref LaunchType, 'ec2' ]
Resources: Resources:
# A log group for storing the stdout logs from this service's containers # A log group for storing the stdout logs from this service's containers
@ -49,9 +55,9 @@ Resources:
Family: !Ref 'ServiceName' Family: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu' Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory' Memory: !Ref 'ContainerMemory'
NetworkMode: awsvpc NetworkMode: !If [ Fargate, "awsvpc", "bridge" ]
RequiresCompatibilities: RequiresCompatibilities:
- FARGATE - !If [ Fargate, "FARGATE", "EC2" ]
ExecutionRoleArn: ExecutionRoleArn:
Fn::ImportValue: !Sub ${EnvironmentName}:ECSTaskExecutionRole Fn::ImportValue: !Sub ${EnvironmentName}:ECSTaskExecutionRole
TaskRoleArn: TaskRoleArn:
@ -63,7 +69,6 @@ Resources:
- Name: !Ref 'ServiceName' - Name: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu' Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory' Memory: !Ref 'ContainerMemory'
# Image: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/microservices/${ServiceName}:latest
Image: !Ref ImageUrl Image: !Ref ImageUrl
LogConfiguration: LogConfiguration:
LogDriver: 'awslogs' LogDriver: 'awslogs'
@ -80,8 +85,9 @@ Resources:
# The service. The service is a resource which allows you to run multiple # The service. The service is a resource which allows you to run multiple
# copies of a type of task, and gather up their logs and metrics, as well # copies of a type of task, and gather up their logs and metrics, as well
# as monitor the number of running tasks and replace any that have crashed # as monitor the number of running tasks and replace any that have crashed
Service: FargateService:
Type: AWS::ECS::Service Type: AWS::ECS::Service
Condition: Fargate
Properties: Properties:
ServiceName: !Ref 'ServiceName' ServiceName: !Ref 'ServiceName'
Cluster: Cluster:
@ -91,6 +97,7 @@ Resources:
MaximumPercent: 200 MaximumPercent: 200
MinimumHealthyPercent: 75 MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount' DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition'
NetworkConfiguration: NetworkConfiguration:
AwsvpcConfiguration: AwsvpcConfiguration:
AssignPublicIp: ENABLED AssignPublicIp: ENABLED
@ -100,12 +107,26 @@ Resources:
# Choose private subnets if using NAT gateways # Choose private subnets if using NAT gateways
- Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetOne - Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetOne
- Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetTwo - Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetTwo
EC2Service:
Type: AWS::ECS::Service
Condition: EC2
Properties:
ServiceName: !Ref 'ServiceName'
Cluster:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition' TaskDefinition: !Ref 'TaskDefinition'
PlacementStrategies:
- Field: memory
Type: binpack
# Enable autoscaling for this service # Enable autoscaling for this service
ScalableTarget: ScalableTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget Type: AWS::ApplicationAutoScaling::ScalableTarget
DependsOn: Service
Properties: Properties:
ServiceNamespace: 'ecs' ServiceNamespace: 'ecs'
ScalableDimension: 'ecs:service:DesiredCount' ScalableDimension: 'ecs:service:DesiredCount'
@ -114,7 +135,7 @@ Resources:
- '/' - '/'
- - service - - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName - Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName' - !If [ Fargate, !GetAtt FargateService.Name, !GetAtt EC2Service.Name ]
MinCapacity: 1 MinCapacity: 1
MaxCapacity: 10 MaxCapacity: 10
RoleARN: RoleARN:

View File

@ -1,5 +1,5 @@
AWSTemplateFormatVersion: '2010-09-09' AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy a service on AWS Fargate, accessible via a public load balancer. Description: Deploy a service into a Fargate/ECS cluster behind a public load balancer.
Parameters: Parameters:
EnvironmentName: EnvironmentName:
Type: String Type: String
@ -9,6 +9,10 @@ Parameters:
Type: String Type: String
Default: database Default: database
Description: A name for the service Description: A name for the service
LaunchType:
Type: String
Default: fargate
AllowedValues: [fargate, ec2]
ImageUrl: ImageUrl:
Type: String Type: String
Description: The url of a docker image that contains the application process that Description: The url of a docker image that contains the application process that
@ -28,11 +32,13 @@ Parameters:
Role: Role:
Type: String Type: String
Default: "" Default: ""
Description: (Optional) An IAM role to give the service's containers if the code within needs to Description: (Optional) An IAM role to give the service's containers if the code within
access other AWS resources like S3 buckets, DynamoDB tables, etc needs to access other AWS resources like S3 buckets, DynamoDB tables, etc
Conditions: Conditions:
HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ] HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ]
Fargate: !Equals [ !Ref LaunchType, 'fargate' ]
EC2: !Equals [ !Ref LaunchType, 'ec2' ]
Resources: Resources:
# A log group for storing the stdout logs from this service's containers # A log group for storing the stdout logs from this service's containers
@ -49,9 +55,9 @@ Resources:
Family: !Ref 'ServiceName' Family: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu' Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory' Memory: !Ref 'ContainerMemory'
NetworkMode: awsvpc NetworkMode: !If [ Fargate, "awsvpc", "bridge" ]
RequiresCompatibilities: RequiresCompatibilities:
- FARGATE - !If [ Fargate, "FARGATE", "EC2" ]
ExecutionRoleArn: ExecutionRoleArn:
Fn::ImportValue: !Sub ${EnvironmentName}:ECSTaskExecutionRole Fn::ImportValue: !Sub ${EnvironmentName}:ECSTaskExecutionRole
TaskRoleArn: TaskRoleArn:
@ -63,7 +69,6 @@ Resources:
- Name: !Ref 'ServiceName' - Name: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu' Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory' Memory: !Ref 'ContainerMemory'
# Image: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/microservices/${ServiceName}:latest
Image: !Ref ImageUrl Image: !Ref ImageUrl
LogConfiguration: LogConfiguration:
LogDriver: 'awslogs' LogDriver: 'awslogs'
@ -80,8 +85,9 @@ Resources:
# The service. The service is a resource which allows you to run multiple # The service. The service is a resource which allows you to run multiple
# copies of a type of task, and gather up their logs and metrics, as well # copies of a type of task, and gather up their logs and metrics, as well
# as monitor the number of running tasks and replace any that have crashed # as monitor the number of running tasks and replace any that have crashed
Service: FargateService:
Type: AWS::ECS::Service Type: AWS::ECS::Service
Condition: Fargate
Properties: Properties:
ServiceName: !Ref 'ServiceName' ServiceName: !Ref 'ServiceName'
Cluster: Cluster:
@ -91,6 +97,7 @@ Resources:
MaximumPercent: 200 MaximumPercent: 200
MinimumHealthyPercent: 75 MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount' DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition'
NetworkConfiguration: NetworkConfiguration:
AwsvpcConfiguration: AwsvpcConfiguration:
AssignPublicIp: ENABLED AssignPublicIp: ENABLED
@ -100,12 +107,26 @@ Resources:
# Choose private subnets if using NAT gateways # Choose private subnets if using NAT gateways
- Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetOne - Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetOne
- Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetTwo - Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetTwo
EC2Service:
Type: AWS::ECS::Service
Condition: EC2
Properties:
ServiceName: !Ref 'ServiceName'
Cluster:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition' TaskDefinition: !Ref 'TaskDefinition'
PlacementStrategies:
- Field: memory
Type: binpack
# Enable autoscaling for this service # Enable autoscaling for this service
ScalableTarget: ScalableTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget Type: AWS::ApplicationAutoScaling::ScalableTarget
DependsOn: Service
Properties: Properties:
ServiceNamespace: 'ecs' ServiceNamespace: 'ecs'
ScalableDimension: 'ecs:service:DesiredCount' ScalableDimension: 'ecs:service:DesiredCount'
@ -114,7 +135,7 @@ Resources:
- '/' - '/'
- - service - - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName - Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName' - !If [ Fargate, !GetAtt FargateService.Name, !GetAtt EC2Service.Name ]
MinCapacity: 1 MinCapacity: 1
MaxCapacity: 10 MaxCapacity: 10
RoleARN: RoleARN:

View File

@ -1,5 +1,5 @@
AWSTemplateFormatVersion: '2010-09-09' AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy a service on AWS Fargate, accessible via a public load balancer. Description: Deploy a service into a Fargate/ECS cluster behind a public load balancer.
Parameters: Parameters:
EnvironmentName: EnvironmentName:
Type: String Type: String
@ -9,6 +9,10 @@ Parameters:
Type: String Type: String
Default: server Default: server
Description: A name for the service Description: A name for the service
LaunchType:
Type: String
Default: fargate
AllowedValues: [fargate, ec2]
ImageUrl: ImageUrl:
Type: String Type: String
Description: The url of a docker image that contains the application process that Description: The url of a docker image that contains the application process that
@ -44,11 +48,13 @@ Parameters:
Role: Role:
Type: String Type: String
Default: "" Default: ""
Description: (Optional) An IAM role to give the service's containers if the code within needs to Description: (Optional) An IAM role to give the service's containers if the code within
access other AWS resources like S3 buckets, DynamoDB tables, etc needs to access other AWS resources like S3 buckets, DynamoDB tables, etc
Conditions: Conditions:
HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ] HasCustomRole: !Not [ !Equals [!Ref 'Role', ''] ]
Fargate: !Equals [ !Ref LaunchType, 'fargate' ]
EC2: !Equals [ !Ref LaunchType, 'ec2' ]
Resources: Resources:
# A log group for storing the stdout logs from this service's containers # A log group for storing the stdout logs from this service's containers
@ -65,9 +71,9 @@ Resources:
Family: !Ref 'ServiceName' Family: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu' Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory' Memory: !Ref 'ContainerMemory'
NetworkMode: awsvpc NetworkMode: !If [ Fargate, "awsvpc", "bridge" ]
RequiresCompatibilities: RequiresCompatibilities:
- FARGATE - !If [ Fargate, "FARGATE", "EC2" ]
ExecutionRoleArn: ExecutionRoleArn:
Fn::ImportValue: !Sub ${EnvironmentName}:ECSTaskExecutionRole Fn::ImportValue: !Sub ${EnvironmentName}:ECSTaskExecutionRole
TaskRoleArn: TaskRoleArn:
@ -79,7 +85,6 @@ Resources:
- Name: !Ref 'ServiceName' - Name: !Ref 'ServiceName'
Cpu: !Ref 'ContainerCpu' Cpu: !Ref 'ContainerCpu'
Memory: !Ref 'ContainerMemory' Memory: !Ref 'ContainerMemory'
# Image: !Sub ${AWS::AccountId}.dkr.ecr.${AWS::Region}.amazonaws.com/microservices/${ServiceName}:latest
Image: !Ref ImageUrl Image: !Ref ImageUrl
PortMappings: PortMappings:
- ContainerPort: !Ref 'ContainerPort' - ContainerPort: !Ref 'ContainerPort'
@ -100,8 +105,9 @@ Resources:
# The service. The service is a resource which allows you to run multiple # The service. The service is a resource which allows you to run multiple
# copies of a type of task, and gather up their logs and metrics, as well # copies of a type of task, and gather up their logs and metrics, as well
# as monitor the number of running tasks and replace any that have crashed # as monitor the number of running tasks and replace any that have crashed
Service: FargateService:
Type: AWS::ECS::Service Type: AWS::ECS::Service
Condition: Fargate
DependsOn: LoadBalancerRule DependsOn: LoadBalancerRule
Properties: Properties:
ServiceName: !Ref 'ServiceName' ServiceName: !Ref 'ServiceName'
@ -112,6 +118,7 @@ Resources:
MaximumPercent: 200 MaximumPercent: 200
MinimumHealthyPercent: 75 MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount' DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition'
NetworkConfiguration: NetworkConfiguration:
AwsvpcConfiguration: AwsvpcConfiguration:
AssignPublicIp: ENABLED AssignPublicIp: ENABLED
@ -121,7 +128,27 @@ Resources:
# Choose private subnets if using NAT gateways # Choose private subnets if using NAT gateways
- Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetOne - Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetOne
- Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetTwo - Fn::ImportValue: !Sub ${EnvironmentName}:PublicSubnetTwo
LoadBalancers:
- ContainerName: !Ref 'ServiceName'
ContainerPort: !Ref 'ContainerPort'
TargetGroupArn: !Ref 'TargetGroup'
EC2Service:
Type: AWS::ECS::Service
Condition: EC2
DependsOn: LoadBalancerRule
Properties:
ServiceName: !Ref 'ServiceName'
Cluster:
Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
DeploymentConfiguration:
MaximumPercent: 200
MinimumHealthyPercent: 75
DesiredCount: !Ref 'DesiredCount'
TaskDefinition: !Ref 'TaskDefinition' TaskDefinition: !Ref 'TaskDefinition'
PlacementStrategies:
- Field: memory
Type: binpack
LoadBalancers: LoadBalancers:
- ContainerName: !Ref 'ServiceName' - ContainerName: !Ref 'ServiceName'
ContainerPort: !Ref 'ContainerPort' ContainerPort: !Ref 'ContainerPort'
@ -140,7 +167,7 @@ Resources:
HealthCheckProtocol: HTTP HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 5 HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 2 HealthyThresholdCount: 2
TargetType: ip TargetType: !If [ Fargate, "ip", !Ref AWS::NoValue ]
Name: !Ref 'ServiceName' Name: !Ref 'ServiceName'
Port: !Ref 'ContainerPort' Port: !Ref 'ContainerPort'
Protocol: HTTP Protocol: HTTP
@ -168,7 +195,6 @@ Resources:
# Enable autoscaling for this service # Enable autoscaling for this service
ScalableTarget: ScalableTarget:
Type: AWS::ApplicationAutoScaling::ScalableTarget Type: AWS::ApplicationAutoScaling::ScalableTarget
DependsOn: Service
Properties: Properties:
ServiceNamespace: 'ecs' ServiceNamespace: 'ecs'
ScalableDimension: 'ecs:service:DesiredCount' ScalableDimension: 'ecs:service:DesiredCount'
@ -177,7 +203,7 @@ Resources:
- '/' - '/'
- - service - - service
- Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName - Fn::ImportValue: !Sub ${EnvironmentName}:ClusterName
- !Ref 'ServiceName' - !If [ Fargate, !GetAtt FargateService.Name, !GetAtt EC2Service.Name ]
MinCapacity: 1 MinCapacity: 1
MaxCapacity: 10 MaxCapacity: 10
RoleARN: RoleARN:

View File

@ -1,25 +0,0 @@
# Parameters:
# GitHubRepo:
# Type: String
# GitHubBranch:
# Type: String
# GitHubToken:
# Type: String
# NoEcho: true
# GitHubUser:
# Type: String
# EnvironmentName:
# Type: String
# Default: production
# DeploymentType:
# Type: String
# Default: fargate
# AllowedValues: [ecs, fargate]
Resources:
CodeStarConnection:
Type: AWS::CodeStarConnections::Connection
Properties:
ConnectionName: MyGitHubConnection
ProviderType: GitHub