aws-cdk-lib.aws_ecs.Ec2Service

class Ec2Service (construct)

LanguageType name
.NETAmazon.CDK.AWS.ECS.Ec2Service
Gogithub.com/aws/aws-cdk-go/awscdk/v2/awsecs#Ec2Service
Javasoftware.amazon.awscdk.services.ecs.Ec2Service
Pythonaws_cdk.aws_ecs.Ec2Service
TypeScript (source)aws-cdk-lib » aws_ecs » Ec2Service

Implements IConstruct, IDependable, IResource, IBaseService, IService, IApplicationLoadBalancerTarget, INetworkLoadBalancerTarget, ILoadBalancerTarget, IConnectable, IEc2Service

This creates a service using the EC2 launch type on an ECS cluster.

Example

declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
declare const vpc: ec2.Vpc;
const service = new ecs.Ec2Service(this, 'Service', { cluster, taskDefinition });

const lb = new elb.LoadBalancer(this, 'LB', { vpc });
lb.addListener({ externalPort: 80 });
lb.addTarget(service.loadBalancerTarget({
  containerName: 'MyContainer',
  containerPort: 80,
}));

Initializer

new Ec2Service(scope: Construct, id: string, props: Ec2ServiceProps)

Parameters

  • scope Construct
  • id string
  • props Ec2ServiceProps

Constructs a new instance of the Ec2Service class.

Construct Props

NameTypeDescription
clusterIClusterThe name of the cluster that hosts the service.
taskDefinitionTaskDefinitionThe task definition to use for tasks in the service.
assignPublicIp?booleanSpecifies whether the task's elastic network interface receives a public IP address.
capacityProviderStrategies?CapacityProviderStrategy[]A list of Capacity Provider strategies used to place a service.
circuitBreaker?DeploymentCircuitBreakerWhether to enable the deployment circuit breaker.
cloudMapOptions?CloudMapOptionsThe options for configuring an Amazon ECS service to use service discovery.
daemon?booleanSpecifies whether the service will use the daemon scheduling strategy.
deploymentAlarms?DeploymentAlarmConfigThe alarm(s) to monitor during deployment, and behavior to apply if at least one enters a state of alarm during the deployment or bake time.
deploymentController?DeploymentControllerSpecifies which deployment controller to use for the service.
desiredCount?numberThe desired number of instantiations of the task definition to keep running on the service.
enableECSManagedTags?booleanSpecifies whether to enable Amazon ECS managed tags for the tasks within the service.
enableExecuteCommand?booleanWhether to enable the ability to execute into a container.
healthCheckGracePeriod?DurationThe period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy Elastic Load Balancing target health checks after a task has first started.
maxHealthyPercent?numberThe maximum number of tasks, specified as a percentage of the Amazon ECS service's DesiredCount value, that can run in a service during a deployment.
minHealthyPercent?numberThe minimum number of tasks, specified as a percentage of the Amazon ECS service's DesiredCount value, that must continue to run and remain healthy during a deployment.
placementConstraints?PlacementConstraint[]The placement constraints to use for tasks in the service.
placementStrategies?PlacementStrategy[]The placement strategies to use for tasks in the service.
propagateTags?PropagatedTagSourceSpecifies whether to propagate the tags from the task definition or the service to the tasks in the service.
securityGroups?ISecurityGroup[]The security groups to associate with the service.
serviceConnectConfiguration?ServiceConnectPropsConfiguration for Service Connect.
serviceName?stringThe name of the service.
vpcSubnets?SubnetSelectionThe subnets to associate with the service.

cluster

Type: ICluster

The name of the cluster that hosts the service.


taskDefinition

Type: TaskDefinition

The task definition to use for tasks in the service.

[disable-awslint:ref-via-interface]


assignPublicIp?

Type: boolean (optional, default: false)

Specifies whether the task's elastic network interface receives a public IP address.

If true, each task will receive a public IP address.

This property is only used for tasks that use the awsvpc network mode.


capacityProviderStrategies?

Type: CapacityProviderStrategy[] (optional, default: undefined)

A list of Capacity Provider strategies used to place a service.


circuitBreaker?

Type: DeploymentCircuitBreaker (optional, default: disabled)

Whether to enable the deployment circuit breaker.

If this property is defined, circuit breaker will be implicitly enabled.


cloudMapOptions?

Type: CloudMapOptions (optional, default: AWS Cloud Map service discovery is not enabled.)

The options for configuring an Amazon ECS service to use service discovery.


