Skip to content

nventive/terraform-aws-ecs-app

Repository files navigation

nventive

terraform-aws-ecs-app

License Latest Release

Terraform module to provision an ECS application.


Providers

This modules uses two instances of the AWS provider. One for Route 53 resources and one for the rest. The reason why is that Route 53 is often in a different account (ie. in the prod account when creating resources for dev).

You must provide both providers, whether you use Route 53 or not. In any case, you can specify the same provider for both if need be.

Examples

Important

We do not pin modules to versions in our examples because of the difficulty of keeping the versions in the documentation in sync with the latest released versions. We highly recommend that in your code you pin the version to the exact version you are using so that your infrastructure remains stable, and update versions in a systematic way so that they do not catch you by surprise.

module "container_definition_1" {
  source = "nventive/ecs-container-definition/aws"
  # We recommend pinning every module to a specific version
  # version = "x.x.x"

  container_name = "test_1"
  environment = [{
    name  = "NODE_ENV"
    value = "production"
  }]
}

module "container_definition_2" {
  source = "nventive/ecs-container-definition/aws"
  # We recommend pinning every module to a specific version
  # version = "x.x.x"

  container_name = "test_2"
  environment = [{
    name  = "NODE_ENV"
    value = "production"
  }]
}

module "ecs_app" {
  source = "nventive/ecs-app/aws"
  # We recommend pinning every module to a specific version
  # version = "x.x.x"

  providers = {
    aws.route53 = aws.route53
    aws         = aws
  }
  alb_arn                    = "arn:aws:elasticloadbalancing:us-east-1:999999999999:loadbalancer/app/xxxxxx/xxxxxxxxxxxxxxxx"
  alb_listeners              = [{ port = 443, protocol = "HTTPS" }, { port = 80, protocol = "HTTP" }]
  alb_security_group_id      = "sg-xxxxxxxxxxxxxxxxx"
  alb_arn_suffix             = "xxxxx/xxxxxxxxxxxxxxxx"
  ecs_cluster_name           = "arn:aws:ecs:us-east-1:999999999999:cluster/xxxxxxxxxxxx"
  ecs_cluster_arn            = dependency.cluster.outputs.cluster_arn
  health_check_matcher       = "200"
  healthcheck_path           = "/"
  service_container_port     = 8080
  service_container_protocol = "HTTP"
  vpc_id                     = "vpc-xxxxxxxxxxxxxxxxx"
  container_definition_json = jsonencode([
    module.container_definition_1.json_map_object,
    module.container_definition_2.json_map_object
  ])
}

Requirements

Name Version
terraform >= 0.13.0
aws >= 3.0
local >= 1.3
null >= 2.0
random >= 3.0
time >= 0.7.0

Providers

Name Version
aws >= 3.0

Modules

Name Source Version
acm_certificate nventive/acm-certificate/aws 1.0.1
alb_alarms cloudposse/alb-target-group-cloudwatch-sns-alarms/aws 0.17.0
alb_ingress cloudposse/alb-ingress/aws 0.25.1
autoscaling cloudposse/ecs-cloudwatch-autoscaling/aws 0.7.3
ecs_alarms cloudposse/ecs-cloudwatch-sns-alarms/aws 0.12.3
ecs_service_sg cloudposse/security-group/aws 2.2.0
service cloudposse/ecs-alb-service-task/aws 0.58.0
this cloudposse/label/null 0.25.0

Resources

Name Type
aws_cloudwatch_log_group.app resource
aws_lb_listener.app resource
aws_security_group_rule.opened_to_alb resource
aws_lb.alb data source

Inputs

