Skip to content

pbs/terraform-aws-ecs-service-module

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PBS TF ECS Service Module

Installation

Using the Repo Source

github.com/pbs/terraform-aws-ecs-service-module?ref=6.1.1

Alternative Installation Methods

More information can be found on these install methods and more in the documentation here.

Usage

This module provisions a basic ECS service. Provide the image_repo and image_tag corresponding to the Docker image you would like to run, and everything from the ECS task definition to the DNS for the load balancer will be provisioned so that you can access your application.

To make the service provisioned here private, set public_service to false. This will set up a DNS entry in a private hosted zone, and adjust the load balancer associated with the service such that it is an internal load balancer.

To switch the kind of load balancer used from an application load balancer to a network load balancer, set load_balancer_type to network.

To run an ECS service on ARM architecture, set runtime_platform accordingly. The cpu_architecture object property being set to ARM64 is what adjusts the task definition such that the tasks run on Graviton hardware for Fargate tasks.

Integrate this module like so:

module "service" {
  source = "github.com/pbs/terraform-aws-ecs-service-module?ref=6.1.1"

  # Required
  hosted_zone = "example.com"

  # Tagging Parameters
  organization = var.organization
  environment  = var.environment
  product      = var.product
  repo         = var.repo

  # Optional
  image_repo = "nginx"
  image_tag = "latest"
}

ECS Cluster

This module will create an ECS cluster if one is not provided. If you would like to use an existing ECS cluster, provide the cluster variable.

module "service" {
  source = "github.com/pbs/terraform-aws-ecs-service-module?ref=6.1.1"

  # Required
  hosted_zone = "example.com"

  # Tagging Parameters
  organization = var.organization
  environment  = var.environment
  product      = var.product
  repo         = var.repo

  # Optional
  cluster = "main"
}

⚠️ It is not advised to use the default of the automatically created cluster from this module in production, as collocation of services on the same cluster can lead to improved resource utilization, cost savings, reduced complexity and nicer CloudWatch dashboards. How much of this applies to you is dependent on your cluster configuration and use-case, however. Feel free to use the cluster provisioned by this module when starting out to reduce the friction of getting started, but consider moving to a dedicated cluster as soon as convenient.

Adding This Version of the Module

If this repo is added as a subtree, then the version of the module should be close to the version shown here:

6.1.1

Note, however that subtrees can be altered as desired within repositories.

Further documentation on usage can be found here.

Below is automatically generated documentation on this Terraform module using terraform-docs


Requirements

Name Version
terraform >= 1.3.2
aws >= 5.30.0

Providers

Name Version
aws 5.40.0

Modules

Name Source Version
cluster github.com/pbs/terraform-aws-ecs-cluster-module 1.0.2
task github.com/pbs/terraform-aws-ecs-task-definition-module 2.0.3

Resources

Name Type
aws_appautoscaling_policy.cpu_autoscaling_policy resource
aws_appautoscaling_policy.memory_autoscaling_policy resource
aws_appautoscaling_policy.scale_down_policy resource
aws_appautoscaling_policy.scale_up_policy resource
aws_appautoscaling_target.autoscaling_target resource
aws_appmesh_virtual_node.virtual_node resource
aws_cloudwatch_metric_alarm.cpu_high resource
aws_cloudwatch_metric_alarm.cpu_low resource
aws_cloudwatch_metric_alarm.memory_high resource
aws_cloudwatch_metric_alarm.memory_low resource
aws_ecs_service.service resource
aws_eip.nlb resource
aws_lb.lb resource
aws_lb_listener.http resource
aws_lb_listener.http_redirect resource
aws_lb_listener.https resource
aws_lb_listener.nlb resource
aws_lb_listener.nlb_tcp resource
aws_lb_listener_rule.http_application_rule resource
aws_lb_listener_rule.https_application_rule resource
aws_lb_target_group.target_group resource
aws_route53_record.app resource
aws_security_group.lb_sg resource
aws_security_group.service_sg resource
aws_security_group_rule.lb_egress resource
aws_security_group_rule.lb_to_service resource
aws_security_group_rule.nlb_service_access_cidr resource
aws_security_group_rule.nlb_service_access_sg resource
aws_security_group_rule.service_egress resource
aws_security_group_rule.user_to_lb_http_cidrs resource
aws_security_group_rule.user_to_lb_http_sgs resource
aws_security_group_rule.user_to_lb_https_cidrs resource
aws_security_group_rule.user_to_lb_https_sgs resource
aws_security_group_rule.user_to_nlb_cidrs resource
aws_security_group_rule.user_to_nlb_sgs resource
aws_security_group_rule.user_to_virtual_node_access_cidr resource
aws_security_group_rule.user_to_virtual_node_access_sg resource
aws_service_discovery_service.service resource
aws_acm_certificate.primary_acm_wildcard_cert data source
aws_default_tags.common_tags data source
aws_route53_zone.hosted_zone data source
aws_subnets.private_subnets data source
aws_subnets.public_subnets data source
aws_vpc.vpc data source

