FargateService

class aws_cdk.aws_ecs.FargateService(scope, id, *, task_definition, assign_public_ip=None, platform_version=None, security_groups=None, vpc_subnets=None, cluster, capacity_provider_strategies=None, circuit_breaker=None, cloud_map_options=None, deployment_alarms=None, deployment_controller=None, desired_count=None, enable_ecs_managed_tags=None, enable_execute_command=None, health_check_grace_period=None, max_healthy_percent=None, min_healthy_percent=None, propagate_tags=None, service_connect_configuration=None, service_name=None, task_definition_revision=None, volume_configurations=None)

Bases: BaseService

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

Resource:

AWS::ECS::Service

ExampleMetadata:

infused

Example:

import aws_cdk.aws_cloudwatch as cw

# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
# elb_alarm: cw.Alarm


service = ecs.FargateService(self, "Service",
    cluster=cluster,
    task_definition=task_definition,
    deployment_alarms=ecs.DeploymentAlarmConfig(
        alarm_names=[elb_alarm.alarm_name],
        behavior=ecs.AlarmBehavior.ROLLBACK_ON_ALARM
    )
)

# Defining a deployment alarm after the service has been created
cpu_alarm_name = "MyCpuMetricAlarm"
cw.Alarm(self, "CPUAlarm",
    alarm_name=cpu_alarm_name,
    metric=service.metric_cpu_utilization(),
    evaluation_periods=2,
    threshold=80
)
service.enable_deployment_alarms([cpu_alarm_name],
    behavior=ecs.AlarmBehavior.FAIL_ON_ALARM
)

Constructs a new instance of the FargateService class.

Parameters:
  • scope (Construct) –

  • id (str) –

  • task_definition (TaskDefinition) – The task definition to use for tasks in the service. [disable-awslint:ref-via-interface]

  • assign_public_ip (Optional[bool]) – Specifies whether the task’s elastic network interface receives a public IP address. If true, each task will receive a public IP address. Default: false

  • platform_version (Optional[FargatePlatformVersion]) – The platform version on which to run your service. If one is not specified, the LATEST platform version is used by default. For more information, see AWS Fargate Platform Versions in the Amazon Elastic Container Service Developer Guide. Default: Latest

  • security_groups (Optional[Sequence[ISecurityGroup]]) – The security groups to associate with the service. If you do not specify a security group, a new security group is created. Default: - A new security group is created.

  • vpc_subnets (Union[SubnetSelection, Dict[str, Any], None]) – The subnets to associate with the service. Default: - Public subnets if assignPublicIp is set, otherwise the first available one of Private, Isolated, Public, in that order.

  • cluster (ICluster) – The name of the cluster that hosts the service.

  • capacity_provider_strategies (Optional[Sequence[Union[CapacityProviderStrategy, Dict[str, Any]]]]) – A list of Capacity Provider strategies used to place a service. Default: - undefined

  • circuit_breaker (Union[DeploymentCircuitBreaker, Dict[str, Any], None]) – Whether to enable the deployment circuit breaker. If this property is defined, circuit breaker will be implicitly enabled. Default: - disabled

  • cloud_map_options (Union[CloudMapOptions, Dict[str, Any], None]) – The options for configuring an Amazon ECS service to use service discovery. Default: - AWS Cloud Map service discovery is not enabled.

  • deployment_alarms (Union[DeploymentAlarmConfig, Dict[str, Any], None]) – 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. Default: - No alarms will be monitored during deployment.

  • deployment_controller (Union[DeploymentController, Dict[str, Any], None]) – Specifies which deployment controller to use for the service. For more information, see Amazon ECS Deployment Types Default: - Rolling update (ECS)

  • desired_count (Union[int, float, None]) – The desired number of instantiations of the task definition to keep running on the service. Default: - When creating the service, default is 1; when updating the service, default uses the current task number.

  • enable_ecs_managed_tags (Optional[bool]) – Specifies whether to enable Amazon ECS managed tags for the tasks within the service. For more information, see Tagging Your Amazon ECS Resources Default: false

  • enable_execute_command (Optional[bool]) – Whether to enable the ability to execute into a container. Default: - undefined

  • health_check_grace_period (Optional[Duration]) – 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. Default: - defaults to 60 seconds if at least one load balancer is in-use and it is not already set

  • max_healthy_percent (Union[int, float, None]) – 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. Default: - 100 if daemon, otherwise 200

  • min_healthy_percent (Union[int, float, None]) – 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. Default: - 0 if daemon, otherwise 50

  • propagate_tags (Optional[PropagatedTagSource]) – 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 Default: PropagatedTagSource.NONE

  • service_connect_configuration (Union[ServiceConnectProps, Dict[str, Any], None]) – Configuration for Service Connect. Default: No ports are advertised via Service Connect on this service, and the service cannot make requests to other services via Service Connect.

  • service_name (Optional[str]) – The name of the service. Default: - CloudFormation-generated name.

  • task_definition_revision (Optional[TaskDefinitionRevision]) – Revision number for the task definition or latest to use the latest active task revision. Default: - Uses the revision of the passed task definition deployed by CloudFormation

  • volume_configurations (Optional[Sequence[ServiceManagedVolume]]) – Configuration details for a volume used by the service. This allows you to specify details about the EBS volume that can be attched to ECS tasks. Default: - undefined

