README.md

April 20, 2026 Β· View on GitHub

Project Banner

Latest ReleaseSlack CommunityGet Support

This component is responsible for creating an ECS service.

Tip

πŸ‘½ Use Atmos with Terraform

Cloud Posse uses atmos to easily orchestrate multiple environments using Terraform.
Works with Github Actions, Atlantis, or Spacelift.

Watch demo of using Atmos with Terraform
Example of running atmos to manage infrastructure from our Quick Start tutorial.

Usage

Stack Level: Regional

Here's an example snippet for how to use this component.

# stacks/catalog/ecs-service/defaults.yaml
components:
  terraform:
    ecs-service/defaults:
      metadata:
        component: ecs-service
        type: abstract
      settings:
        spacelift:
          workspace_enabled: true
      vars:
        enabled: true
        public_lb_enabled: false
        ecr_stage_name: mgmt-automation
        task:
          launch_type: FARGATE
          network_mode: awsvpc
          desired_count: 1
          ignore_changes_desired_count: true
          ignore_changes_task_definition: false
          assign_public_ip: false
          propagate_tags: SERVICE
          wait_for_steady_state: true
          circuit_breaker_deployment_enabled: true
          circuit_breaker_rollback_enabled: true

This will launch google's echoserver using an external image from gcr

NOTE: Usage of image instead of ecr_image.

# stacks/catalog/ecs-service/echoserver.yaml
import:
  - catalog/ecs-service/defaults

components:
  terraform:
    ecs/platform/echoserver/service:
      metadata:
        component: ecs-service
        inherits:
          - ecs-service/defaults
      vars:
        enabled: true
        name: echoserver
        public_lb_enabled: false
        cluster_attributes: [platform]
        ## Example task_exec_iam_policy
        # task_exec_iam_policy:
        #   - policy_id: "EcsServiceEchoServer"
        #     statements:
        #       - sid: "EcsServiceEchoServer"
        #         effect: "Allow"
        #         actions:
        #           - "kms:Decrypt"
        #         resources:
        #           - "*"
        containers:
          service:
            name: "echoserver"
            image: gcr.io/google_containers/echoserver:1.10
            port_mappings:
              - containerPort: 8080
                hostPort: 8080
                protocol: tcp
        task:
          desired_count: 1
          task_memory: 512
          task_cpu: 256

This will launch a kong service using an ecr image from mgmt-automation account.

NOTE: Usage of ecr_image instead of image.

import:
  - catalog/ecs-service/defaults

components:
  terraform:
    ecs/b2b/kong/service:
      metadata:
        component: ecs-service
        inherits:
          - ecs-service/defaults
      vars:
        name: kong
        public_lb_enabled: true
        cluster_attributes: [b2b]
        containers:
          service:
            name: "kong-gateway"
            ecr_image: kong:latest
            map_environment:
              KONG_DECLARATIVE_CONFIG: /home/kong/production.yml
            port_mappings:
              - containerPort: 8000
                hostPort: 8000
                protocol: tcp
        task:
          desired_count: 1
          task_memory: 512
          task_cpu: 256

This will launch a httpd service using an external image from dockerhub

NOTE: Usage of image instead of ecr_image.

# stacks/catalog/ecs-service/httpd.yaml
import:
  - catalog/ecs-service/defaults

components:
  terraform:
    ecs/platform/httpd/service:
      metadata:
        component: ecs-service
        inherits:
          - ecs-service/defaults
      vars:
        enabled: true
        name: httpd
        public_lb_enabled: true
        cluster_attributes: [platform]
        containers:
          service:
            name: "Hello"
            image: httpd:2.4
            port_mappings:
              - containerPort: 80
                hostPort: 80
                protocol: tcp
            command:
              - '/bin/sh -c "echo ''<html> <head> <title>Amazon ECS Sample App</title> <style>body {margin-top: 40px;
                background-color: #333;} </style> </head><body> <div style=color:white;text-align:center> <h1>Amazon ECS
                Sample App</h1> <h2>Congratulations!</h2> <p>Your application is now running on a container in Amazon
                ECS.</p> </div></body></html>'' >  /usr/local/apache2/htdocs/index.html && httpd-foreground"'
            entrypoint: ["sh", "-c"]
        task:
          desired_count: 1
          task_memory: 512
          task_cpu: 256

Other Domains

