Skip to content

robertomoutinho/terraform-aws-ecs-app

Repository files navigation

AWS Terraform module which runs an web app on AWS Fargate

This repository contains Terraform infrastructure code which creates AWS resources required to run an web app on AWS, including:

  • AWS Application Load Balancer (ALB)
  • AWS Route53 domain name pointing to ALB
  • AWS Elastic Cloud Service (ECS) task running on AWS Fargate (with the provided docker image)
  • AWS Service Discovery
  • AWS IAM necessary to access other AWS resources (such as S3, SNS and etc)
  • AWS Cloudwatch for the logs

Checkov

Requirements

Name Version
terraform >= 0.14.0
aws >= 4.46.0, < 5.0

Providers

Name Version
aws >= 4.46.0, < 5.0
external n/a

Modules

Name Source Version
alb terraform-aws-modules/alb/aws 5.16.0
alb_http_sg terraform-aws-modules/security-group/aws v3.18.0
alb_https_sg terraform-aws-modules/security-group/aws v3.18.0
container_definition cloudposse/ecs-container-definition/aws v0.58.1
datadog_firelens cloudposse/ecs-container-definition/aws v0.58.1
datadog_sidecar cloudposse/ecs-container-definition/aws v0.58.1

Resources

Name Type
aws_appautoscaling_policy.auto_scaling_cpu resource
aws_appautoscaling_policy.auto_scaling_mem resource
aws_appautoscaling_policy.auto_scaling_request resource
aws_appautoscaling_policy.this resource
aws_appautoscaling_target.target resource
aws_cloudwatch_log_group.app resource
aws_ecs_service.app resource
aws_ecs_task_definition.app resource
aws_iam_role.ecs_task_execution resource
aws_iam_role_policy.ecs_task_access_backend resource
aws_iam_role_policy.ecs_task_access_secrets resource
aws_iam_role_policy_attachment.ecs_task_execution resource
aws_kms_alias.this resource
aws_kms_key.this resource
aws_lb.nlb resource
aws_lb_listener.allow_http resource
aws_lb_listener.force_https resource
aws_lb_listener.nlb_listener resource
aws_lb_listener_certificate.extra_certs resource
aws_lb_target_group.nlb_tg resource
aws_route53_record.app resource
aws_security_group.app resource
aws_security_group_rule.allow_all resource
aws_security_group_rule.allow_extra_cidr resource
aws_security_group_rule.ingress_with_alb_http_security_group_id resource
aws_security_group_rule.ingress_with_alb_https_security_group_id resource
aws_security_group_rule.ingress_with_self_rule resource
aws_security_group_rule.service_discovery_ingress_rule resource
aws_service_discovery_service.sds resource
aws_caller_identity.current data source
aws_ecs_cluster.cluster data source
aws_iam_policy_document.ecs_task_access_backend data source
aws_iam_policy_document.ecs_task_access_secrets data source
aws_iam_policy_document.ecs_tasks data source
aws_iam_policy_document.this data source
aws_partition.current data source
aws_region.current data source
aws_route53_zone.this data source
aws_secretsmanager_secret.creds data source
aws_vpc.selected data source
external_external.current_image data source

Inputs