Methods

add_volume(volume)

Adds a volume to the Service.

Parameters:

volume (ServiceManagedVolume) –

Return type:

None

apply_removal_policy(policy)

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).

Parameters:

policy (RemovalPolicy) –

Return type:

None

associate_cloud_map_service(*, service, container=None, container_port=None)

Associates this service with a CloudMap service.

Parameters:
  • service (IService) – The cloudmap service to register with.

  • container (Optional[ContainerDefinition]) – The container to point to for a SRV record. Default: - the task definition’s default container

  • container_port (Union[int, float, None]) – The port to point to for a SRV record. Default: - the default port of the task definition’s default container

Return type:

None

attach_to_application_target_group(target_group)

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.

Parameters:

target_group (IApplicationTargetGroup) –

Return type:

LoadBalancerTargetProps

attach_to_classic_lb(load_balancer)

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

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

Parameters:

load_balancer (LoadBalancer) –

Return type:

None

attach_to_network_target_group(target_group)

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.

Parameters:

target_group (INetworkTargetGroup) –

Return type:

LoadBalancerTargetProps

auto_scale_task_count(*, max_capacity, min_capacity=None)

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

Parameters:
  • max_capacity (Union[int, float]) – Maximum capacity to scale to.

  • min_capacity (Union[int, float, None]) – Minimum capacity to scale to. Default: 1

Return type:

ScalableTaskCount

enable_cloud_map(*, cloud_map_namespace=None, container=None, container_port=None, dns_record_type=None, dns_ttl=None, failure_threshold=None, name=None)

Enable CloudMap service discovery for the service.

Parameters:
  • cloud_map_namespace (Optional[INamespace]) – The service discovery namespace for the Cloud Map service to attach to the ECS service. Default: - the defaultCloudMapNamespace associated to the cluster

  • container (Optional[ContainerDefinition]) – The container to point to for a SRV record. Default: - the task definition’s default container

  • container_port (Union[int, float, None]) – The port to point to for a SRV record. Default: - the default port of the task definition’s default container

  • dns_record_type (Optional[DnsRecordType]) – The DNS record type that you want AWS Cloud Map to create. The supported record types are A or SRV. Default: - DnsRecordType.A if TaskDefinition.networkMode = AWS_VPC, otherwise DnsRecordType.SRV

  • dns_ttl (Optional[Duration]) – The amount of time that you want DNS resolvers to cache the settings for this record. Default: Duration.minutes(1)

  • failure_threshold (Union[int, float, None]) – The number of 30-second intervals that you want Cloud Map to wait after receiving an UpdateInstanceCustomHealthStatus request before it changes the health status of a service instance. NOTE: This is used for HealthCheckCustomConfig

  • name (Optional[str]) – The name of the Cloud Map service to attach to the ECS service. Default: CloudFormation-generated name

Return type:

Service

Returns:

The created CloudMap service

enable_deployment_alarms(alarm_names, *, behavior=None)

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.

Parameters:
  • alarm_names (Sequence[str]) –

  • behavior (Optional[AlarmBehavior]) – Default rollback on alarm. Default: AlarmBehavior.ROLLBACK_ON_ALARM

Return type:

None

enable_service_connect(*, log_driver=None, namespace=None, services=None)

Enable Service Connect on this service.

Parameters:
  • log_driver (Optional[LogDriver]) – The log driver configuration to use for the Service Connect agent logs. Default: - none

  • namespace (Optional[str]) – The cloudmap namespace to register this service into. Default: the cloudmap namespace specified on the cluster.

  • services (Optional[Sequence[Union[ServiceConnectService, Dict[str, Any]]]]) – The list of Services, including a port mapping, terse client alias, and optional intermediate DNS name. This property may be left blank if the current ECS service does not need to advertise any ports via Service Connect. Default: none

Return type:

None

load_balancer_target(*, container_name, container_port=None, protocol=None)

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.

Parameters:
  • container_name (str) – The name of the container.

  • container_port (Union[int, float, None]) – The port number of the container. Only applicable when using application/network load balancers. Default: - Container port of the first added port mapping.

  • protocol (Optional[Protocol]) – The protocol used for the port mapping. Only applicable when using application load balancers. Default: Protocol.TCP

Return type:

IEcsLoadBalancerTarget

Example:

# listener: elbv2.ApplicationListener
# service: ecs.BaseService