daemon?

Type: boolean (optional, default: false)

Specifies whether the service will use the daemon scheduling strategy.

If true, the service scheduler deploys exactly one task on each container instance in your cluster.

When you are using this strategy, do not specify a desired number of tasks orany task placement strategies.


deploymentAlarms?

Type: DeploymentAlarmConfig (optional, default: No alarms will be monitored during deployment.)

The alarm(s) to monitor during deployment, and behavior to apply if at least one enters a state of alarm during the deployment or bake time.


deploymentController?

Type: DeploymentController (optional, default: Rolling update (ECS))

Specifies which deployment controller to use for the service.

For more information, see Amazon ECS Deployment Types


desiredCount?

Type: number (optional, default: When creating the service, default is 1; when updating the service, default uses the current task number.)

The desired number of instantiations of the task definition to keep running on the service.


enableECSManagedTags?

Type: boolean (optional, default: false)

Specifies whether to enable Amazon ECS managed tags for the tasks within the service.

For more information, see Tagging Your Amazon ECS Resources


enableExecuteCommand?

Type: boolean (optional, default: undefined)

Whether to enable the ability to execute into a container.


healthCheckGracePeriod?

Type: Duration (optional, default: defaults to 60 seconds if at least one load balancer is in-use and it is not already set)

The period of time, in seconds, that the Amazon ECS service scheduler ignores unhealthy Elastic Load Balancing target health checks after a task has first started.


maxHealthyPercent?

Type: number (optional, default: 100 if daemon, otherwise 200)

The maximum number of tasks, specified as a percentage of the Amazon ECS service's DesiredCount value, that can run in a service during a deployment.


minHealthyPercent?

Type: number (optional, default: 0 if daemon, otherwise 50)

The minimum number of tasks, specified as a percentage of the Amazon ECS service's DesiredCount value, that must continue to run and remain healthy during a deployment.


placementConstraints?

Type: PlacementConstraint[] (optional, default: No constraints.)

The placement constraints to use for tasks in the service.

For more information, see Amazon ECS Task Placement Constraints.


placementStrategies?

Type: PlacementStrategy[] (optional, default: No strategies.)

The placement strategies to use for tasks in the service.

For more information, see Amazon ECS Task Placement Strategies.


propagateTags?

Type: PropagatedTagSource (optional, default: PropagatedTagSource.NONE)

Specifies whether to propagate the tags from the task definition or the service to the tasks in the service.

Valid values are: PropagatedTagSource.SERVICE, PropagatedTagSource.TASK_DEFINITION or PropagatedTagSource.NONE


securityGroups?

Type: ISecurityGroup[] (optional, default: A new security group is created.)

The security groups to associate with the service.

If you do not specify a security group, a new security group is created.

This property is only used for tasks that use the awsvpc network mode.


serviceConnectConfiguration?

Type: ServiceConnectProps (optional, default: No ports are advertised via Service Connect on this service, and the service cannot make requests to other services via Service Connect.)

Configuration for Service Connect.


serviceName?

Type: string (optional, default: CloudFormation-generated name.)

The name of the service.


vpcSubnets?

Type: SubnetSelection (optional, default: Public subnets if assignPublicIp is set, otherwise the first available one of Private, Isolated, Public, in that order.)

The subnets to associate with the service.

This property is only used for tasks that use the awsvpc network mode.

Properties

NameTypeDescription
clusterIClusterThe cluster that hosts the service.
connectionsConnectionsThe security groups which manage the allowed network traffic for the service.
envResourceEnvironmentThe environment this resource belongs to.
nodeNodeThe tree node.
serviceArnstringThe Amazon Resource Name (ARN) of the service.
serviceNamestringThe name of the service.
stackStackThe stack in which this resource is defined.
taskDefinitionTaskDefinitionThe task definition to use for tasks in the service.
cloudMapService?IServiceThe CloudMap service created for this service, if any.

cluster

Type: ICluster

The cluster that hosts the service.


connections

Type: Connections

The security groups which manage the allowed network traffic for the service.


env

Type: ResourceEnvironment

The environment this resource belongs to.

For resources that are created and managed by the CDK (generally, those created by creating new class instances like Role, Bucket, etc.), this is always the same as the environment of the stack they belong to; however, for imported resources (those obtained from static methods like fromRoleArn, fromBucketName, etc.), that might be different than the stack they were imported into.


node

Type: Node

The tree node.


serviceArn

Type: string