Name Description Type Default Required
additional_tag_map Additional key-value pairs to add to each map in tags_as_list_of_maps. Not added to tags or id.
This is for some rare cases where resources want additional configuration of tags
and therefore take a list of maps with tag key, value, and additional configuration.
map(string) {} no
alb_alarms_3xx_threshold The maximum count of 3XX requests over a period. A negative value will disable the alert. number 25 no
alb_alarms_4xx_threshold The maximum count of 4XX requests over a period. A negative value will disable the alert. number 25 no
alb_alarms_5xx_threshold The maximum count of 5XX requests over a period. A negative value will disable the alert. number 25 no
alb_alarms_alarm_actions A list of ARNs (i.e. SNS Topic ARN) to execute when this alarm transitions into an ALARM state from any other state. If set, this list takes precedence over notify_arns. list(string)
[
""
]
no
alb_alarms_enabled Whether to enable SNS alarms for the ALB target group. bool false no
alb_alarms_evaluation_periods Number of periods to evaluate for the alarm. number 1 no
alb_alarms_insufficient_data_actions A list of ARNs (i.e. SNS Topic ARN) to execute when this alarm transitions into an INSUFFICIENT_DATA state from any other state. If set, this list takes precedence over notify_arns. list(string)
[
""
]
no
alb_alarms_ok_actions A list of ARNs (i.e. SNS Topic ARN) to execute when this alarm transitions into an OK state from any other state. If set, this list takes precedence over notify_arns. list(string)
[
""
]
no
alb_alarms_period Duration in seconds to evaluate for the alarm. number 300 no
alb_alarms_response_time_threshold The maximum average target response time (in seconds) over a period. A negative value will disable the alert. number 0.5 no
alb_arn ARN of the ALB. string n/a yes
alb_arn_suffix The ARN suffix of ALB. string n/a yes
alb_ingress_stickiness_cookie_duration The time period, in seconds, during which requests from a client should be routed to the same target. After this time period expires, the load balancer-generated cookie is considered stale. The range is 1 second to 1 week (604800 seconds). The default value is 1 day (86400 seconds) number 86400 no
alb_ingress_stickiness_enabled Boolean to enable / disable stickiness. bool true no
alb_ingress_stickiness_type The type of sticky sessions. The only current possible value is lb_cookie string "lb_cookie" no
alb_listeners A list of map containing a port and a protocol and optionally a default_action for all ALB listeners.
list(object({
port = number
protocol = string
default_action = object({
type = string
target_group_arn = optional(string)
redirect = optional(object({
host = optional(string)
path = optional(string)
port = optional(string)
protocol = optional(string)
query = optional(string)
status_code = string
}))
fixed_response = optional(object({
content_type = string
message_body = optional(string)
status_code = optional(string)
}))
})
}))
[
{
"default_action": {
"type": "forward"
},
"port": 80,
"protocol": "HTTP"
}
]
no
alb_security_group_id ALB security group id (to allow connection from the ALB to the service). string n/a yes
aliases List of FQDN's - Used to set the Alternate Domain Names (CNAMEs). list(string) [] no
attributes ID element. Additional attributes (e.g. workers or cluster) to add to id,
in the order they appear in the list. New attributes are appended to the
end of the list. The elements of the list are joined by the delimiter
and treated as a single ID element.
list(string) [] no
autoscaling_cpu_enabled Whether the ECS service should scale based on CPU utilization. bool false no
autoscaling_enabled Whether to enable autoscaling for the ECS service. bool false no
autoscaling_max_capacity Maximum number of running instances of a Service. number 2 no
autoscaling_memory_enabled Whether the ECS service should scale based on memory utilization. bool false no
autoscaling_min_capacity Minimum number of running instances of a Service. number 1 no
autoscaling_scale_down_adjustment Scaling adjustment to make during scale down event. number -1 no
autoscaling_scale_down_cooldown Period (in seconds) to wait between scale down events. number 300 no
autoscaling_scale_up_adjustment Scaling adjustment to make during scale up event. number 1 no
autoscaling_scale_up_cooldown Period (in seconds) to wait between scale up events. number 60 no
certificate_certificate_body_base64 The certificate's PEM-formatted public key base64-encoded. string "" no
certificate_chain_base64 The certificate's PEM-formatted chain base64-encoded. string "" no
certificate_private_key_base64 The certificate's PEM-formatted private key base64-encoded. string "" no
certificate_transparency_logging_preference Specifies whether certificate details should be added to a certificate transparency log. bool true no
certificate_type Used to chose a sub-module. Should be either request or import a certificate. string "request" no
certificate_validation_method Method to use for validation, DNS or EMAIL. string "DNS" no
certificate_wait_for_certificate_issued Whether to wait for the certificate to be issued by ACM (the certificate status changed from Pending Validation to Issued). bool false no
cloudwatch_log_group_retention_in_days Number of days to retain Cloudwatch logs. number 60 no
container_definition_json A string containing a JSON-encoded array of container definitions
("[{ "name": "container1", ... }, { "name": "container2", ... }]").
See API_ContainerDefinition,
cloudposse/terraform-aws-ecs-container-definition, or
ecs_task_definition#container_definitions
string n/a yes
context Single object for setting entire context at once.
See description of individual variables for details.
Leave string and numeric variables as null to use default value.
Individual variable settings (non-null) override settings in context object,
except for attributes, tags, and additional_tag_map, which are merged.
any
{
"additional_tag_map": {},
"attributes": [],
"delimiter": null,
"descriptor_formats": {},
"enabled": true,
"environment": null,
"id_length_limit": null,
"label_key_case": null,
"label_order": [],
"label_value_case": null,
"labels_as_tags": [
"unset"
],
"name": null,
"namespace": null,
"regex_replace_chars": null,
"stage": null,
"tags": {},
"tenant": null
}
no
default_service_security_group_enabled Enables the creation of a default security group for the ECS Service bool true no
delimiter Delimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
string null no
descriptor_formats Describe additional descriptors to be output in the descriptors output map.
Map of maps. Keys are names of descriptors. Values are maps of the form
{<br> format = string<br> labels = list(string)<br>}
(Type is any so the map values can later be enhanced to provide additional options.)
format is a Terraform format string to be passed to the format() function.
labels is a list of labels, in order, to pass to format() function.
Label values will be normalized before being passed to format() so they will be
identical to how they appear in id.
Default is {} (descriptors output will be empty).
any {} no
dns_alias_enabled Create a DNS alias for the CDN. Requires parent_zone_id or parent_zone_name. bool false no
ecs_alarm_description The string to format and use as the ECS alarm description. string "Average service %v utilization %v last %f minute(s) over %v period(s)" no
ecs_alarms_cpu_utilization_high_alarm_actions A list of ARNs (i.e. SNS Topic ARN) to notify on CPU Utilization High Alarm action. list(string) [] no
ecs_alarms_cpu_utilization_high_evaluation_periods Number of periods to evaluate for the alarm. number 1 no
ecs_alarms_cpu_utilization_high_ok_actions A list of ARNs (i.e. SNS Topic ARN) to notify on CPU Utilization High OK action. list(string) [] no
ecs_alarms_cpu_utilization_high_period Duration in seconds to evaluate for the alarm. number 300 no
ecs_alarms_cpu_utilization_high_threshold The maximum percentage of CPU utilization average. number 80 no
ecs_alarms_cpu_utilization_low_alarm_actions A list of ARNs (i.e. SNS Topic ARN) to notify on CPU Utilization Low Alarm action. list(string) [] no
ecs_alarms_cpu_utilization_low_evaluation_periods Number of periods to evaluate for the alarm. number 1 no
ecs_alarms_cpu_utilization_low_ok_actions A list of ARNs (i.e. SNS Topic ARN) to notify on CPU Utilization Low OK action. list(string) [] no
ecs_alarms_cpu_utilization_low_period Duration in seconds to evaluate for the alarm. number 300 no
ecs_alarms_cpu_utilization_low_threshold The minimum percentage of CPU utilization average. number 20 no
ecs_alarms_enabled Whether to enable SNS alarms for the ECS service. bool false no
ecs_alarms_memory_utilization_high_alarm_actions A list of ARNs (i.e. SNS Topic ARN) to notify on Memory Utilization High Alarm action. list(string) [] no
ecs_alarms_memory_utilization_high_evaluation_periods Number of periods to evaluate for the alarm. number 1 no
ecs_alarms_memory_utilization_high_ok_actions A list of ARNs (i.e. SNS Topic ARN) to notify on Memory Utilization High OK action. list(string) [] no
ecs_alarms_memory_utilization_high_period Duration in seconds to evaluate for the alarm. number 300 no
ecs_alarms_memory_utilization_high_threshold The maximum percentage of Memory utilization average. number 80 no
ecs_alarms_memory_utilization_low_alarm_actions A list of ARNs (i.e. SNS Topic ARN) to notify on Memory Utilization Low Alarm action. list(string) [] no
ecs_alarms_memory_utilization_low_evaluation_periods Number of periods to evaluate for the alarm. number 1 no
ecs_alarms_memory_utilization_low_ok_actions A list of ARNs (i.e. SNS Topic ARN) to notify on Memory Utilization Low OK action. list(string) [] no
ecs_alarms_memory_utilization_low_period Duration in seconds to evaluate for the alarm. number 300 no
ecs_alarms_memory_utilization_low_threshold The minimum percentage of Memory utilization average. number 20 no
ecs_cluster_arn The ARN of the ECS cluster. string n/a yes
ecs_cluster_name The name of the ECS cluster. string n/a yes
enabled Set to false to prevent the module from creating any resources bool null no
environment ID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT' string null no
health_check_enabled Indicates whether health checks are enabled. Defaults to true bool true no
health_check_healthy_threshold The number of consecutive health checks successes required before healthy number 2 no
health_check_interval The duration in seconds in between health checks number 15 no
health_check_matcher The HTTP response codes to indicate a healthy check.
Example: "200-399"
string n/a yes
health_check_path The destination for the health check request string "/" no
health_check_port The port to use to connect with the target. Valid values are either ports 1-65536, or traffic-port. Defaults to traffic-port string "traffic-port" no
health_check_protocol The protocol to use to connect with the target. Defaults to HTTP. Not applicable when target_type is lambda string "HTTP" no
health_check_timeout The amount of time to wait in seconds before failing a health check request number 10 no
health_check_unhealthy_threshold The number of consecutive health check failures required before unhealthy number 2 no
healthcheck_path DEPRECATED: Use health_check_path instead.
Path for the ALB health checks.
string null no
id_length_limit Limit id to this many characters (minimum 6).
Set to 0 for unlimited length.
Set to null for keep the existing setting, which defaults to 0.
Does not affect id_full.
number null no
kms_key_arn KMS Key ARN for Cloudwatch logs. string null no
label_key_case Controls the letter case of the tags keys (label names) for tags generated by this module.
Does not affect keys of tags passed in via the tags input.
Possible values: lower, title, upper.
Default value: title.
string null no
label_order The order in which the labels (ID elements) appear in the id.
Defaults to ["namespace", "environment", "stage", "name", "attributes"].
You can omit any of the 6 labels ("tenant" is the 6th), but at least one must be present.
list(string) null no
label_value_case Controls the letter case of ID elements (labels) as included in id,
set as tag values, and output by this module individually.
Does not affect values of tags passed in via the tags input.
Possible values: lower, title, upper and none (no transformation).
Set this to title and set delimiter to "" to yield Pascal Case IDs.
Default value: lower.
string null no
labels_as_tags Set of labels (ID elements) to include as tags in the tags output.
Default is to include all labels.
Tags with empty values will not be included in the tags output.
Set to [] to suppress all generated tags.
Notes:
The value of the name tag, if included, will be the id, not the name.
Unlike other null-label inputs, the initial setting of labels_as_tags cannot be
changed in later chained modules. Attempts to change it will be silently ignored.
set(string)
[
"default"
]
no
name ID element. Usually the component or solution name, e.g. 'app' or 'jenkins'.
This is the only ID element not also included as a tag.
The "name" tag is set to the full id string. There is no tag with the value of the name input.
string null no
namespace ID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally unique string null no
parent_zone_id ID of the hosted zone to contain this record (or specify parent_zone_name). Requires dns_alias_enabled set to true. string "" no
parent_zone_name Name of the hosted zone to contain this record (or specify parent_zone_id). Requires dns_alias_enabled set to true. string "" no
regex_replace_chars Terraform regular expression (regex) string.
Characters matching the regex will be removed from the ID elements.
If not set, "/[^a-zA-Z0-9-]/" is used to remove all characters other than hyphens, letters and digits.
string null no
service_assign_public_ip Assign a public IP address to the ENI (Fargate launch type only). Valid values are true or false. Default false. bool false no
service_circuit_breaker_deployment_enabled Whether to enable the deployment circuit breaker logic for the service. bool false no
service_circuit_breaker_rollback_enabled Whether to enable Amazon ECS to roll back the service if a service deployment fails. bool false no
service_container_name Name of the service to map to the load balancer. string n/a yes
service_container_port Container internal port for the service. number n/a yes
service_container_protocol Container protocol for the service. string "HTTP" no
service_deployment_controller_type Type of deployment controller. Valid values are CODE_DEPLOY and ECS. string "ECS" no
service_deployment_maximum_percent The upper limit of the number of tasks (as a percentage of desired_count) that can be running in a service during a deployment. number 200 no
service_deployment_minimum_healthy_percent The lower limit (as a percentage of desired_count) of the number of tasks that must remain running and healthy in a service during a deployment. number 100 no
service_desired_count The number of instances of the task definition to place and keep running. number 1 no
service_exec_enabled Specifies whether to enable Amazon ECS Exec for the tasks within the service. bool false no
service_health_check_grace_period_seconds Seconds to ignore failing load balancer health checks on newly instantiated tasks to prevent premature shutdown, up to 7200. Only valid for services configured to use load balancers. number 0 no
service_ignore_changes_desired_count Whether to ignore changes for desired count in the ECS service. bool false no
service_ignore_changes_task_definition Whether to ignore changes in container definition and task definition in the ECS service. bool true no
service_launch_type The launch type on which to run your service. Valid values are EC2 and FARGATE. string "FARGATE" no
service_security_groups A list of Security Group IDs to allow in Service network_configuration if var.network_mode = "awsvpc". list(string) [] no
service_task_cpu The number of CPU units used by the task. If using FARGATE launch type task_cpu must match supported memory values. number 256 no
service_task_memory The amount of memory (in MiB) used by the task. If using Fargate launch type task_memory must match supported cpu value. number 512 no
service_task_policy_arns A list of IAM Policy ARNs to attach to the generated task role. list(string) [] no
service_volumes Task volume definitions as list of configuration objects.
list(object({
host_path = string
name = string
docker_volume_configuration = list(object({
autoprovision = bool
driver = string
driver_opts = map(string)
labels = map(string)
scope = string
}))
efs_volume_configuration = list(object({
file_system_id = string
root_directory = string
transit_encryption = string
transit_encryption_port = string
authorization_config = list(object({
access_point_id = string
iam = string
}))
}))
}))
[] no
stage ID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release' string null no
subnet_ids List of subnet IDs for the DB. DB instance will be created in the VPC associated with the DB subnet group provisioned using the subnet IDs. Specify one of subnet_ids, db_subnet_group_name or availability_zone. list(string) [] no
tags Additional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.
map(string) {} no
tenant ID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is for string null no
vpc_id VPC ID the DB instance will be created in. string n/a yes
wait_for_steady_state If true, it will wait for the service to reach a steady state (like aws ecs wait services-stable) before continuing. bool false no

Outputs

Name Description
alb_listener_arns The ARN of the ALB listeners.
ecs_service_security_group_id The ID of the Security Group for the ECS service.
service_arn ECS Service ARN
service_name ECS Service name
task_definition_family ECS task definition family
task_exec_role_arn ECS Task exec role ARN
task_role_arn ECS Task role ARN
url Full URL of the app

Breaking Changes

Please consult BREAKING_CHANGES.md for more information about version history and compatibility.

Contributing

Please read CONTRIBUTING.md for details on the process for contributing to this project.

Be mindful of our Code of Conduct.

We're hiring

Look for current openings on BambooHR https://nventive.bamboohr.com/careers/

Stay in touch

nventive.com | Linkedin | Instagram | YouTube | Spotify