Name Description Type Default Required
alb_extra_acm_cert_arn The ARN of the ACM SSL certificate for the extra cert list(string) [] no
alb_extra_security_group_ids List of one or more security groups to be added to the load balancer list(string) [] no
alb_extra_target_groups List of one or more target groups to be added to the load balancer list(string) [] no
alb_ingress_cidr_blocks Comma separated string of IPv4 CIDR ranges to use on all ingress rules of the ALB. string "0.0.0.0/0" no
alb_internal Whether the load balancer is internal or external bool false no
alb_log_bucket_name S3 bucket (externally created) for storing load balancer access logs. Required if alb_logging_enabled is true. string "" no
alb_log_location_prefix S3 prefix within the log_bucket_name under which logs are stored. string "" no
alb_logging_enabled Controls if the ALB will log requests to S3. bool false no
app_container_command The command that is passed to the container list(string) null no
app_docker_image The docker image to be used. If set, app_ecr_image_repo will be ignored string "" no
app_ecr_image_repo The ECR Repository where the app image is located string "" no
app_fqdn FQDN of app to use. Set this only to override Route53 and ALB's DNS name. string null no
app_port_mapping The port mappings to configure for the container. This is a list of maps. Each map should contain "containerPort", "hostPort", and "protocol", where "protocol" is one of "tcp" or "udp". If using containers in a task with the awsvpc or host network mode, the hostPort can either be left blank or set to the same value as the containerPort
list(object({
containerPort = number
hostPort = number
protocol = string
}))
[
{
"containerPort": 80,
"hostPort": 80,
"protocol": "tcp"
}
]
no
app_sg_extra_cidr A list of extra cidr blocks to allow ingress traffic to container list(string) [] no
asg_cooldown_to_scale_down_again The amount of time, in seconds, after a scaling activity completes and before the next scaling down activity can start. number 300 no
asg_cooldown_to_scale_up_again The amount of time, in seconds, after a scaling activity completes and before the next scaling up activity can start. number 60 no
asg_custom_policies Map of autoscaling policies to create for the service any
{
"cpu": {
"target_tracking_scaling_policy_configuration": {
"predefined_metric_specification": {
"predefined_metric_type": "ECSServiceAverageCPUUtilization"
}
}
},
"memory": {
"target_tracking_scaling_policy_configuration": {
"predefined_metric_specification": {
"predefined_metric_type": "ECSServiceAverageMemoryUtilization"
}
}
}
}
no
asg_evaluation_periods The number of periods over which data is compared to the specified threshold. number 5 no
asg_max_tasks The amount of maximum tasks number 3 no
asg_min_tasks The amount of minimum tasks number 1 no
asg_period The period in seconds over which the specified statistic is applied number 60 no
asg_threshold_cpu_to_scale_up The value against which the specified statistic is compared. number 60 no
asg_threshold_mem_to_scale_up The value against which the specified statistic is compared. number 60 no
asg_threshold_request_to_scale_up The value against which the specified statistic is compared. number 100 no
certificate_arn ARN of certificate issued by AWS ACM. string "" no
cloudwatch_log_retention_in_days Retention period of app CloudWatch logs number 7 no
container_memory_reservation The amount of memory (in MiB) to reserve for the container number 128 no
create_default_role Default role + policies for secrets and s3 access should be created ? bool true no
create_route53_record Whether to create Route53 record for app bool true no
custom_container_definitions A list of valid container definitions provided as a single valid JSON document. By default, the standard container definition is used. string "" no
custom_environment_secrets List of additional secrets the container will use (list should contain maps with name and valueFrom)
list(object(
{
name = string
valueFrom = string
}
))
[] no
custom_environment_variables List of additional environment variables the container will use (list should contain maps with name and value)
list(object(
{
name = string
value = string
}
))
[] no
datadog_agent_container_essential Determines whether all other containers in a task are stopped, if this container fails or stops for any reason bool false no
datadog_agent_container_image The datadog agent sidecar container image string "public.ecr.aws/datadog/agent:latest" no
datadog_firelens_container_essential Determines whether all other containers in a task are stopped, if this container fails or stops for any reason bool false no
datadog_firelens_container_image The datadog firelens sidecar container image string "public.ecr.aws/aws-observability/aws-for-fluent-bit:stable" no
datadog_process_collection_enabled Whether to enable process collection bool true no
datadog_service_name The datadog service name string "" no
datadog_tags Tags for datadog agent container. string "env:default, service:default, region:default" no
docker_labels Docker labels to add to the container map(string) {} no
ecs_capacity_provider Short name of the capacity provider string "FARGATE" no
ecs_cluster_name The ECS cluster Name any n/a yes
ecs_efs_volumes (Optional) A set of volume blocks that containers in your task may use
list(object({
name = string
efs_volume_configuration = object({
file_system_id = string
root_directory = string
})
authorization_config = object({
access_point_id = string
})
}))
[] no
ecs_enable_execute_command Specifies whether to enable Amazon ECS Exec for the tasks within the service bool false no
ecs_ephemeral_storage_size The size (in GiB) of storage available to the task number 40 no
ecs_linux_parameters Linux-specific modifications that are applied to the container, such as Linux kernel capabilities. For more details, see https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_LinuxParameters.html
object({
capabilities = object({
add = list(string)
drop = list(string)
})
devices = list(object({
containerPath = string
hostPath = string
permissions = list(string)
}))
initProcessEnabled = bool
maxSwap = number
sharedMemorySize = number
swappiness = number
tmpfs = list(object({
containerPath = string
mountOptions = list(string)
size = number
}))
})
null no
ecs_mount_points (Optional) Container mount points. This is a list of maps, where each map should contain containerPath, sourceVolume and readOnly
list(object({
containerPath = string
sourceVolume = string
readOnly = bool
}))
[] no
ecs_pseudo_terminal When this parameter is true, a TTY is allocated. bool null no
ecs_requires_compatibilities A list of requires_compatibilities list(string)
[
"FARGATE"
]
no
ecs_service_assign_public_ip Should be true, if ECS service is using public subnets (more info: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_cannot_pull_image.html) bool false no
ecs_service_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 200 no
ecs_service_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 50 no
ecs_service_desired_count The number of instances of the task definition to place and keep running number 1 no
ecs_stop_timeout Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit normally on its own number 60 no
ecs_task_cpu The number of cpu units used by the task number 256 no
ecs_task_memory The amount (in MiB) of memory used by the task number 512 no
ecs_ulimits Container ulimit settings. This is a list of maps, where each map should contain "name", "hardLimit" and "softLimit"
list(object({
name = string
hardLimit = number
softLimit = number
}))
null no
enable_alb IF an application load balancer should be created bool true no
enable_asg If autoscaling should be enabled bool false no
enable_cpu_scaling If autoscaling should be enabled based on CPU bool true no
enable_custom_scaling If autoscaling should be enabled based on a custom metric bool false no
enable_datadog_log_forwarder Whether we create the lambda to forward logs to datadog bool false no
enable_datadog_sidecar Whether the datadog sidecar should be added to the task definition bool false no
enable_mem_scaling If autoscaling should be enabled based on Memory bool false no
enable_nlb IF an network load balancer should be created bool false no
enable_request_scaling If autoscaling should be enabled based on qtd of request for ALB bool false no
enable_service_discovery Whether the service should be registered with Service Discovery. In order to use Service Disovery, an existing DNS Namespace must exist and be passed in. bool false no
environment The name of the environment string n/a yes
external_iam_role The ARN of the role to be attached to the ECS container string "" no
health_check_healthy_threshold Healthcheck interval number 3 no
health_check_http_code_matcher Healthcheck interval string "200-399" no
health_check_interval Healthcheck interval number 15 no
health_check_path Healthcheck interval string "/" no
health_check_timeout Healthcheck interval number 5 no
health_check_unhealthy_threshold Healthcheck interval number 4 no
iam_role_for_external_datasource This Role is used to get the current app version deploy to ECS string n/a yes
name Name to use on all resources created (VPC, ALB, etc) string "app" no
policies_arn A list of the ARN of the policies you want to apply list(string)
[
"arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
]
no
private_subnet_ids A list of IDs of existing private subnets inside the VPC list(string) [] no
public_subnet_ids A list of IDs of existing public subnets inside the VPC list(string) [] no
repository_credentials_name The SecretsManager Secret Name of the repository credentials to use string null no
route53_record_name Name of Route53 record to create ACM certificate in and main A-record. If null is specified, var.name is used instead. Provide empty string to point root domain name to ALB. string null no
route53_zone_name Route53 zone name to create ACM certificate in and main A-record, without trailing dot string "" no
secret_path path to append to IAM secrets access policy string "" no
service_discovery_dns_record_type The type of the resource, which indicates the value that Amazon Route 53 returns in response to DNS queries. One of A or SRV. string "A" no
service_discovery_dns_ttl The amount of time, in seconds, that you want DNS resolvers to cache the settings for this resource record set. number 10 no
service_discovery_failure_threshold The number of 30-second intervals that you want service discovery to wait before it changes the health status of a service instance. Maximum value of 10. number 1 no
service_discovery_namespace_id The ID of the namespace to use for DNS configuration. string null no
service_discovery_routing_policy The routing policy that you want to apply to all records that Route 53 creates when you register an instance and specify the service. One of MULTIVALUE or WEIGHTED. string "MULTIVALUE" no
tags A map of tags to use on all resources map(string) n/a yes
vpc_id ID of an existing VPC where resources will be created string "" no

Outputs

Name Description
alb_dns_name Dns name of alb
alb_https_tcp_listener_arns The ARNs of the HTTPS load balancer listeners created.
alb_id The ID and ARN of the application load balancer created
alb_target_group_arns ARNs of the target groups. Useful for passing to your Auto Scaling group.
alb_zone_id Zone ID of alb
cloudwatch_group_name The AWS cloudwatch group name
ecs_security_group Security group assigned to ECS Service in network configuration
ecs_task_definition Task definition for ECS service (used for external triggers)
nlb_dns_name Dns name of nlb
nlb_id The ID and ARN of the network load balancer created
task_role_arn The app ECS task role arn
vpc_id ID of the VPC that was created or passed in