This component supports alternate service names for your ECS Service through a couple of variables:

  • vanity_domain & vanity_alias - This will create a route to the service in the listener rules of the ALB. This will also create a Route 53 alias record in the hosted zone in this account. The hosted zone is looked up by the vanity_domain input.
  • additional_targets - This will create a route to the service in the listener rules of the ALB. This will not create a Route 53 alias record.

Examples:

ecs/platform/service/echo-server:
  vars:
    vanity_domain: "dev-acme.com"
    vanity_alias:
      - "echo-server.dev-acme.com"
    additional_targets:
      - "echo.acme.com"

This then creates the following listener rules:

HTTP Host Header is
echo-server.public-platform.use2.dev.plat.service-discovery.com
OR echo-server.dev-acme.com
OR echo.acme.com

It will also create the record in Route53 to point "echo-server.dev-acme.com" to the ALB. Thus "echo-server.dev-acme.com" should resolve.

We can then create a pointer to this service in the acme.come hosted zone.

dns-primary:
  vars:
    domain_names:
      - acme.com
    record_config:
      - root_zone: acme.com
        name: echo.
        type: CNAME
        ttl: 60
        records:
          - echo-server.dev-acme.com

This will create a CNAME record in the acme.com hosted zone that points echo.acme.com to echo-server.dev-acme.com.

EFS

EFS is supported by this ecs service, you can use either efs_volumes or efs_component_volumes in your task definition.

This example shows how to use efs_component_volumes which remote looks up efs component and uses the efs_id to mount the volume. And how to use efs_volumes

components:
  terraform:
    ecs-services/my-service:
      metadata:
        component: ecs-service
        inherits:
          - ecs-services/defaults
      vars:
        containers:
          service:
            name: app
            image: my-image:latest
            log_configuration:
              logDriver: awslogs
              options: {}
            port_mappings:
              - containerPort: 8080
                hostPort: 8080
                protocol: tcp
            mount_points:
              - containerPath: "/var/lib/"
                sourceVolume: "my-volume-mount"

        task:
          efs_component_volumes:
            - name: "my-volume-mount"
              host_path: null
              efs_volume_configuration:
                - component: efs/my-volume-mount
                  root_directory: "/var/lib/"
                  transit_encryption: "ENABLED"
                  transit_encryption_port: 2999
                  authorization_config: []
          efs_volumes:
            - name: "my-volume-mount-2"
              host_path: null
              efs_volume_ configuration:
                - file_system_id: "fs-1234"
                  root_directory: "/var/lib/"
                  transit_encryption: "ENABLED"
                  transit_encryption_port: 2998
                  authorization_config: []

Important

In Cloud Posse's examples, we avoid pinning modules to specific versions to prevent discrepancies between the documentation and the latest released versions. However, for your own projects, we strongly advise pinning each module to the exact version you're using. This practice ensures the stability of your infrastructure. Additionally, we recommend implementing a systematic approach for updating versions to avoid unexpected changes.

Requirements

NameVersion
terraform>= 1.8.0
aws>= 4.66.1, < 6.0.0
jq>=0.2.0

Providers

NameVersion
aws>= 4.66.1, < 6.0.0
jq>=0.2.0

Modules

NameSourceVersion
albcloudposse/stack-config/yaml//modules/remote-state2.0.0
alb_ingresscloudposse/alb-ingress/aws0.31.0
cloudmap_namespacecloudposse/stack-config/yaml//modules/remote-state2.0.0
cloudmap_namespace_service_discoverycloudposse/stack-config/yaml//modules/remote-state2.0.0
container_definitioncloudposse/ecs-container-definition/aws0.61.2
datadog_container_definitioncloudposse/ecs-container-definition/aws0.61.2
datadog_fluent_bit_container_definitioncloudposse/ecs-container-definition/aws0.61.2
datadog_sidecar_logscloudposse/cloudwatch-logs/aws0.6.9
ecs_alb_service_taskcloudposse/ecs-alb-service-task/aws0.78.0
ecs_cloudwatch_autoscalingcloudposse/ecs-cloudwatch-autoscaling/aws1.0.0
ecs_cloudwatch_sns_alarmscloudposse/ecs-cloudwatch-sns-alarms/aws0.13.2
ecs_clustercloudposse/stack-config/yaml//modules/remote-state2.0.0
efscloudposse/stack-config/yaml//modules/remote-state2.0.0
gha_assume_role../account-map/modules/team-assume-role-policyn/a
gha_role_namecloudposse/label/null0.25.0
iam_rolecloudposse/stack-config/yaml//modules/remote-state2.0.0
iam_roles../account-map/modules/iam-rolesn/a
logscloudposse/cloudwatch-logs/aws0.6.9
nlbcloudposse/stack-config/yaml//modules/remote-state2.0.0
rdscloudposse/stack-config/yaml//modules/remote-state2.0.0
roles_to_principals../account-map/modules/roles-to-principalsn/a
s3cloudposse/stack-config/yaml//modules/remote-state2.0.0
security_groupcloudposse/stack-config/yaml//modules/remote-state2.0.0
service_domaincloudposse/stack-config/yaml//modules/remote-state2.0.0
task_exec_iam_policycloudposse/iam-policy/aws2.0.2
thiscloudposse/label/null0.25.0
vanity_aliascloudposse/route53-alias/aws0.13.0
vpccloudposse/stack-config/yaml//modules/remote-state2.0.0