Inputs

Name Description Type Default Required
environment Environment (sharedtools, dev, staging, qa, prod) string n/a yes
organization Organization using this module. Used to prefix tags so that they are easily identified as being from your organization string n/a yes
product Tag used to group resources according to product string n/a yes
repo Tag used to point to the repo using this module string n/a yes
acm_arn ARN of the ACM certificate to use for the service. If null, one will be guessed based on the primary hosted zone of the service. string null no
alb_ssl_policy SSL policy to use for an Application Load Balancer application. string "ELBSecurityPolicy-2016-08" no
aliases CNAME(s) that are allowed to be used for this service. Default is product.hosted_zone. e.g. [product.example.com] --> [product.example.com] list(string) null no
alpn_policy Name of the Application-Layer Protocol Negotiation (ALPN) policy. Can be set if protocol is TLS. Valid values are HTTP1Only, HTTP2Only, HTTP2Optional, HTTP2Preferred, and None. string "HTTP2Preferred" no
assign_public_ip Assign public IP to the service bool true no
awslogs_driver_mode (optional) awslogs driver mode. Set this to blocking if you would rather have an outage than lose logs. string "non-blocking" no
cluster Name of the ECS Cluster this service runs in. If null, one will be created based on the product string null no
cluster_ec2_backed Whether or not to provision an autoscaled EC2 fleet to back the cluster bool false no
cluster_instance_type Instance type to use for EC2 backed cluster string "m7a.xlarge" no
cluster_launch_template_version Version of the launch template to use string "$Latest" no
cluster_max_instance_lifetime Maximum lifetime for an instance in the autoscaling group number 604800 no
cluster_max_size Maximum size for the autoscaling group to scale out to for the cluster number 25 no
cluster_maximum_scaling_step_size Capacity provider maximum scaling step size number 10 no
cluster_min_size Minimum size for the autoscaling group to scale out to for the cluster number 3 no
cluster_minimum_scaling_step_size Capacity provider maximum scaling step size number 1 no
cluster_name Name of the cluster string null no
cluster_protect_from_scale_in Allow ECS to protect instances running tasks from being terminated while tasks are running on them. Must be false when destroying cluster bool true no
cluster_role_policy_json (optional) IAM policy to attach to role used for the instance profile of instances in this cluster string null no
cluster_target_capacity Capacity provider target capacity number 75 no
cnames CNAME(s) that are going to be created for this service in the hosted_zone. This can be set to [] to avoid creating a CNAME for the app. This can be useful for CDNs. Default is product. e.g. [product] --> [product.example.com] list(string) null no
command (optional) command to run in the container as an array. e.g. ["sleep", "10"]. If null, does not set a command in the task definition. list(string) null no
container_definitions (optional) JSON container definitions for task string null no
container_name (optional) name for the container to have string null no
container_port (optional) port the container is exposing number 80 no
container_protocol Protocol to use in connection to the container string "HTTP" no
cpu_reservation (optional) CPU reservation for task number 256 no
create_attach_eip_to_nlb Create EIPs for each subnet and attach them to the NLB (public only) bool false no
create_lb Create load balancer for service. If creating a virtual node, will ignore value. bool true no
deployment_maximum_percent The upper limit (as a percentage of the service's desiredCount) of the number of running tasks that can be running in a service during a deployment number 150 no
deployment_minimum_healthy_percent The lower limit (as a percentage of the service's desiredCount) of the number of running tasks that must remain running and healthy in a service during a deployment number 100 no
dns_evaluate_target_health evaluate health of endpoints by querying DNS records bool false no
efs_mounts (optional) efs mount set of objects. Components should include dns_name, container_mount_point, efs_mount_point
set(object({
file_system_id = string
efs_path = string
container_path = string
}))
[] no
enable_application_signals (optional) if set to true, will enable CW Application Signals bool false no
enable_circuit_breaker Enables ECS circuit breaker bool true no
enable_circuit_breaker_rollback Enables ECS circuit breaker rollback bool true no
enable_cross_zone_load_balancing Enable cross-zone load balancing for NLBs. ALB have this enabled by default and cannot be disabled. string true no
enable_execute_command Enables ecs exec. If null, will enable if not on prod bool null no
entrypoint (optional) entrypoint to run in the container as an array. e.g. ["sleep", "10"]. If null, does not set an entrypoint in the task definition. list(string) null no
env_vars (optional) environment variables to be passed to the container. By default, only passes SSM_PATH set(map(any)) null no
envoy_tag (optional) tag for envoy. Update periodically if using App Mesh. string "v1.23.1.0-prod" no
healthcheck_healthy_threshold The number of consecutive health checks successes required before considering an unhealthy target healthy number 3 no
healthcheck_interval The approximate amount of time, in seconds, between health checks of an individual target number 10 no
healthcheck_matcher The HTTP codes to use when checking for a successful response from a target number 200 no
healthcheck_path The destination for the health check request string null no
healthcheck_protocol The protocol to use to connect with the target string null no
healthcheck_timeout The amount of time, in seconds, during which no response means a failed health check number 6 no
healthcheck_unhealthy_threshold The number of consecutive health check failures required before considering the target unhealthy number 3 no
hosted_zone Name of the hosted zone for DNS. e.g. hosted_zone = example.org --> service.example.org. Based on the is_hosted_zone_private, this is the primary or the private hosted zone. string null no
http_port HTTP port number. number "80" no
https_port HTTPS port number. number "443" no
idle_timeout Idle timeout for the load balancer. If null, will use whatever the default is for the load balancer type. number null no
image_repo (optional) image repo. e.g. image_repo = nginx --> nginx:image_tag string "nginx" no
image_tag (optional) tag of the image. e.g. image_tag = latest --> image_repo:latest string "alpine" no
internal Use an internal load balancer. If null, will be internal when the service is private. bool null no
is_hosted_zone_private Is the route53 zone private or not. bool false no
launch_type The launch type on which to run your service string "FARGATE" no
load_balancer_name Load balancer name. Will default to product if not defined. string null no
load_balancer_sg_name Prefix for the name of the load balancer security group. If null, will use ${local.load_balancer_name}-sg-. string null no
load_balancer_type Type of load balancer to use. application, network or gateway. string "application" no
log_group_class (Optional) log class of the log group. Possible values are: STANDARD or INFREQUENT_ACCESS string "INFREQUENT_ACCESS" no
log_group_name (optional) name for the log group string null no
max_capacity The maximum capacity of tasks for this service number 2 no
memory_reservation (optional) memory reservation for task number 512 no
mesh_name (optional) the name for the App Mesh this task is associated with. If null, ignored string null no
min_capacity The minimum capacity of tasks for this service number 1 no
name Name of the service. Will default to product if not defined. string null no
namespace Namespace. If null, defaults to var.application-tag. string null no
namespace_id Namespace ID. string null no
network_mode (optional) network mode for the task string "awsvpc" no
newrelic_secret_arn ARN for AWS Secrets Manager secret of New Relic Insights insert key. string null no
newrelic_secret_name Name for AWS Secrets Manager secret of New Relic Insights insert key. string null no
nlb_protocol Protocol for the network load balancer used in this service. Ignored for application load balancers. string "TLS" no
nlb_ssl_policy SSL policy to use for a Network Load Balancer application. string "ELBSecurityPolicy-TLS13-1-2-2021-06" no
platform_version The platform version on which to run your service string "LATEST" no
private_subnets Private subnets for the service. If null, private subnets will be looked up based on environment tag and will be selected based on public_service. list(string) null no
propagate_tags Specifies whether to propagate the tags from the task definition or the service to the tasks string "SERVICE" no
public_service Service should be provisioned in public subnet. Ignored if subnets defined. bool false no
public_subnets Public subnets for the service. If null, public subnets will be looked up based on environment tag and will be selected based on public_service. list(string) null no
pythonpath (optional) PYTHONPATH of the application; required by the cwagent sidecar container string ":" no
requires_compatibilities (optional) capabilities that the task requires set(string)
[
"FARGATE"
]
no
restricted_cidr_blocks CIDR blocks to receive restricted service access. If empty, no CIDRs will be allowed to connect. list(string)
[
"0.0.0.0/0"
]
no
restricted_sg SG to receive restricted service access. If null, no sg will be configured to connect string null no
retention_in_days (optional) log retention in days number 7 no
role_policy_json the policy to apply for this service. Defaults to a valid ECS role policy if null. string null no
route_priority Starting route priority, incremented by each listener rule number 10 no
runtime_platform (optional) Runtime platform for the task. Defaults to LINUX operating system family w/ CPU architecture x86_64.
object({
operating_system_family = optional(string, "LINUX")
cpu_architecture = optional(string, "X86_64")
})
{
"cpu_architecture": "X86_64",
"operating_system_family": "LINUX"
}
no
scale_down_adjustment Tasks to add on scale up number -1 no
scale_down_cooldown Scale down cooldown in minutes number 5 no
scale_down_cpu_threshold Threshold at which CPU utilization triggers a scale down event number 20 no
scale_down_memory_threshold Threshold at which Memory utilization triggers a scale down event number 20 no
scale_up_adjustment Tasks to add on scale up number 2 no
scale_up_cooldown Scale up cooldown in minutes number 1 no
scale_up_cpu_threshold Threshold at which CPU utilization triggers a scale up event number 80 no
scale_up_memory_threshold Threshold at which Memory utilization triggers a scale up event number 80 no
scaling_approach Approach to take with scaling. Valid values are target_tracking and step_scaling string "target_tracking" no
scaling_evaluation_period Scaling evaluation period in seconds number 60 no
scaling_evaluation_periods Number of periods over which data is compared to the threshold number 1 no
service_healthcheck_healthy_threshold The number of successful checks before a service is considered healthy number 2 no
service_healthcheck_interval The time, in milliseconds, between health checks of the service number 6000 no
service_healthcheck_timeout The time, in milliseconds, before a timeout on the health check of the service number 3000 no
service_healthcheck_unhealthy_threshold The number of unsuccessful checks before a service is considered unhealthy number 2 no
service_sg_name Prefix for the name of the service security group. If null, will use ${local.name}-service-sg-. string null no
ssm_path (optional) path to the ssm parameters you want pulled into your container during execution of the entrypoint string null no
subnets Subnets for the service. If null, private and public subnets will be looked up based on environment tag and one will be selected based on public_service. list(string) null no
tags Extra tags map(string) {} no
target_cpu_utilization Target CPU utilization for scaling number 50 no
target_group_name Target group name. Will default to product if not defined. string null no
target_memory_utilization Target memory utilization for scaling number 50 no
task_def_arn Task definition ARN. If null, task will be created with default values, except that image_repo and image_tag may be defined. string null no
task_family (optional) task family for task. This is effectively the name of the task, without qualification of revision string null no
tcp_port NLB TCP port number. Ignored for application load balancers. number null no
use_xray_sidecar (optional) if set to null, will use the sidecar to trace the task if envoy is used, as that automatically implements tracing configs. bool null no
virtual_gateway (optional) the name of the virtual gateway associated with this task definition. If null, ignored string null no
virtual_node (optional) the name of the virtual node associated with this task definition. Ignored if virtual_gateway set. If null, ignored string null no
virtual_node_protocol Protocol for the virtual node string "http" no
vpc_id VPC ID. If null, one will be looked up based on environment tag. string null no

Outputs

Name Description
arn ARN of the service
cluster Cluster this service is associated with
container_name Name of the main container used by this service
domain_name One domain name that will resolve to this service. Might not be a valid alias.
https_listener_arn ARN of the HTTPS listener. Useful when adding extra ACM certificates to the listener.
iam_task_role_arn IAM role ARN associated with a task defition, if task defition is created by the ecs service module
image_tag Tag of the image used by this service
lb_arn Load balancer ARN
lb_dns_name Load balancer DNS Name
lb_sg Load balancer security group
lb_zone_id Load balancer Zone Id
name Name of the service
service_id CloudMap Service ID
service_sg Service security group
subnets Subnets used by this service
task_def_arn Current task definition ARN used by this service
task_family Current task family used by this service
virtual_node_name Name of the virtual node