listener.add_targets("ECS",
    port=80,
    targets=[service.load_balancer_target(
        container_name="MyContainer",
        container_port=1234
    )]
)
metric(metric_name, *, account=None, color=None, dimensions_map=None, label=None, period=None, region=None, statistic=None, unit=None)

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

Parameters:
  • metric_name (str) –

  • account (Optional[str]) – Account which this metric comes from. Default: - Deployment account.

  • color (Optional[str]) – The hex color code, prefixed with ‘#’ (e.g. ‘#00ff00’), to use when this metric is rendered on a graph. The Color class has a set of standard colors that can be used here. Default: - Automatic color

  • dimensions_map (Optional[Mapping[str, str]]) – Dimensions of the metric. Default: - No dimensions.

  • label (Optional[str]) – Label for this metric when added to a Graph in a Dashboard. You can use dynamic labels to show summary information about the entire displayed time series in the legend. For example, if you use:: [max: ${MAX}] MyMetric As the metric label, the maximum value in the visible range will be shown next to the time series name in the graph’s legend. Default: - No label

  • period (Optional[Duration]) – The period over which the specified statistic is applied. Default: Duration.minutes(5)

  • region (Optional[str]) – Region which this metric comes from. Default: - Deployment region.

  • statistic (Optional[str]) – What function to use for aggregating. Use the aws_cloudwatch.Stats helper class to construct valid input strings. Can be one of the following: - “Minimum” | “min” - “Maximum” | “max” - “Average” | “avg” - “Sum” | “sum” - “SampleCount | “n” - “pNN.NN” - “tmNN.NN” | “tm(NN.NN%:NN.NN%)” - “iqm” - “wmNN.NN” | “wm(NN.NN%:NN.NN%)” - “tcNN.NN” | “tc(NN.NN%:NN.NN%)” - “tsNN.NN” | “ts(NN.NN%:NN.NN%)” Default: Average

  • unit (Optional[Unit]) – Unit used to filter the metric stream. Only refer to datums emitted to the metric stream with the given unit and ignore all others. Only useful when datums are being emitted to the same metric stream under different units. The default is to use all matric datums in the stream, regardless of unit, which is recommended in nearly all cases. CloudWatch does not honor this property for graphs. Default: - All metric datums in the given metric stream

Return type:

Metric

metric_cpu_utilization(*, account=None, color=None, dimensions_map=None, label=None, period=None, region=None, statistic=None, unit=None)

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

Parameters:
  • account (Optional[str]) – Account which this metric comes from. Default: - Deployment account.

  • color (Optional[str]) – The hex color code, prefixed with ‘#’ (e.g. ‘#00ff00’), to use when this metric is rendered on a graph. The Color class has a set of standard colors that can be used here. Default: - Automatic color

  • dimensions_map (Optional[Mapping[str, str]]) – Dimensions of the metric. Default: - No dimensions.

  • label (Optional[str]) –

    Label for this metric when added to a Graph in a Dashboard. You can use dynamic labels to show summary information about the entire displayed time series in the legend. For example, if you use:: [max: ${MAX}] MyMetric As the metric label, the maximum value in the visible range will be shown next to the time series name in the graph’s legend. Default: - No label

  • period (Optional[Duration]) – The period over which the specified statistic is applied. Default: Duration.minutes(5)

  • region (Optional[str]) – Region which this metric comes from. Default: - Deployment region.

  • statistic (Optional[str]) – What function to use for aggregating. Use the aws_cloudwatch.Stats helper class to construct valid input strings. Can be one of the following: - “Minimum” | “min” - “Maximum” | “max” - “Average” | “avg” - “Sum” | “sum” - “SampleCount | “n” - “pNN.NN” - “tmNN.NN” | “tm(NN.NN%:NN.NN%)” - “iqm” - “wmNN.NN” | “wm(NN.NN%:NN.NN%)” - “tcNN.NN” | “tc(NN.NN%:NN.NN%)” - “tsNN.NN” | “ts(NN.NN%:NN.NN%)” Default: Average

  • unit (Optional[Unit]) – Unit used to filter the metric stream. Only refer to datums emitted to the metric stream with the given unit and ignore all others. Only useful when datums are being emitted to the same metric stream under different units. The default is to use all matric datums in the stream, regardless of unit, which is recommended in nearly all cases. CloudWatch does not honor this property for graphs. Default: - All metric datums in the given metric stream

Default:

average over 5 minutes

Return type:

Metric

metric_memory_utilization(*, account=None, color=None, dimensions_map=None, label=None, period=None, region=None, statistic=None, unit=None)

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