Resources

NameType
aws_iam_policy.defaultresource
aws_iam_role.github_actionsresource
aws_iam_role_policy.github_actionsresource
aws_iam_role_policy_attachment.additional_execresource
aws_iam_role_policy_attachment.custom_execresource
aws_kinesis_stream.defaultresource
aws_s3_object.task_definition_templateresource
aws_security_group_rule.custom_sg_rulesresource
aws_service_discovery_service.defaultresource
aws_ssm_parameter.full_urlsresource
aws_caller_identity.currentdata source
aws_ecs_task_definition.created_taskdata source
aws_iam_policy_document.github_actions_iam_ecspresso_policydata source
aws_iam_policy_document.github_actions_iam_platform_policydata source
aws_iam_policy_document.github_actions_iam_policydata source
aws_iam_policy_document.thisdata source
aws_kms_alias.selecteddata source
aws_route53_zone.selecteddata source
aws_route53_zone.selected_vanitydata source
aws_s3_object.task_definitiondata source
aws_s3_objects.mirrordata source
aws_ssm_parameter.datadog_api_keydata source
aws_ssm_parameters_by_path.defaultdata source
jq_query.service_domain_querydata source

Inputs

NameDescriptionTypeDefaultRequired
additional_lb_target_groupsAdditional load balancer target group configurations for registering multiple container ports.
This allows you to register sidecar containers to separate target groups.
Each entry requires:
- container_name: Name of the container to register
- container_port: Port on the container to register
- target_group_arn: ARN of the target group. Each additional port must specify a unique target group ARN
list(object({
container_name = string
container_port = number
target_group_arn = string
}))
[]no
additional_security_groupsA list of additional security group IDs to add to the servicelist(string)[]no
additional_tag_mapAdditional 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
additional_targetsAdditional target routes to add to the ALB that point to this service. The only difference between this and var.vanity_alias is var.vanity_alias will create an alias record in Route 53 in the hosted zone in this account as well. var.additional_targets only adds the listener route to this service's target group.list(string)[]no
alb_configurationThe configuration to use for the ALB, specifying which cluster alb configuration to usestring"default"no
alb_nameThe name of the ALB this service should attach tostringnullno
attributesID 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_dimensionThe dimension to use to decide to autoscalestring"cpu"no
autoscaling_enabledShould this service autoscale using SNS alaramsbooltrueno
chamber_serviceSSM parameter service name for use with chamber. This is used in chamber_format where /chamber_service/chamber\_service/name/container_name/container\_name/parameter would be the default.string"ecs-service"no
cluster_attributesThe attributes of the cluster name e.g. if the full name is namespace-tenant-environment-dev-ecs-b2b then the cluster_name is ecs and this value should be b2b.list(string)[]no
containersInputs for the container definition module.
user: The user to run as inside the container. Can be any of these formats: user, user:group, uid, uid:gid, user:gid, uid:group. The default (null) will use the container's configured USER directive or root if not set."
map(object({
name = string
ecr_image = optional(string)
image = optional(string)
memory = optional(number)
memory_reservation = optional(number)
cpu = optional(number)
essential = optional(bool, true)
readonly_root_filesystem = optional(bool, null)
privileged = optional(bool, null)
user = optional(string, null)
container_depends_on = optional(list(object({
containerName = string
condition = string # START, COMPLETE, SUCCESS, HEALTHY
})), null)

port_mappings = optional(list(object({
containerPort = number
hostPort = optional(number)
protocol = optional(string)
name = optional(string)
appProtocol = optional(string)
})), [])
command = optional(list(string), null)
entrypoint = optional(list(string), null)
healthcheck = optional(object({
command = list(string)
interval = number
retries = number
startPeriod = number
timeout = number
}), null)
ulimits = optional(list(object({
name = string
softLimit = number
hardLimit = number
})), null)
log_configuration = optional(object({
logDriver = string
options = optional(map(string), {})
}))
docker_labels = optional(map(string), null)
map_environment = optional(map(string), {})
map_secrets = optional(map(string), {})
volumes_from = optional(list(object({
sourceContainer = string
readOnly = bool
})), null)
mount_points = optional(list(object({
sourceVolume = optional(string)
containerPath = optional(string)
readOnly = optional(bool)
})), [])
}))
{}no
contextSingle 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
cpu_utilization_high_alarm_actionsA list of ARNs (i.e. SNS Topic ARN) to notify on CPU Utilization High Alarm actionlist(string)[]no
cpu_utilization_high_evaluation_periodsNumber of periods to evaluate for the alarmnumber1no
cpu_utilization_high_ok_actionsA list of ARNs (i.e. SNS Topic ARN) to notify on CPU Utilization High OK actionlist(string)[]no
cpu_utilization_high_periodDuration in seconds to evaluate for the alarmnumber300no
cpu_utilization_high_thresholdThe maximum percentage of CPU utilization averagenumber80no
cpu_utilization_low_alarm_actionsA list of ARNs (i.e. SNS Topic ARN) to notify on CPU Utilization Low Alarm actionlist(string)[]no
cpu_utilization_low_evaluation_periodsNumber of periods to evaluate for the alarmnumber1no
cpu_utilization_low_ok_actionsA list of ARNs (i.e. SNS Topic ARN) to notify on CPU Utilization Low OK actionlist(string)[]no
cpu_utilization_low_periodDuration in seconds to evaluate for the alarmnumber300no
cpu_utilization_low_thresholdThe minimum percentage of CPU utilization averagenumber20no
custom_security_group_rulesThe list of custom security group rules to add to the service security group
list(object({
type = string
from_port = number
to_port = number
protocol = string
cidr_blocks = optional(list(string))
description = optional(string)
source_security_group_id = optional(string)
prefix_list_ids = optional(list(string))
security_group_id = optional(string)
}))
[]no
datadog_agent_sidecar_enabledEnable the Datadog Agent Sidecarboolfalseno
datadog_api_key_ssm_parameter_nameThe SSM Parameter Name containing the Datadog API Keystringnullno
datadog_log_method_is_firelensDatadog logs can be sent via cloudwatch logs (and lambda) or firelens, set this to true to enable firelens via a sidecar container for fluentbitboolfalseno
datadog_logging_default_tags_enabledAdd Default tags to all logs sent to Datadogbooltrueno
datadog_logging_tagsTags to add to all logs sent to Datadogmap(string)nullno
datadog_sidecar_containers_logs_enabledEnable the Datadog Agent Sidecar to send logs to aws cloudwatch group, requires datadog_agent_sidecar_enabled to be truebooltrueno
datadog_siteThe Datadog Site to send logs tostring"us5.datadoghq.com"no
delimiterDelimiter to be used between ID elements.
Defaults to - (hyphen). Set to "" to use no delimiter at all.
stringnullno
descriptor_formatsDescribe 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
ecr_regionThe region to use for the fully qualified ECR image URL. Defaults to the current region.string""no
ecr_stage_nameThe ecr stage (account) name to use for the fully qualified ECR image URL.string"auto"no
ecs_cluster_nameThe name of the ECS Cluster this belongs toany"ecs"no
enable_all_egress_ruleA flag to enable/disable adding the all ports egress rule to the service security groupbooltrueno
enabledSet to false to prevent the module from creating any resourcesboolnullno
environmentID element. Usually used for region e.g. 'uw2', 'us-west-2', OR role 'prod', 'staging', 'dev', 'UAT'stringnullno
exec_enabledSpecifies whether to enable Amazon ECS Exec for the tasks within the serviceboolfalseno
github_actions_allowed_reposA list of the GitHub repositories that are allowed to assume this role from GitHub Actions. For example,
["cloudposse/infra-live"]. Can contain "*" as wildcard.
If org part of repo name is omitted, "cloudposse" will be assumed.
list(string)[]no
github_actions_ecspresso_enabledCreate IAM policies required for deployments with Ecspressoboolfalseno
github_actions_iam_role_attributesAdditional attributes to add to the role namelist(string)[]no
github_actions_iam_role_enabledFlag to toggle creation of an IAM Role that GitHub Actions can assume to access AWS resourcesboolfalseno
github_oidc_trusted_role_arnsA list of IAM Role ARNs allowed to assume this cluster's GitHub OIDC rolelist(string)[]no
health_check_healthy_thresholdThe number of consecutive health checks successes required before healthynumber2no
health_check_intervalThe duration in seconds in between health checksnumber15no
health_check_matcherThe HTTP response codes to indicate a healthy checkstring"200-404"no
health_check_pathThe destination for the health check requeststring"/health"no
health_check_portThe port to use to connect with the target. Valid values are either ports 1-65536, or traffic-port. Defaults to traffic-portstring"traffic-port"no
health_check_protocolThe protocol to use to connect with the target. Defaults to HTTP. Not applicable when target_type is lambdastring"HTTP"no
health_check_timeoutThe amount of time to wait in seconds before failing a health check requestnumber10no
health_check_unhealthy_thresholdThe number of consecutive health check failures required before unhealthynumber2no
http_protocolWhich http protocol to use in outputs and SSM url params. This value is ignored if a load balancer is not used. If it is null, the redirect value from the ALB determines the protocol.stringnullno
iam_policy_enabledIf set to true will create IAM policy in AWSboolfalseno
iam_policy_statementsMap of IAM policy statements to use in the policy. This can be used with or instead of the var.iam_source_json_url.any{}no
id_length_limitLimit 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.
numbernullno
kinesis_enabledEnable Kinesisboolfalseno
kms_alias_name_ssmKMS alias name for SSMstring"alias/aws/ssm"no
kms_key_aliasID of KMS keystring"default"no
label_key_caseControls 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.
stringnullno
label_orderThe 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)nullno
label_value_caseControls 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.
stringnullno
labels_as_tagsSet 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
lb_catch_allShould this service act as catch all for all subdomain hosts of the vanity domainboolfalseno
logsFeed inputs into cloudwatch logs moduleany{}no
memory_utilization_high_alarm_actionsA list of ARNs (i.e. SNS Topic ARN) to notify on Memory Utilization High Alarm actionlist(string)[]no
memory_utilization_high_evaluation_periodsNumber of periods to evaluate for the alarmnumber1no
memory_utilization_high_ok_actionsA list of ARNs (i.e. SNS Topic ARN) to notify on Memory Utilization High OK actionlist(string)[]no
memory_utilization_high_periodDuration in seconds to evaluate for the alarmnumber300no
memory_utilization_high_thresholdThe maximum percentage of Memory utilization averagenumber80no
memory_utilization_low_alarm_actionsA list of ARNs (i.e. SNS Topic ARN) to notify on Memory Utilization Low Alarm actionlist(string)[]no
memory_utilization_low_evaluation_periodsNumber of periods to evaluate for the alarmnumber1no
memory_utilization_low_ok_actionsA list of ARNs (i.e. SNS Topic ARN) to notify on Memory Utilization Low OK actionlist(string)[]no
memory_utilization_low_periodDuration in seconds to evaluate for the alarmnumber300no
memory_utilization_low_thresholdThe minimum percentage of Memory utilization averagenumber20no
nameID 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.
stringnullno
namespaceID element. Usually an abbreviation of your organization name, e.g. 'eg' or 'cp', to help ensure generated IDs are globally uniquestringnullno
nlb_nameThe name of the NLB this service should attach tostringnullno
portThe port for the created ALB target group. Defaults to 80number80no
protocolThe protocol for the created ALB target group. Defaults to HTTPstring"HTTP"no
rds_nameThe name of the RDS database this service should allow access toanynullno
regex_replace_charsTerraform 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.
stringnullno
regionAWS Regionstringn/ayes
retention_periodLength of time data records are accessible after they are added to the streamnumber48no
s3_mirror_nameThe name of the S3 mirror componentstringnullno
scale_down_step_adjustmentsList of step adjustments for scale down policy
list(object({
metric_interval_lower_bound = optional(number)
metric_interval_upper_bound = optional(number)
scaling_adjustment = number
}))
[
{
"metric_interval_lower_bound": null,
"metric_interval_upper_bound": 0,
"scaling_adjustment": -1
}
]
no
scale_up_step_adjustmentsList of step adjustments for scale up policy
list(object({
metric_interval_lower_bound = optional(number)
metric_interval_upper_bound = optional(number)
scaling_adjustment = number
}))
[
{
"metric_interval_lower_bound": 0,
"metric_interval_upper_bound": null,
"scaling_adjustment": 1
}
]
no
service_connect_configurationsThe list of Service Connect configurations.
See service_connect_configuration docs https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_service#service_connect_configuration
list(object({
enabled = bool
namespace = optional(string, null)
log_configuration = optional(object({
log_driver = string
options = optional(map(string), null)
secret_option = optional(list(object({
name = string
value_from = string
})), [])
}), null)
service = optional(list(object({
client_alias = list(object({
dns_name = string
port = number
}))
discovery_name = optional(string, null)
ingress_port_override = optional(number, null)
port_name = string
})), [])
}))
[]no
service_registriesThe list of Service Registries.
See service_registries docs https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/ecs_service#service_registries
list(object({
namespace = string
registry_arn = optional(string)
port = optional(number)
container_name = optional(string)
container_port = optional(number)
}))
[]no
shard_countNumber of shards that the stream will usenumber1no
shard_level_metricsList of shard-level CloudWatch metrics which can be enabled for the streamlist(string)
[
"IncomingBytes",
"IncomingRecords",
"IteratorAgeMilliseconds",
"OutgoingBytes",
"OutgoingRecords",
"ReadProvisionedThroughputExceeded",
"WriteProvisionedThroughputExceeded"
]
no
ssm_enabledIf true create SSM keys for the database user and password.boolfalseno
ssm_key_formatSSM path format. The values will will be used in the following order: var.ssm_key_prefix, var.name, var.ssm_key_*string"/%v/%v/%v"no
ssm_key_prefixSSM path prefix. Omit the leading forward slash /.string"ecs-service"no
stageID element. Usually used to indicate role, e.g. 'prod', 'staging', 'source', 'build', 'test', 'deploy', 'release'stringnullno
stickiness_cookie_durationThe 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)number86400no
stickiness_enabledBoolean to enable / disable stickiness. Default is truebooltrueno
stickiness_typeThe type of sticky sessions. The only current possible value is lb_cookiestring"lb_cookie"no
stream_modeStream mode details for the Kinesis streamstring"PROVISIONED"no
tagsAdditional tags (e.g. {'BusinessUnit': 'XYZ'}).
Neither the tag keys nor the tag values will be modified by this module.
map(string){}no
taskFeed inputs into ecs_alb_service_task module
object({
task_cpu = optional(number)
task_memory = optional(number)
task_role_arn = optional(string, "")
pid_mode = optional(string, null)
ipc_mode = optional(string, null)
network_mode = optional(string)
propagate_tags = optional(string)
assign_public_ip = optional(bool, false)
use_alb_security_groups = optional(bool, true)
launch_type = optional(string, "FARGATE")
scheduling_strategy = optional(string, "REPLICA")
capacity_provider_strategies = optional(list(object({
capacity_provider = string
weight = number
base = number
})), [])

deployment_minimum_healthy_percent = optional(number, null)
deployment_maximum_percent = optional(number, null)
desired_count = optional(number, 0)
min_capacity = optional(number, 1)
max_capacity = optional(number, 2)
wait_for_steady_state = optional(bool, true)
circuit_breaker_deployment_enabled = optional(bool, true)
circuit_breaker_rollback_enabled = optional(bool, true)

ignore_changes_task_definition = optional(bool, true)
ignore_changes_desired_count = optional(bool, false)

ecs_service_enabled = optional(bool, true)
bind_mount_volumes = optional(list(object({
name = string
host_path = string
})), [])
efs_volumes = optional(list(object({
host_path = string
name = 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
}))
}))
})), [])
efs_component_volumes = optional(list(object({
host_path = string
name = string
efs_volume_configuration = list(object({
component = optional(string, "efs")
tenant = optional(string, null)
environment = optional(string, null)
stage = optional(string, null)

root_directory = string
transit_encryption = string
transit_encryption_port = string
authorization_config = list(object({
access_point_id = string
iam = string
}))
}))
})), [])
docker_volumes = optional(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
}))
})), [])
fsx_volumes = optional(list(object({
host_path = string
name = string
fsx_windows_file_server_volume_configuration = list(object({
file_system_id = string
root_directory = string
authorization_config = list(object({
credentials_parameter = string
domain = string
}))
}))
})), [])
})
{}no
task_enabledWhether or not to use the ECS task modulebooltrueno
task_exec_iam_policyIAM policy as list of Terraform objects, compatible with Terraform aws_iam_policy_document data source
except that source_policy_documents and override_policy_documents are not included.
Use inputs iam_source_policy_documents and iam_override_policy_documents for that.
list(object({
policy_id = optional(string, null)
version = optional(string, null)
statements = list(object({
sid = optional(string, null)
effect = optional(string, null)
actions = optional(list(string), null)
not_actions = optional(list(string), null)
resources = optional(list(string), null)
not_resources = optional(list(string), null)
conditions = optional(list(object({
test = string
variable = string
values = list(string)
})), [])
principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
not_principals = optional(list(object({
type = string
identifiers = list(string)
})), [])
}))
}))
[]no
task_exec_policy_arns_mapA map of name to IAM Policy ARNs to attach to the generated task execution role.
The names are arbitrary, but must be known at plan time. The purpose of the name
is so that changes to one ARN do not cause a ripple effect on the other ARNs.
If you cannot provide unique names known at plan time, use task_exec_policy_arns instead.
map(string){}no
task_iam_role_componentA component that outputs an iam_role module as 'role' for adding to the service as a whole.stringnullno
task_policy_arnsThe IAM policy ARNs to attach to the ECS task IAM rolelist(string)
[
"arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly",
"arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess"
]
no
task_security_group_componentA component that outputs security_group_id for adding to the service as a whole.stringnullno
tenantID element _(Rarely used, not included by default)_. A customer identifier, indicating who this instance of a resource is forstringnullno
unauthenticated_pathsUnauthenticated path pattern to matchlist(string)[]no
unauthenticated_priorityThe priority for the rules without authentication, between 1 and 50000 (1 being highest priority). Must be different from authenticated_priority since a listener can't have multiple rules with the same prioritystring0no
use_lbWhether use load balancer for the serviceboolfalseno
use_rds_client_sgUse the RDS client security groupboolfalseno
vanity_aliasThe vanity aliases to use for the public LB.list(string)[]no
vanity_domainWhether to use the vanity domain alias for the servicestringnullno
vpc_component_nameThe name of a VPC componentstring"vpc"no
zone_componentThe component name to look up service domain remote-state onstring"dns-delegated"no
zone_component_outputA json query to use to get the zone domain from the remote state. Seestring".default_domain_name"no

