ExternalService L2 construct
This creates a service using the External launch type on an ECS cluster.
Example
declare const cluster: ecs.Cluster;
declare const taskDefinition: ecs.TaskDefinition;
new ecs.Ec2Service(this, 'Ec2Service', {
cluster,
taskDefinition,
daemon: true,
});
new ecs.ExternalService(this, 'ExternalService', {
cluster,
taskDefinition,
daemon: true,
});
# cluster: ecs.Cluster
# task_definition: ecs.TaskDefinition
ecs.Ec2Service(self, "Ec2Service",
cluster=cluster,
task_definition=task_definition,
daemon=True
)
ecs.ExternalService(self, "ExternalService",
cluster=cluster,
task_definition=task_definition,
daemon=True
)
Cluster cluster;
TaskDefinition taskDefinition;
Ec2Service.Builder.create(this, "Ec2Service")
.cluster(cluster)
.taskDefinition(taskDefinition)
.daemon(true)
.build();
ExternalService.Builder.create(this, "ExternalService")
.cluster(cluster)
.taskDefinition(taskDefinition)
.daemon(true)
.build();
// Install: dotnet add package Amazon.CDK.Lib
Cluster cluster;
TaskDefinition taskDefinition;
new Ec2Service(this, "Ec2Service", new Ec2ServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
Daemon = true
});
new ExternalService(this, "ExternalService", new ExternalServiceProps {
Cluster = cluster,
TaskDefinition = taskDefinition,
Daemon = true
});
// Install: go get github.com/aws/aws-cdk-go/awscdk/v2
var cluster Cluster
var taskDefinition TaskDefinition
ecs.NewEc2Service(this, jsii.String("Ec2Service"), &Ec2ServiceProps{
Cluster: Cluster,
TaskDefinition: TaskDefinition,
Daemon: jsii.Boolean(true),
})
ecs.NewExternalService(this, jsii.String("ExternalService"), &ExternalServiceProps{
Cluster: Cluster,
TaskDefinition: TaskDefinition,
Daemon: jsii.Boolean(true),
})
Initializer
new ExternalService(scope: Construct, id: string, props: ExternalServiceProps)
ExternalService(scope: Construct, id: str, props: ExternalServiceProps)
new ExternalService(Construct scope, String id, ExternalServiceProps props)
new ExternalService(Construct scope, string id, ExternalServiceProps props)
NewExternalService(Scope Construct, Id *string, Props ExternalServiceProps)
Construct Props
canaryConfigurationTrafficShiftConfigcanary_configurationTrafficShiftConfigcanaryConfigurationTrafficShiftConfigCanaryConfigurationTrafficShiftConfigCanaryConfigurationTrafficShiftConfig= no canary configuration#Only valid when deploymentStrategy is set to CANARY.
capacityProviderStrategiesCapacityProviderStrategy[]capacity_provider_strategiestyping.List[CapacityProviderStrategy]capacityProviderStrategiesList<CapacityProviderStrategy>CapacityProviderStrategiesCapacityProviderStrategy[]CapacityProviderStrategies*[]CapacityProviderStrategy= undefined#circuitBreakerDeploymentCircuitBreakercircuit_breakerDeploymentCircuitBreakercircuitBreakerDeploymentCircuitBreakerCircuitBreakerDeploymentCircuitBreakerCircuitBreakerDeploymentCircuitBreaker= disabled#If this property is defined, circuit breaker will be implicitly enabled.
cloudMapOptionsCloudMapOptionscloud_map_optionsCloudMapOptionscloudMapOptionsCloudMapOptionsCloudMapOptionsCloudMapOptionsCloudMapOptionsCloudMapOptions= AWS Cloud Map service discovery …#default
Default: AWS Cloud Map service discovery is not enabled.
notes
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 or any task placement strategies. Tasks using the Fargate launch type or the CODE_DEPLOY or EXTERNAL deployment controller types don't support the DAEMON scheduling strategy.
deploymentAlarmsDeploymentAlarmConfigdeployment_alarmsDeploymentAlarmConfigdeploymentAlarmsDeploymentAlarmConfigDeploymentAlarmsDeploymentAlarmConfigDeploymentAlarmsDeploymentAlarmConfig= No alarms will be monitored duri…#default
Default: No alarms will be monitored during deployment.
deploymentControllerDeploymentControllerdeployment_controllerDeploymentControllerdeploymentControllerDeploymentControllerDeploymentControllerDeploymentControllerDeploymentControllerDeploymentController= Rolling update (ECS)#For more information, see Amazon ECS Deployment Types
deploymentStrategyDeploymentStrategydeployment_strategyDeploymentStrategydeploymentStrategyDeploymentStrategyDeploymentStrategyDeploymentStrategyDeploymentStrategyDeploymentStrategy= ROLLING#desiredCountnumberdesired_countint | floatdesiredCountNumberDesiredCountdoubleDesiredCount*float64= When creating the service, defau…#default
Default: When creating the service, default is 1; when updating the service, default uses the current task number.
enableECSManagedTagsbooleanenable_ecs_managed_tagsboolenableECSManagedTagsBooleanEnableECSManagedTagsboolEnableECSManagedTags*bool= false#For more information, see Tagging Your Amazon ECS Resources
enableExecuteCommandbooleanenable_execute_commandboolenableExecuteCommandBooleanEnableExecuteCommandboolEnableExecuteCommand*bool= undefined#forceNewDeploymentForceNewDeploymentforce_new_deploymentForceNewDeploymentforceNewDeploymentForceNewDeploymentForceNewDeploymentForceNewDeploymentForceNewDeploymentForceNewDeployment= no forced deployment#notes
By default, deployments aren't forced. You can use this option to start a new deployment with no service definition changes. For example, you can update a service's tasks to use a newer Docker image with the same image/tag combination (my_image:latest) or to roll Fargate tasks onto a newer platform version.
This is equivalent to calling the forceNewDeployment() method, but allows you to configure it declaratively at construction time, including the ability to explicitly disable it with enabled: false.
healthCheckGracePeriodDurationhealth_check_grace_periodDurationhealthCheckGracePeriodDurationHealthCheckGracePeriodDurationHealthCheckGracePeriodDuration= defaults to 60 seconds if at lea…#default
Default: defaults to 60 seconds if at least one load balancer is in-use and it is not already set
lifecycleHooksIDeploymentLifecycleHookTarget[]lifecycle_hookstyping.List[IDeploymentLifecycleHookTarget]lifecycleHooksList<IDeploymentLifecycleHookTarget>LifecycleHooksIDeploymentLifecycleHookTarget[]LifecycleHooks*[]IDeploymentLifecycleHookTarget= none;#linearConfigurationTrafficShiftConfiglinear_configurationTrafficShiftConfiglinearConfigurationTrafficShiftConfigLinearConfigurationTrafficShiftConfigLinearConfigurationTrafficShiftConfig= no linear configuration#Only valid when deploymentStrategy is set to LINEAR.
maxHealthyPercentnumbermax_healthy_percentint | floatmaxHealthyPercentNumberMaxHealthyPercentdoubleMaxHealthyPercent*float64= 100 if daemon, otherwise 200#minHealthyPercentnumbermin_healthy_percentint | floatminHealthyPercentNumberMinHealthyPercentdoubleMinHealthyPercent*float64= 0 if daemon, otherwise 50#propagateTagsPropagatedTagSourcepropagate_tagsPropagatedTagSourcepropagateTagsPropagatedTagSourcePropagateTagsPropagatedTagSourcePropagateTagsPropagatedTagSource= PropagatedTagSource.NONE#Valid values are: PropagatedTagSource.SERVICE, PropagatedTagSource.TASK_DEFINITION or PropagatedTagSource.NONE
securityGroupsISecurityGroup[]security_groupstyping.List[ISecurityGroup]securityGroupsList<ISecurityGroup>SecurityGroupsISecurityGroup[]SecurityGroups*[]ISecurityGroup= A new security group is created.#If you do not specify a security group, a new security group is created.
serviceConnectConfigurationServiceConnectPropsservice_connect_configurationServiceConnectPropsserviceConnectConfigurationServiceConnectPropsServiceConnectConfigurationServiceConnectPropsServiceConnectConfigurationServiceConnectProps= No ports are advertised via Serv…#default
Default: No ports are advertised via Service Connect on this service, and the service cannot make requests to other services via Service Connect.
serviceNamestringservice_namestrserviceNameStringServiceNamestringServiceName*string= CloudFormation-generated name.#taskDefinitionTaskDefinitiontask_definitionTaskDefinitiontaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionrequired#[disable-awslint:ref-via-interface]
taskDefinitionRevisionTaskDefinitionRevisiontask_definition_revisionTaskDefinitionRevisiontaskDefinitionRevisionTaskDefinitionRevisionTaskDefinitionRevisionTaskDefinitionRevisionTaskDefinitionRevisionTaskDefinitionRevision= Uses the revision of the passed …#default
Default: Uses the revision of the passed task definition deployed by CloudFormation
volumeConfigurationsServiceManagedVolume[]volume_configurationstyping.List[ServiceManagedVolume]volumeConfigurationsList<ServiceManagedVolume>VolumeConfigurationsServiceManagedVolume[]VolumeConfigurations*[]ServiceManagedVolume= undefined#This allows you to specify details about the EBS volume that can be attached to ECS tasks.
Properties
cloudMapServiceIServicecloud_map_serviceIServicecloudMapServiceIServiceCloudMapServiceIServiceCloudMapServiceIService#connectionsConnectionsconnectionsConnectionsconnectionsConnectionsConnectionsConnectionsConnectionsConnectionsrequired#envResourceEnvironmentenvResourceEnvironmentenvResourceEnvironmentEnvResourceEnvironmentEnvResourceEnvironmentrequired#notes
For resources that are created and managed in a Stack (those created by creating new class instances like new Role(), new Bucket(), etc.), this is always the same as the environment of the stack they belong to.
For referenced resources (those obtained from referencing methods like Role.fromRoleArn(), Bucket.fromBucketName(), etc.), they might be different than the stack they were imported into.
loadBalancersCfnService.LoadBalancerProperty[]load_balancerstyping.List[LoadBalancerProperty]loadBalancersList<LoadBalancerProperty>LoadBalancersLoadBalancerProperty[]LoadBalancers*[]LoadBalancerPropertyrequired#PROPERTY_INJECTION_IDstringproperty_injection_idstrPROPERTY_INJECTION_IDStringPROPERTY_INJECTION_IDstringPROPERTY_INJECTION_ID*stringrequiredstatic#serviceRefServiceReferenceservice_refServiceReferenceserviceRefServiceReferenceServiceRefServiceReferenceServiceRefServiceReferencerequired#taskDefinitionTaskDefinitiontask_definitionTaskDefinitiontaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionTaskDefinitionrequired#Methods
addLifecycleHook(target: IDeploymentLifecycleHookTarget): voiddef add_lifecycle_hook(self, target: IDeploymentLifecycleHookTarget) -> Nonepublic void addLifecycleHook(IDeploymentLifecycleHookTarget target)public void AddLifecycleHook(IDeploymentLifecycleHookTarget target)func AddLifecycleHook(Target IDeploymentLifecycleHookTarget)#1 parameter
Parameters
targettargettargettargetTarget— The lifecycle hook target to add.
addVolume(volume: ServiceManagedVolume): voiddef add_volume(self, volume: ServiceManagedVolume) -> Nonepublic void addVolume(ServiceManagedVolume volume)public void AddVolume(ServiceManagedVolume volume)func AddVolume(Volume ServiceManagedVolume)#applyCrossStackReferenceStrength(strength: ReferenceStrength): voiddef apply_cross_stack_reference_strength(self, strength: ReferenceStrength) -> Nonepublic void applyCrossStackReferenceStrength(ReferenceStrength strength)public void ApplyCrossStackReferenceStrength(ReferenceStrength strength)func ApplyCrossStackReferenceStrength(Strength ReferenceStrength)#notes · 1 parameter
When set, any cross-stack reference to this resource will use the specified mechanism instead of the global default determined by the @aws-cdk/core:defaultCrossStackReferences context key. This is useful for selectively weakening specific references to avoid the "deadly embrace" problem without changing the app-wide default.
Parameters
strengthstrengthstrengthstrengthStrength— - The reference strength to use for this resource.
applyRemovalPolicy(policy: RemovalPolicy): voiddef apply_removal_policy(self, policy: RemovalPolicy) -> Nonepublic void applyRemovalPolicy(RemovalPolicy policy)public void ApplyRemovalPolicy(RemovalPolicy policy)func ApplyRemovalPolicy(Policy RemovalPolicy)#notes
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: AssociateCloudMapServiceOptions): voiddef associate_cloud_map_service(self, _options: AssociateCloudMapServiceOptions) -> Nonepublic void associateCloudMapService(AssociateCloudMapServiceOptions _options)public void AssociateCloudMapService(AssociateCloudMapServiceOptions _options)func AssociateCloudMapService(_options AssociateCloudMapServiceOptions)#attachToApplicationTargetGroup(_targetGroup: IApplicationTargetGroup): LoadBalancerTargetPropsdef attach_to_application_target_group(self, _target_group: IApplicationTargetGroup) -> LoadBalancerTargetPropspublic LoadBalancerTargetProps attachToApplicationTargetGroup(IApplicationTargetGroup _targetGroup)public LoadBalancerTargetProps AttachToApplicationTargetGroup(IApplicationTargetGroup _targetGroup)func AttachToApplicationTargetGroup(_targetGroup IApplicationTargetGroup) LoadBalancerTargetProps#attachToClassicLB(loadBalancer: LoadBalancer): voiddef attach_to_classic_lb(self, load_balancer: LoadBalancer) -> Nonepublic void attachToClassicLB(LoadBalancer loadBalancer)public void AttachToClassicLB(LoadBalancer loadBalancer)func AttachToClassicLB(LoadBalancer LoadBalancer)#Don't call this. Call loadBalancer.addTarget() instead.
1 parameter
Parameters
loadBalancerload_balancerloadBalancerloadBalancerLoadBalancer— [disable-awslint:ref-via-interface].
attachToNetworkTargetGroup(targetGroup: INetworkTargetGroup): LoadBalancerTargetPropsdef attach_to_network_target_group(self, target_group: INetworkTargetGroup) -> LoadBalancerTargetPropspublic LoadBalancerTargetProps attachToNetworkTargetGroup(INetworkTargetGroup targetGroup)public LoadBalancerTargetProps AttachToNetworkTargetGroup(INetworkTargetGroup targetGroup)func AttachToNetworkTargetGroup(TargetGroup INetworkTargetGroup) LoadBalancerTargetProps#Don't call this function directly. Instead, call listener.addTargets() to add this service to a load balancer.
autoScaleTaskCount(_props: EnableScalingProps): ScalableTaskCountdef auto_scale_task_count(self, _props: EnableScalingProps) -> ScalableTaskCountpublic ScalableTaskCount autoScaleTaskCount(EnableScalingProps _props)public ScalableTaskCount AutoScaleTaskCount(EnableScalingProps _props)func AutoScaleTaskCount(_props EnableScalingProps) ScalableTaskCount#enableCloudMap(_options: CloudMapOptions): Servicedef enable_cloud_map(self, _options: CloudMapOptions) -> Servicepublic Service enableCloudMap(CloudMapOptions _options)public Service EnableCloudMap(CloudMapOptions _options)func EnableCloudMap(_options CloudMapOptions) Service#enableDeploymentAlarms(alarmNames: string[], options?: DeploymentAlarmOptions): voiddef enable_deployment_alarms(self, alarm_names: typing.List[str], options: typing.Optional[DeploymentAlarmOptions] = None) -> Nonepublic void enableDeploymentAlarms(List<String> alarmNames, DeploymentAlarmOptions options)public void EnableDeploymentAlarms(string[] alarmNames, DeploymentAlarmOptions? options = null)func EnableDeploymentAlarms(AlarmNames *[]*string, Options DeploymentAlarmOptions)#notes
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?: ServiceConnectProps): voiddef enable_service_connect(self, config: typing.Optional[ServiceConnectProps] = None) -> Nonepublic void enableServiceConnect(ServiceConnectProps config)public void EnableServiceConnect(ServiceConnectProps? config = null)func EnableServiceConnect(Config ServiceConnectProps)#forceNewDeployment(nonce?: string): voiddef force_new_deployment(self, nonce: typing.Optional[str] = None) -> Nonepublic void forceNewDeployment(String nonce)public void ForceNewDeployment(string? nonce = null)func ForceNewDeployment(Nonce *string)#notes · 1 parameter
This can be used to trigger a deployment without changing the task definition or desired count. ECS will start a new deployment even if there are no changes to the service configuration.
Important: When called without a nonce, a timestamp is generated automatically, which means every cdk synth produces a different template and every cdk deploy triggers a new deployment regardless of whether any code has changed. To avoid this, provide a stable nonce value that only changes when you intentionally want to force a redeployment (e.g., an image digest or a version string).
Parameters
noncenoncenoncenonceNonce— - A unique string (1-255 characters) that signals ECS to start a new deployment.
fromExternalServiceArn(scope: Construct, id: string, externalServiceArn: string): IExternalService@staticmethod def from_external_service_arn(scope: Construct, id: str, external_service_arn: str) -> IExternalServicepublic static IExternalService fromExternalServiceArn(Construct scope, String id, String externalServiceArn)public static IExternalService FromExternalServiceArn(Construct scope, string id, string externalServiceArn)func FromExternalServiceArn(Scope Construct, Id *string, ExternalServiceArn *string) IExternalServicestatic#fromExternalServiceAttributes(scope: Construct, id: string, attrs: ExternalServiceAttributes): IBaseService@staticmethod def from_external_service_attributes(scope: Construct, id: str, attrs: ExternalServiceAttributes) -> IBaseServicepublic static IBaseService fromExternalServiceAttributes(Construct scope, String id, ExternalServiceAttributes attrs)public static IBaseService FromExternalServiceAttributes(Construct scope, string id, ExternalServiceAttributes attrs)func FromExternalServiceAttributes(Scope Construct, Id *string, Attrs ExternalServiceAttributes) IBaseServicestatic#fromServiceArnWithCluster(scope: Construct, id: string, serviceArn: string): IBaseService@staticmethod def from_service_arn_with_cluster(scope: Construct, id: str, service_arn: str) -> IBaseServicepublic static IBaseService fromServiceArnWithCluster(Construct scope, String id, String serviceArn)public static IBaseService FromServiceArnWithCluster(Construct scope, string id, string serviceArn)func FromServiceArnWithCluster(Scope Construct, Id *string, ServiceArn *string) IBaseServicestatic#The format is the "new" format "arn:aws:ecs:region:aws_account_id:service/cluster-name/service-name".
isConstruct(x: any): boolean@staticmethod def is_construct(x: Any) -> boolpublic static Boolean isConstruct(Object x)public static bool IsConstruct(object x)func IsConstruct(X interface{}) *boolstatic#notes · 1 parameter · returns
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
xxxxX— Any object.
Returns: true if x is an object created from a class which extends Construct.
isOwnedResource(construct: IConstruct): boolean@staticmethod def is_owned_resource(construct: IConstruct) -> boolpublic static Boolean isOwnedResource(IConstruct construct)public static bool IsOwnedResource(IConstruct construct)func IsOwnedResource(Construct IConstruct) *boolstatic#isResource(construct: IConstruct): boolean@staticmethod def is_resource(construct: IConstruct) -> boolpublic static Boolean isResource(IConstruct construct)public static bool IsResource(IConstruct construct)func IsResource(Construct IConstruct) *boolstatic#isUsingECSDeploymentController(): booleandef is_using_ecs_deployment_controller(self, ) -> boolpublic Boolean isUsingECSDeploymentController()public bool IsUsingECSDeploymentController()func IsUsingECSDeploymentController() *bool#returns
Returns: true if the service is using the ECS deployment controller or if no deployment controller is specified (defaults to ECS)
loadBalancerTarget(_options: LoadBalancerTargetOptions): IEcsLoadBalancerTargetdef load_balancer_target(self, _options: LoadBalancerTargetOptions) -> IEcsLoadBalancerTargetpublic IEcsLoadBalancerTarget loadBalancerTarget(LoadBalancerTargetOptions _options)public IEcsLoadBalancerTarget LoadBalancerTarget(LoadBalancerTargetOptions _options)func LoadBalancerTarget(_options LoadBalancerTargetOptions) IEcsLoadBalancerTarget#metric(metricName: string, props?: MetricOptions): Metricdef metric(self, metric_name: str, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metric(String metricName, MetricOptions props)public Metric Metric(string metricName, MetricOptions? props = null)func Metric(MetricName *string, Props MetricOptions) Metric#metricCpuUtilization(props?: MetricOptions): Metricdef metric_cpu_utilization(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricCpuUtilization(MetricOptions props)public Metric MetricCpuUtilization(MetricOptions? props = null)func MetricCpuUtilization(Props MetricOptions) Metric#metricMemoryUtilization(props?: MetricOptions): Metricdef metric_memory_utilization(self, props: typing.Optional[MetricOptions] = None) -> Metricpublic Metric metricMemoryUtilization(MetricOptions props)public Metric MetricMemoryUtilization(MetricOptions? props = null)func MetricMemoryUtilization(Props MetricOptions) Metric#registerLoadBalancerTargets(..._targets: EcsTarget[]): voiddef register_load_balancer_targets(self, _targets: EcsTarget) -> Nonepublic void registerLoadBalancerTargets(EcsTarget _targets)public void RegisterLoadBalancerTargets(EcsTarget _targets)func RegisterLoadBalancerTargets(_targets EcsTarget)#toString(): stringdef to_string(self, ) -> strpublic String toString()public string ToString()func ToString() *string#with(...mixins: IMixin[]): IConstructdef with(self, mixins: IMixin) -> IConstructpublic IConstruct with(IMixin mixins)public IConstruct With(IMixin mixins)func With(Mixins IMixin) IConstruct#Mixins are applied in order. The list of constructs is captured at the start of the call, so constructs added by a mixin will not be visited. Use multiple with() calls if subsequent mixins should apply to added constructs.