Resource: awsEcsService
-> Note: To prevent a race condition during service deletion, make sure to set dependsOn
to the related awsIamRolePolicy
; otherwise, the policy may be destroyed too soon and the ECS service will then get stuck in the draining
state.
Provides an ECS service - effectively a task that is expected to run until an error occurs or a user terminates it (typically a webserver or a database).
See ECS Services section in AWS developer guide.
Example Usage
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.ecsService.EcsService(this, "mongo", {
cluster: "${aws_ecs_cluster.foo.id}",
depends_on: ["${aws_iam_role_policy.foo}"],
desiredCount: 3,
iamRole: "${aws_iam_role.foo.arn}",
loadBalancer: [
{
containerName: "mongo",
containerPort: 8080,
targetGroupArn: "${aws_lb_target_group.foo.arn}",
},
],
name: "mongodb",
orderedPlacementStrategy: [
{
field: "cpu",
type: "binpack",
},
],
placementConstraints: [
{
expression: "attribute:ecs.availability-zone in [us-west-2a, us-west-2b]",
type: "memberOf",
},
],
taskDefinition: "${aws_ecs_task_definition.mongo.arn}",
});
Ignoring Changes to Desired Count
You can utilize the generic Terraform resource lifecycle configuration block with ignoreChanges
to create an ECS service with an initial count of running instances, then ignore any changes to that count caused externally (e.g., Application Autoscaling).
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsEcsServiceExample = new aws.ecsService.EcsService(this, "example", {
desiredCount: 2,
});
awsEcsServiceExample.addOverride("lifecycle", [
{
ignore_changes: ["${desired_count}"],
},
]);
Daemon Scheduling Strategy
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.ecsService.EcsService(this, "bar", {
cluster: "${aws_ecs_cluster.foo.id}",
name: "bar",
schedulingStrategy: "DAEMON",
taskDefinition: "${aws_ecs_task_definition.bar.arn}",
});
CloudWatch Deployment Alarms
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.ecsService.EcsService(this, "example", {
alarms: {
alarmNames: ["${aws_cloudwatch_metric_alarm.example.alarm_name}"],
enable: true,
rollback: true,
},
cluster: "${aws_ecs_cluster.example.id}",
name: "example",
});
External Deployment Controller
/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
new aws.ecsService.EcsService(this, "example", {
cluster: "${aws_ecs_cluster.example.id}",
deploymentController: {
type: "EXTERNAL",
},
name: "example",
});
Redeploy Service On Every Apply
The key used with triggers
is arbitrary.
resource "aws_ecs_service" "example" {
# ... other configurations ...
force_new_deployment = true
triggers = {
redeployment = timestamp()
}
}
Argument Reference
The following arguments are required:
name
- (Required) Name of the service (up to 255 letters, numbers, hyphens, and underscores)
The following arguments are optional:
alarms
- (Optional) Information about the CloudWatch alarms. See below.capacityProviderStrategy
- (Optional) Capacity provider strategies to use for the service. Can be one or more. These can be updated without destroying and recreating the service only ifforceNewDeployment =True
and not changing from 0capacityProviderStrategy
blocks to greater than 0, or vice versa. See below.cluster
- (Optional) ARN of an ECS cluster.deploymentCircuitBreaker
- (Optional) Configuration block for deployment circuit breaker. See below.deploymentController
- (Optional) Configuration block for deployment controller configuration. See below.deploymentMaximumPercent
- (Optional) 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. Not valid when using thedaemon
scheduling strategy.deploymentMinimumHealthyPercent
- (Optional) 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.desiredCount
- (Optional) Number of instances of the task definition to place and keep running. Defaults to 0. Do not specify if using thedaemon
scheduling strategy.enableEcsManagedTags
- (Optional) Specifies whether to enable Amazon ECS managed tags for the tasks within the service.enableExecuteCommand
- (Optional) Specifies whether to enable Amazon ECS Exec for the tasks within the service.forceNewDeployment
- (Optional) Enable to force a new task deployment of the service. This can be used to update tasks to use a newer Docker image with same image/tag combination (e.g.,myimage:latest
), roll Fargate tasks onto a newer platform version, or immediately deployorderedPlacementStrategy
andplacementConstraints
updates.healthCheckGracePeriodSeconds
- (Optional) Seconds to ignore failing load balancer health checks on newly instantiated tasks to prevent premature shutdown, up to 2147483647. Only valid for services configured to use load balancers.iamRole
- (Optional) ARN of the IAM role that allows Amazon ECS to make calls to your load balancer on your behalf. This parameter is required if you are using a load balancer with your service, but only if your task definition does not use theawsvpc
network mode. If usingawsvpc
network mode, do not specify this role. If your account has already created the Amazon ECS service-linked role, that role is used by default for your service unless you specify a role here.launchType
- (Optional) Launch type on which to run your service. The valid values areec2
,fargate
, andexternal
. Defaults toec2
.loadBalancer
- (Optional) Configuration block for load balancers. See below.networkConfiguration
- (Optional) Network configuration for the service. This parameter is required for task definitions that use theawsvpc
network mode to receive their own Elastic Network Interface, and it is not supported for other network modes. See below.orderedPlacementStrategy
- (Optional) Service level strategy rules that are taken into consideration during task placement. List from top to bottom in order of precedence. Updates to this configuration will take effect next task deployment unlessforceNewDeployment
is enabled. The maximum number oforderedPlacementStrategy
blocks is5
. See below.placementConstraints
- (Optional) Rules that are taken into consideration during task placement. Updates to this configuration will take effect next task deployment unlessforceNewDeployment
is enabled. Maximum number ofplacementConstraints
is10
. See below.platformVersion
- (Optional) Platform version on which to run your service. Only applicable forlaunchType
set tofargate
. Defaults tolatest
. More information about Fargate platform versions can be found in the AWS ECS User Guide.propagateTags
- (Optional) Specifies whether to propagate the tags from the task definition or the service to the tasks. The valid values areservice
andTASK_DEFINITION
.schedulingStrategy
- (Optional) Scheduling strategy to use for the service. The valid values arereplica
anddaemon
. Defaults toreplica
. Note that Tasks using the Fargate launch type or theCODE_DEPLOY
orexternal
deployment controller types don't support thedaemon
scheduling strategy.serviceConnectConfiguration
- (Optional) The ECS Service Connect configuration for this service to discover and connect to services, and be discovered by, and connected from, other services within a namespace. See below.serviceRegistries
- (Optional) Service discovery registries for the service. The maximum number ofserviceRegistries
blocks is1
. See below.tags
- (Optional) Key-value map of resource tags. If configured with a providerdefaultTags
configuration block present, tags with matching keys will overwrite those defined at the provider-level.taskDefinition
- (Optional) Family and revision (family:revision
) or full ARN of the task definition that you want to run in your service. Required unless using theexternal
deployment controller. If a revision is not specified, the latestactive
revision is used.triggers
- (Optional) Map of arbitrary keys and values that, when changed, will trigger an in-place update (redeployment). Useful withtimestamp()
. See example above.waitForSteadyState
- (Optional) Iftrue
, Terraform will wait for the service to reach a steady state (likeawsEcsWaitServicesStable
) before continuing. Defaultfalse
.
alarms
The alarms
configuration block supports the following:
alarmsNames
- (Required) One or more CloudWatch alarm names.enable
- (Required) Determines whether to use the CloudWatch alarm option in the service deployment process.rollback
- (Required) Determines whether to configure Amazon ECS to roll back the service if a service deployment fails. If rollback is used, when a service deployment fails, the service is rolled back to the last deployment that completed successfully.
capacityProviderStrategy
The capacityProviderStrategy
configuration block supports the following:
base
- (Optional) Number of tasks, at a minimum, to run on the specified capacity provider. Only one capacity provider in a capacity provider strategy can have a base defined.capacityProvider
- (Required) Short name of the capacity provider.weight
- (Required) Relative percentage of the total number of launched tasks that should use the specified capacity provider.
deploymentCircuitBreaker
The deploymentCircuitBreaker
configuration block supports the following:
enable
- (Required) Whether to enable the deployment circuit breaker logic for the service.rollback
- (Required) Whether to enable Amazon ECS to roll back the service if a service deployment fails. If rollback is enabled, when a service deployment fails, the service is rolled back to the last deployment that completed successfully.
deploymentController
The deploymentController
configuration block supports the following:
type
- (Optional) Type of deployment controller. Valid values:CODE_DEPLOY
,ecs
,external
. Default:ecs
.
loadBalancer
loadBalancer
supports the following:
elbName
- (Required for ELB Classic) Name of the ELB (Classic) to associate with the service.targetGroupArn
- (Required for ALB/NLB) ARN of the Load Balancer target group to associate with the service.containerName
- (Required) Name of the container to associate with the load balancer (as it appears in a container definition).containerPort
- (Required) Port on the container to associate with the load balancer.
-> Version note: Multiple loadBalancer
configuration block support was added in Terraform AWS Provider version 2.22.0. This allows configuration of ECS service support for multiple target groups.
networkConfiguration
networkConfiguration
support the following:
subnets
- (Required) Subnets associated with the task or service.securityGroups
- (Optional) Security groups associated with the task or service. If you do not specify a security group, the default security group for the VPC is used.assignPublicIp
- (Optional) Assign a public IP address to the ENI (Fargate launch type only). Valid values aretrue
orfalse
. Defaultfalse
.
For more information, see Task Networking
orderedPlacementStrategy
orderedPlacementStrategy
supports the following:
type
- (Required) Type of placement strategy. Must be one of:binpack
,random
, orspread
field
- (Optional) For thespread
placement strategy, valid values areinstanceId
(orhost
, which has the same effect), or any platform or custom attribute that is applied to a container instance. For thebinpack
type, valid values arememory
andcpu
. For therandom
type, this attribute is not needed. For more information, see Placement Strategy.
-> Note: for spread
, host
and instanceId
will be normalized, by AWS, to be instanceId
. This means the statefile will show instanceId
but your config will differ if you use host
.
placementConstraints
placementConstraints
support the following:
type
- (Required) Type of constraint. The only valid values at this time arememberOf
anddistinctInstance
.expression
- (Optional) Cluster Query Language expression to apply to the constraint. Does not need to be specified for thedistinctInstance
type. For more information, see Cluster Query Language in the Amazon EC2 Container Service Developer Guide.
serviceRegistries
serviceRegistries
support the following:
registryArn
- (Required) ARN of the Service Registry. The currently supported service registry is Amazon Route 53 Auto Naming Service(awsServiceDiscoveryService
). For more information, see Serviceport
- (Optional) Port value used if your Service Discovery service specified an SRV record.containerPort
- (Optional) Port value, already specified in the task definition, to be used for your service discovery service.containerName
- (Optional) Container name value, already specified in the task definition, to be used for your service discovery service.
serviceConnectConfiguration
serviceConnectConfiguration
supports the following:
enabled
- (Required) Specifies whether to use Service Connect with this service.logConfiguration
- (Optional) The log configuration for the container. See below.namespace
- (Optional) The namespace name or ARN of theawsServiceDiscoveryHttpNamespace
for use with Service Connect.service
- (Optional) The list of Service Connect service objects. See below.
logConfiguration
logConfiguration
supports the following:
logDriver
- (Required) The log driver to use for the container.options
- (Optional) The configuration options to send to the log driver.secretOption
- (Optional) The secrets to pass to the log configuration. See below.
secretOption
secretOption
supports the following:
name
- (Required) The name of the secret.valueFrom
- (Required) The secret to expose to the container. The supported values are either the full ARN of the AWS Secrets Manager secret or the full ARN of the parameter in the SSM Parameter Store.
service
service
supports the following:
clientAlias
- (Optional) The list of client aliases for this Service Connect service. You use these to assign names that can be used by client applications. The maximum number of client aliases that you can have in this list is 1. See below.discoveryName
- (Optional) The name of the new AWS Cloud Map service that Amazon ECS creates for this Amazon ECS service.ingressPortOverride
- (Optional) The port number for the Service Connect proxy to listen on.portName
- (Required) The name of one of theportMappings
from all the containers in the task definition of this Amazon ECS service.
clientAlias
clientAlias
supports the following:
dnsName
- (Optional) The name that you use in the applications of client tasks to connect to this service.port
- (Required) The listening port number for the Service Connect proxy. This port is available inside of all of the tasks within the same namespace.
Attributes Reference
In addition to all arguments above, the following attributes are exported:
cluster
- Amazon Resource Name (ARN) of cluster which the service runs on.desiredCount
- Number of instances of the task definition.iamRole
- ARN of IAM role used for ELB.id
- ARN that identifies the service.name
- Name of the service.tagsAll
- A map of tags assigned to the resource, including those inherited from the providerdefaultTags
configuration block.
Timeouts
create
- (Default20M
)update
- (Default20M
)delete
- (Default20M
)
Import
ECS services can be imported using the name
together with ecs cluster name
, e.g.,