Outputs

NameDescription
ecs_cluster_arnSelected ECS cluster ARN
environment_mapEnvironment variables to pass to the container, this is a map of key/value pairs, where the key is containerName,variableName
full_domainDomain to respond to GET requests
github_actions_iam_role_arnARN of IAM role for GitHub Actions
github_actions_iam_role_nameName of IAM role for GitHub Actions
lb_arnSelected LB ARN
lb_listener_httpsSelected LB HTTPS Listener
lb_sg_idSelected LB SG ID
logsOutput of cloudwatch logs module
service_arnThe ECS service ARN
service_imageThe image of the service container
service_nameThe ECS service name
service_sg_idThe ECS service security group ID
ssm_key_prefixSSM prefix
ssm_parametersSSM parameters for the ECS Service
subnet_idsSelected subnet IDs
task_definition_arnThe task definition ARN
task_definition_revisionThe task definition revision
task_templateThe task template rendered
vpc_idSelected VPC ID
vpc_sg_idSelected VPC SG ID

Check out these related projects.

  • Cloud Posse Terraform Modules - Our collection of reusable Terraform modules used by our reference architectures.
  • Atmos - Atmos is like docker-compose but for your infrastructure

References

For additional context, refer to some of these links.

Tip

Use Terraform Reference Architectures for AWS