The Amazon Resource Name (ARN) of the service.


serviceName

Type: string

The name of the service.


stack

Type: Stack

The stack in which this resource is defined.


taskDefinition

Type: TaskDefinition

The task definition to use for tasks in the service.


cloudMapService?

Type: IService (optional)

The CloudMap service created for this service, if any.

Methods

NameDescription
addPlacementConstraints(...constraints)Adds one or more placement constraints to use for tasks in the service.
addPlacementStrategies(...strategies)Adds one or more placement strategies to use for tasks in the service.
applyRemovalPolicy(policy)Apply the given removal policy to this resource.
associateCloudMapService(options)Associates this service with a CloudMap service.
attachToApplicationTargetGroup(targetGroup)This method is called to attach this service to an Application Load Balancer.
attachToClassicLB(loadBalancer)Registers the service as a target of a Classic Load Balancer (CLB).
attachToNetworkTargetGroup(targetGroup)This method is called to attach this service to a Network Load Balancer.
autoScaleTaskCount(props)An attribute representing the minimum and maximum task count for an AutoScalingGroup.
enableCloudMap(options)Enable CloudMap service discovery for the service.
enableDeploymentAlarms(alarmNames, options?)Enable Deployment Alarms which take advantage of arbitrary alarms and configure them after service initialization.
enableServiceConnect(config?)Enable Service Connect on this service.
loadBalancerTarget(options)Return a load balancing target for a specific container and port.
metric(metricName, props?)This method returns the specified CloudWatch metric name for this service.
metricCpuUtilization(props?)This method returns the CloudWatch metric for this service's CPU utilization.
metricMemoryUtilization(props?)This method returns the CloudWatch metric for this service's memory utilization.
registerLoadBalancerTargets(...targets)Use this function to create all load balancer targets to be registered in this service, add them to target groups, and attach target groups to listeners accordingly.
toString()Returns a string representation of this construct.
static fromEc2ServiceArn(scope, id, ec2ServiceArn)Imports from the specified service ARN.
static fromEc2ServiceAttributes(scope, id, attrs)Imports from the specified service attributes.

addPlacementConstraints(...constraints)

public addPlacementConstraints(...constraints: PlacementConstraint[]): void

Parameters

  • constraints PlacementConstraint

Adds one or more placement constraints to use for tasks in the service.

For more information, see Amazon ECS Task Placement Constraints.


addPlacementStrategies(...strategies)

public addPlacementStrategies(...strategies: PlacementStrategy[]): void

Parameters

  • strategies PlacementStrategy

Adds one or more placement strategies to use for tasks in the service.

For more information, see Amazon ECS Task Placement Strategies.


applyRemovalPolicy(policy)

public applyRemovalPolicy(policy: RemovalPolicy): void

Parameters

  • policy RemovalPolicy

Apply the given removal policy to this resource.

The Removal Policy controls what happens to this resource when it stops being managed by CloudFormation, either because you've removed it from the CDK application or because you've made a change that requires the resource to be replaced.

The resource can be deleted (RemovalPolicy.DESTROY), or left in your AWS account for data recovery and cleanup later (RemovalPolicy.RETAIN).


associateCloudMapService(options)

public associateCloudMapService(options: AssociateCloudMapServiceOptions): void

Parameters

  • options AssociateCloudMapServiceOptions

Associates this service with a CloudMap service.


attachToApplicationTargetGroup(targetGroup)

public attachToApplicationTargetGroup(targetGroup: IApplicationTargetGroup): LoadBalancerTargetProps

Parameters

  • targetGroup IApplicationTargetGroup

Returns

  • LoadBalancerTargetProps

This method is called to attach this service to an Application Load Balancer.

Don't call this function directly. Instead, call listener.addTargets() to add this service to a load balancer.


attachToClassicLB(loadBalancer)

public attachToClassicLB(loadBalancer: LoadBalancer): void

Parameters

  • loadBalancer LoadBalancer

Registers the service as a target of a Classic Load Balancer (CLB).

Don't call this. Call loadBalancer.addTarget() instead.


attachToNetworkTargetGroup(targetGroup)

public attachToNetworkTargetGroup(targetGroup: INetworkTargetGroup): LoadBalancerTargetProps

Parameters

  • targetGroup INetworkTargetGroup

Returns

  • LoadBalancerTargetProps

This method is called to attach this service to a Network Load Balancer.

Don't call this function directly. Instead, call listener.addTargets() to add this service to a load balancer.