Parameters:
  • account (Optional[str]) – Account which this metric comes from. Default: - Deployment account.

  • color (Optional[str]) – The hex color code, prefixed with ‘#’ (e.g. ‘#00ff00’), to use when this metric is rendered on a graph. The Color class has a set of standard colors that can be used here. Default: - Automatic color

  • dimensions_map (Optional[Mapping[str, str]]) – Dimensions of the metric. Default: - No dimensions.

  • label (Optional[str]) –

    Label for this metric when added to a Graph in a Dashboard. You can use dynamic labels to show summary information about the entire displayed time series in the legend. For example, if you use:: [max: ${MAX}] MyMetric As the metric label, the maximum value in the visible range will be shown next to the time series name in the graph’s legend. Default: - No label

  • period (Optional[Duration]) – The period over which the specified statistic is applied. Default: Duration.minutes(5)

  • region (Optional[str]) – Region which this metric comes from. Default: - Deployment region.

  • statistic (Optional[str]) – What function to use for aggregating. Use the aws_cloudwatch.Stats helper class to construct valid input strings. Can be one of the following: - “Minimum” | “min” - “Maximum” | “max” - “Average” | “avg” - “Sum” | “sum” - “SampleCount | “n” - “pNN.NN” - “tmNN.NN” | “tm(NN.NN%:NN.NN%)” - “iqm” - “wmNN.NN” | “wm(NN.NN%:NN.NN%)” - “tcNN.NN” | “tc(NN.NN%:NN.NN%)” - “tsNN.NN” | “ts(NN.NN%:NN.NN%)” Default: Average

  • unit (Optional[Unit]) – Unit used to filter the metric stream. Only refer to datums emitted to the metric stream with the given unit and ignore all others. Only useful when datums are being emitted to the same metric stream under different units. The default is to use all matric datums in the stream, regardless of unit, which is recommended in nearly all cases. CloudWatch does not honor this property for graphs. Default: - All metric datums in the given metric stream

Default:

average over 5 minutes

Return type:

Metric

register_load_balancer_targets(*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.

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

Parameters:

targets (EcsTarget) –

Return type:

None

Example:

# listener: elbv2.ApplicationListener
# service: ecs.BaseService

service.register_load_balancer_targets(
    container_name="web",
    container_port=80,
    new_target_group_id="ECS",
    listener=ecs.ListenerConfig.application_listener(listener,
        protocol=elbv2.ApplicationProtocol.HTTPS
    )
)
to_string()

Returns a string representation of this construct.

Return type:

str

Attributes

cloud_map_service

The CloudMap service created for this service, if any.

cluster

The cluster that hosts the service.

connections

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

env

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

The tree node.

service_arn

The Amazon Resource Name (ARN) of the service.

service_name

The name of the service.

Attribute:

true

stack

The stack in which this resource is defined.

task_definition

The task definition to use for tasks in the service.

Static Methods

classmethod from_fargate_service_arn(scope, id, fargate_service_arn)

Imports from the specified service ARN.

Parameters:
  • scope (Construct) –

  • id (str) –

  • fargate_service_arn (str) –

Return type:

IFargateService

classmethod from_fargate_service_attributes(scope, id, *, cluster, service_arn=None, service_name=None)

Imports from the specified service attributes.

Parameters:
  • scope (Construct) –

  • id (str) –

  • cluster (ICluster) – The cluster that hosts the service.

  • service_arn (Optional[str]) – The service ARN. Default: - either this, or serviceName, is required

  • service_name (Optional[str]) – The name of the service. Default: - either this, or serviceArn, is required

Return type:

IBaseService

classmethod from_service_arn_with_cluster(scope, id, service_arn)

Import an existing ECS/Fargate Service using the service cluster format.

The format is the “new” format “arn:aws:ecs:region:aws_account_id:service/cluster-name/service-name”.

Parameters:
  • scope (Construct) –

  • id (str) –

  • service_arn (str) –

See:

https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-account-settings.html#ecs-resource-ids

Return type:

IBaseService

classmethod is_construct(x)

Checks if x is a construct.

Use this method instead of instanceof to properly detect Construct instances, even when the construct library is symlinked.

Explanation: in JavaScript, multiple copies of the constructs library on disk are seen as independent, completely different libraries. As a consequence, the class Construct in each copy of the constructs library is seen as a different class, and an instance of one class will not test as instanceof the other class. npm install will not create installations like this, but users may manually symlink construct libraries together or use a monorepo tool: in those cases, multiple copies of the constructs library can be accidentally installed, and instanceof will behave unpredictably. It is safest to avoid using instanceof, and using this type-testing method instead.

Parameters:

x (Any) – Any object.

Return type:

bool

Returns:

true if x is an object created from a class which extends Construct.

classmethod is_owned_resource(construct)

Returns true if the construct was created by CDK, and false otherwise.

Parameters:

construct (IConstruct) –

Return type:

bool

classmethod is_resource(construct)

Check whether the given construct is a Resource.

Parameters:

construct (IConstruct) –

Return type:

bool