Use Cloud Posse's ready-to-go terraform architecture blueprints for AWS to get up and running quickly.

βœ… We build it together with your team.
βœ… Your team owns everything.
βœ… 100% Open Source and backed by fanatical support.

Request Quote

πŸ“š Learn More

Cloud Posse is the leading DevOps Accelerator for funded startups and enterprises.

Your team can operate like a pro today.

Ensure that your team succeeds by using Cloud Posse's proven process and turnkey blueprints. Plus, we stick around until you succeed.

Day-0: Your Foundation for Success

  • Reference Architecture. You'll get everything you need from the ground up built using 100% infrastructure as code.
  • Deployment Strategy. Adopt a proven deployment strategy with GitHub Actions, enabling automated, repeatable, and reliable software releases.
  • Site Reliability Engineering. Gain total visibility into your applications and services with Datadog, ensuring high availability and performance.
  • Security Baseline. Establish a secure environment from the start, with built-in governance, accountability, and comprehensive audit logs, safeguarding your operations.
  • GitOps. Empower your team to manage infrastructure changes confidently and efficiently through Pull Requests, leveraging the full power of GitHub Actions.

Request Quote

Day-2: Your Operational Mastery

  • Training. Equip your team with the knowledge and skills to confidently manage the infrastructure, ensuring long-term success and self-sufficiency.
  • Support. Benefit from a seamless communication over Slack with our experts, ensuring you have the support you need, whenever you need it.
  • Troubleshooting. Access expert assistance to quickly resolve any operational challenges, minimizing downtime and maintaining business continuity.
  • Code Reviews. Enhance your team’s code quality with our expert feedback, fostering continuous improvement and collaboration.
  • Bug Fixes. Rely on our team to troubleshoot and resolve any issues, ensuring your systems run smoothly.
  • Migration Assistance. Accelerate your migration process with our dedicated support, minimizing disruption and speeding up time-to-value.
  • Customer Workshops. Engage with our team in weekly workshops, gaining insights and strategies to continuously improve and innovate.