autoScaleTaskCount(props)

public autoScaleTaskCount(props: EnableScalingProps): ScalableTaskCount

Parameters

  • props EnableScalingProps

Returns

  • ScalableTaskCount

An attribute representing the minimum and maximum task count for an AutoScalingGroup.


enableCloudMap(options)

public enableCloudMap(options: CloudMapOptions): Service

Parameters

  • options CloudMapOptions

Returns

  • Service

Enable CloudMap service discovery for the service.


enableDeploymentAlarms(alarmNames, options?)

public enableDeploymentAlarms(alarmNames: string[], options?: DeploymentAlarmOptions): void

Parameters

  • alarmNames string[]
  • options DeploymentAlarmOptions

Enable Deployment Alarms which take advantage of arbitrary alarms and configure them after service initialization.

If you have already enabled deployment alarms, this function can be used to tell ECS about additional alarms that should interrupt a deployment.

New alarms specified in subsequent calls of this function will be appended to the existing list of alarms.

The same Alarm Behavior must be used on all deployment alarms. If you specify different AlarmBehavior values in multiple calls to this function, or the Alarm Behavior used here doesn't match the one used in the service constructor, an error will be thrown.

If the alarm's metric references the service, you cannot pass Alarm.alarmName here. That will cause a circular dependency between the service and its deployment alarm. See this package's README for options to alarm on service metrics, and avoid this circular dependency.


enableServiceConnect(config?)

public enableServiceConnect(config?: ServiceConnectProps): void

Parameters

  • config ServiceConnectProps

Enable Service Connect on this service.


loadBalancerTarget(options)

public loadBalancerTarget(options: LoadBalancerTargetOptions): IEcsLoadBalancerTarget

Parameters

  • options LoadBalancerTargetOptions

Returns

  • IEcsLoadBalancerTarget

Return a load balancing target for a specific container and port.

Use this function to create a load balancer target if you want to load balance to another container than the first essential container or the first mapped port on the container.

Use the return value of this function where you would normally use a load balancer target, instead of the Service object itself. Example

declare const listener: elbv2.ApplicationListener;
declare const service: ecs.BaseService;
listener.addTargets('ECS', {
  port: 80,
  targets: [service.loadBalancerTarget({
    containerName: 'MyContainer',
    containerPort: 1234,
  })],
});

metric(metricName, props?)

public metric(metricName: string, props?: MetricOptions): Metric

Parameters

  • metricName string
  • props MetricOptions

Returns

  • Metric

This method returns the specified CloudWatch metric name for this service.


metricCpuUtilization(props?)

public metricCpuUtilization(props?: MetricOptions): Metric

Parameters

  • props MetricOptions

Returns

  • Metric

This method returns the CloudWatch metric for this service's CPU utilization.


metricMemoryUtilization(props?)

public metricMemoryUtilization(props?: MetricOptions): Metric

Parameters

  • props MetricOptions

Returns

  • Metric

This method returns the CloudWatch metric for this service's memory utilization.


registerLoadBalancerTargets(...targets)

public registerLoadBalancerTargets(...targets: EcsTarget[]): void

Parameters

  • targets EcsTarget

Use this function to create all load balancer targets to be registered in this service, add them to target groups, and attach target groups to listeners accordingly.

Alternatively, you can use listener.addTargets() to create targets and add them to target groups. Example

declare const listener: elbv2.ApplicationListener;
declare const service: ecs.BaseService;
service.registerLoadBalancerTargets(
  {
    containerName: 'web',
    containerPort: 80,
    newTargetGroupId: 'ECS',
    listener: ecs.ListenerConfig.applicationListener(listener, {
      protocol: elbv2.ApplicationProtocol.HTTPS
    }),
  },
)

toString()

public toString(): string

Returns

  • string

Returns a string representation of this construct.


static fromEc2ServiceArn(scope, id, ec2ServiceArn)

public static fromEc2ServiceArn(scope: Construct, id: string, ec2ServiceArn: string): IEc2Service

Parameters

  • scope Construct
  • id string
  • ec2ServiceArn string

Returns

  • IEc2Service

Imports from the specified service ARN.


static fromEc2ServiceAttributes(scope, id, attrs)

public static fromEc2ServiceAttributes(scope: Construct, id: string, attrs: Ec2ServiceAttributes): IBaseService

Parameters

  • scope Construct
  • id string
  • attrs Ec2ServiceAttributes

Returns

  • IBaseService

Imports from the specified service attributes.