BaseService L2 construct
The base class for Ec2Service and FargateService services.
Example
import * as ecs from 'aws-cdk-lib/aws-ecs';
const service = ecs.BaseService.fromServiceArnWithCluster(this, 'EcsService',
'arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName'
);
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const buildOutput = new codepipeline.Artifact();
// add source and build stages to the pipeline as usual...
const deployStage = pipeline.addStage({
stageName: 'Deploy',
actions: [
new codepipeline_actions.EcsDeployAction({
actionName: 'DeployAction',
service: service,
input: buildOutput,
}),
],
});
Initializer
new BaseService(scope: Construct, id: string, props: BaseServiceProps, additionalProps: any, taskDefinition: TaskDefinition)
BaseService(scope: Construct, id: str, props: BaseServiceProps, additional_props: Any, task_definition: TaskDefinition)
new BaseService(Construct scope, String id, BaseServiceProps props, Object additionalProps, TaskDefinition taskDefinition)
new BaseService(Construct scope, string id, BaseServiceProps props, object additionalProps, TaskDefinition taskDefinition)
NewBaseService(Scope Construct, Id *string, Props BaseServiceProps, AdditionalProps interface{}, TaskDefinition TaskDefinition)
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.
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
launchTypeLaunchTypelaunch_typeLaunchTypelaunchTypeLaunchTypeLaunchTypeLaunchTypeLaunchTypeLaunchTyperequired#LaunchType will be omitted if capacity provider strategies are specified on the service.
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
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.#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#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#Don't call this function directly. Instead, call listener.addTargets() to add this service to a load balancer.
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#returns
Returns: The created CloudMap 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.
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#notes · example
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.
declare const listener: elbv2.ApplicationListener;
declare const service: ecs.BaseService;
listener.addTargets('ECS', {
port: 80,
targets: [service.loadBalancerTarget({
containerName: 'MyContainer',
containerPort: 1234,
})],
});
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)#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(): 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.