Request Quote

✨ Contributing

This project is under active development, and we encourage contributions from our community.

Many thanks to our outstanding contributors:

For πŸ› bug reports & feature requests, please use the issue tracker.

In general, PRs are welcome. We follow the typical "fork-and-pull" Git workflow.

  1. Review our Code of Conduct and Contributor Guidelines.
  2. Fork the repo on GitHub
  3. Clone the project to your own machine
  4. Commit changes to your own branch
  5. Push your work back up to your fork
  6. Submit a Pull Request so that we can review your changes

NOTE: Be sure to merge the latest changes from "upstream" before making a pull request!

Running Terraform Tests

We use Atmos to streamline how Terraform tests are run. It centralizes configuration and wraps common test workflows with easy-to-use commands.

All tests are located in the test/ folder.

Under the hood, tests are powered by Terratest together with our internal Test Helpers library, providing robust infrastructure validation.

Setup dependencies:

To run tests:

  • Run all tests:
    atmos test run
    
  • Clean up test artifacts:
    atmos test clean
    
  • Explore additional test options:
    atmos test --help
    

The configuration for test commands is centrally managed. To review what's being imported, see the atmos.yaml file.

Learn more about our automated testing in our documentation or implementing custom commands with atmos.

🌎 Slack Community

Join our Open Source Community on Slack. It's FREE for everyone! Our "SweetOps" community is where you get to talk with others who share a similar vision for how to rollout and manage infrastructure. This is the best place to talk shop, ask questions, solicit feedback, and work together as a community to build totally sweet infrastructure.

πŸ“° Newsletter

Sign up for our newsletter and join 3,000+ DevOps engineers, CTOs, and founders who get insider access to the latest DevOps trends, so you can always stay in the know. Dropped straight into your Inbox every week β€” and usually a 5-minute read.

πŸ“† Office Hours

Join us every Wednesday via Zoom for your weekly dose of insider DevOps trends, AWS news and Terraform insights, all sourced from our SweetOps community, plus a live Q&A that you can’t find anywhere else. It's FREE for everyone!

License

License

Preamble to the Apache License, Version 2.0

Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.

Trademarks

All other trademarks referenced herein are the property of their respective owners.


Copyright Β© 2017-2026 Cloud Posse, LLC

README footer

Beacon