aws-cdk-lib
Version:
Version 2 of the AWS Cloud Development Kit library
2 lines (1 loc) • 29.6 kB
JavaScript
"use strict";var __decorate=exports&&exports.__decorate||function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r},_a,_b;Object.defineProperty(exports,"__esModule",{value:!0}),exports.AsgCapacityProvider=exports.ExecuteCommandLogging=exports.ContainerInsights=exports.Cluster=exports.MachineImageType=void 0;var jsiiDeprecationWarnings=()=>{var tmp=require("../../.warnings.jsii.js");return jsiiDeprecationWarnings=()=>tmp,tmp};const JSII_RTTI_SYMBOL_1=Symbol.for("jsii.rtti");var constructs_1=()=>{var tmp=require("constructs");return constructs_1=()=>tmp,tmp},amis_1=()=>{var tmp=require("./amis");return amis_1=()=>tmp,tmp},instance_drain_hook_1=()=>{var tmp=require("./drain-hook/instance-drain-hook");return instance_drain_hook_1=()=>tmp,tmp},ecs_canned_metrics_generated_1=()=>{var tmp=require("./ecs-canned-metrics.generated");return ecs_canned_metrics_generated_1=()=>tmp,tmp},ecs_generated_1=()=>{var tmp=require("./ecs.generated");return ecs_generated_1=()=>tmp,tmp},autoscaling=()=>{var tmp=require("../../aws-autoscaling");return autoscaling=()=>tmp,tmp},cloudwatch=()=>{var tmp=require("../../aws-cloudwatch");return cloudwatch=()=>tmp,tmp},ec2=()=>{var tmp=require("../../aws-ec2");return ec2=()=>tmp,tmp},iam=()=>{var tmp=require("../../aws-iam");return iam=()=>tmp,tmp},aws_iam_1=()=>{var tmp=require("../../aws-iam");return aws_iam_1=()=>tmp,tmp},cloudmap=()=>{var tmp=require("../../aws-servicediscovery");return cloudmap=()=>tmp,tmp},core_1=()=>{var tmp=require("../../core");return core_1=()=>tmp,tmp},metadata_resource_1=()=>{var tmp=require("../../core/lib/metadata-resource");return metadata_resource_1=()=>tmp,tmp},cx_api_1=()=>{var tmp=require("../../cx-api");return cx_api_1=()=>tmp,tmp};const CLUSTER_SYMBOL=Symbol.for("@aws-cdk/aws-ecs/lib/cluster.Cluster");var MachineImageType;(function(MachineImageType2){MachineImageType2[MachineImageType2.AMAZON_LINUX_2=0]="AMAZON_LINUX_2",MachineImageType2[MachineImageType2.BOTTLEROCKET=1]="BOTTLEROCKET"})(MachineImageType||(exports.MachineImageType=MachineImageType={}));const getCanContainersAccessInstanceRoleDefault=(canContainersAccessInstanceRole,disableEcsImdsBlockingFlag)=>canContainersAccessInstanceRole!==void 0?canContainersAccessInstanceRole:disableEcsImdsBlockingFlag===!0;class Cluster extends core_1().Resource{static isCluster(x){return x!==null&&typeof x=="object"&&CLUSTER_SYMBOL in x}static fromClusterAttributes(scope,id,attrs){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_ecs_ClusterAttributes(attrs)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.fromClusterAttributes),error}return new ImportedCluster(scope,id,attrs)}static fromClusterArn(scope,id,clusterArn){const clusterName=core_1().Stack.of(scope).splitArn(clusterArn,core_1().ArnFormat.SLASH_RESOURCE_NAME).resourceName;if(!clusterName)throw new Error(`Missing required Cluster Name from Cluster ARN: ${clusterArn}`);const errorSuffix="is not available for a Cluster imported using fromClusterArn(), please use fromClusterAttributes() instead.";class Import extends core_1().Resource{constructor(){super(...arguments),this.clusterArn=clusterArn,this.clusterName=clusterName}get hasEc2Capacity(){throw new Error(`hasEc2Capacity ${errorSuffix}`)}get connections(){throw new Error(`connections ${errorSuffix}`)}get vpc(){throw new Error(`vpc ${errorSuffix}`)}}return new Import(scope,id,{environmentFromArn:clusterArn})}constructor(scope,id,props={}){super(scope,id,{physicalName:props.clusterName}),this.connections=new(ec2()).Connections,this._capacityProviderNames=[],this._defaultCapacityProviderStrategy=[],this._hasEc2Capacity=!1;try{jsiiDeprecationWarnings().aws_cdk_lib_aws_ecs_ClusterProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,Cluster),error}if((0,metadata_resource_1().addConstructMetadata)(this,props),props.containerInsights!==void 0&&props.containerInsightsV2)throw new Error("You cannot set both containerInsights and containerInsightsV2");let clusterSettings;if(props.containerInsights!==void 0?clusterSettings=[{name:"containerInsights",value:props.containerInsights?ContainerInsights.ENABLED:ContainerInsights.DISABLED}]:props.containerInsightsV2!==void 0&&(clusterSettings=[{name:"containerInsights",value:props.containerInsightsV2}]),this._capacityProviderNames=props.capacityProviders??[],props.enableFargateCapacityProviders&&this.enableFargateCapacityProviders(),props.executeCommandConfiguration){if(props.executeCommandConfiguration.logging===ExecuteCommandLogging.OVERRIDE!=(props.executeCommandConfiguration.logConfiguration!==void 0))throw new Error("Execute command log configuration must only be specified when logging is OVERRIDE.");this._executeCommandConfiguration=props.executeCommandConfiguration}this._managedStorageConfiguration=props.managedStorageConfiguration,this._cfnCluster=new(ecs_generated_1()).CfnCluster(this,"Resource",{clusterName:this.physicalName,clusterSettings,configuration:this.renderClusterConfiguration()}),this.clusterArn=this.getResourceArnAttribute(this._cfnCluster.attrArn,{service:"ecs",resource:"cluster",resourceName:this.physicalName}),this.clusterName=this.getResourceNameAttribute(this._cfnCluster.ref),this.vpc=props.vpc||new(ec2()).Vpc(this,"Vpc",{maxAzs:2}),this._defaultCloudMapNamespace=props.defaultCloudMapNamespace!==void 0?this.addDefaultCloudMapNamespace(props.defaultCloudMapNamespace):void 0,this._autoscalingGroup=props.capacity!==void 0?this.addCapacity("DefaultAutoScalingGroup",props.capacity):void 0,this.updateKeyPolicyForEphemeralStorageConfiguration(props.clusterName),core_1().Aspects.of(this).add(new MaybeCreateCapacityProviderAssociations(this,id),{priority:core_1().AspectPriority.MUTATING})}updateKeyPolicyForEphemeralStorageConfiguration(clusterName){const key=this._managedStorageConfiguration?.fargateEphemeralStorageKmsKey;if(!key)return;const clusterConditions={StringEquals:{"kms:EncryptionContext:aws:ecs:clusterAccount":[core_1().Aws.ACCOUNT_ID],...clusterName&&{"kms:EncryptionContext:aws:ecs:clusterName":[clusterName]}}};key.addToResourcePolicy(new(aws_iam_1()).PolicyStatement({sid:"Allow generate data key access for Fargate tasks.",principals:[new(aws_iam_1()).ServicePrincipal("fargate.amazonaws.com")],resources:["*"],actions:["kms:GenerateDataKeyWithoutPlaintext"],conditions:clusterConditions})),key.addToResourcePolicy(new(aws_iam_1()).PolicyStatement({sid:"Allow grant creation permission for Fargate tasks.",principals:[new(aws_iam_1()).ServicePrincipal("fargate.amazonaws.com")],resources:["*"],actions:["kms:CreateGrant"],conditions:{...clusterConditions,"ForAllValues:StringEquals":{"kms:GrantOperations":["Decrypt"]}}}))}enableFargateCapacityProviders(){for(const provider of["FARGATE","FARGATE_SPOT"])this._capacityProviderNames.includes(provider)||this._capacityProviderNames.push(provider)}addDefaultCapacityProviderStrategy(defaultCapacityProviderStrategy){if(this._defaultCapacityProviderStrategy.length>0)throw new Error("Cluster default capacity provider strategy is already set.");if(defaultCapacityProviderStrategy.some(dcp=>dcp.capacityProvider.includes("FARGATE"))&&defaultCapacityProviderStrategy.some(dcp=>!dcp.capacityProvider.includes("FARGATE")))throw new Error("A capacity provider strategy cannot contain a mix of capacity providers using Auto Scaling groups and Fargate providers. Specify one or the other and try again.");if(defaultCapacityProviderStrategy.forEach(dcp=>{if(!this._capacityProviderNames.includes(dcp.capacityProvider))throw new Error(`Capacity provider ${dcp.capacityProvider} must be added to the cluster with addAsgCapacityProvider() before it can be used in a default capacity provider strategy.`)}),defaultCapacityProviderStrategy.filter(dcp=>!!dcp.base).length>1)throw new Error("Only 1 capacity provider in a capacity provider strategy can have a nonzero base.");this._defaultCapacityProviderStrategy=defaultCapacityProviderStrategy}renderClusterConfiguration(){if(!(!this._executeCommandConfiguration&&!this._managedStorageConfiguration))return{executeCommandConfiguration:this._executeCommandConfiguration&&{kmsKeyId:this._executeCommandConfiguration.kmsKey?.keyArn,logConfiguration:this._executeCommandConfiguration.logConfiguration&&this.renderExecuteCommandLogConfiguration(),logging:this._executeCommandConfiguration.logging},managedStorageConfiguration:this._managedStorageConfiguration&&{fargateEphemeralStorageKmsKeyId:this._managedStorageConfiguration.fargateEphemeralStorageKmsKey?.keyId,kmsKeyId:this._managedStorageConfiguration.kmsKey?.keyId}}}renderExecuteCommandLogConfiguration(){const logConfiguration=this._executeCommandConfiguration?.logConfiguration;if(logConfiguration?.s3EncryptionEnabled&&!logConfiguration?.s3Bucket)throw new Error("You must specify an S3 bucket name in the execute command log configuration to enable S3 encryption.");if(logConfiguration?.cloudWatchEncryptionEnabled&&!logConfiguration?.cloudWatchLogGroup)throw new Error("You must specify a CloudWatch log group in the execute command log configuration to enable CloudWatch encryption.");return{cloudWatchEncryptionEnabled:logConfiguration?.cloudWatchEncryptionEnabled,cloudWatchLogGroupName:logConfiguration?.cloudWatchLogGroup?.logGroupName,s3BucketName:logConfiguration?.s3Bucket?.bucketName,s3EncryptionEnabled:logConfiguration?.s3EncryptionEnabled,s3KeyPrefix:logConfiguration?.s3KeyPrefix}}addDefaultCloudMapNamespace(options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_ecs_CloudMapNamespaceOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addDefaultCloudMapNamespace),error}if(this._defaultCloudMapNamespace!==void 0)throw new Error("Can only add default namespace once.");const namespaceType=options.type!==void 0?options.type:cloudmap().NamespaceType.DNS_PRIVATE;let sdNamespace;switch(namespaceType){case cloudmap().NamespaceType.DNS_PRIVATE:sdNamespace=new(cloudmap()).PrivateDnsNamespace(this,"DefaultServiceDiscoveryNamespace",{name:options.name,vpc:this.vpc});break;case cloudmap().NamespaceType.DNS_PUBLIC:sdNamespace=new(cloudmap()).PublicDnsNamespace(this,"DefaultServiceDiscoveryNamespace",{name:options.name});break;case cloudmap().NamespaceType.HTTP:sdNamespace=new(cloudmap()).HttpNamespace(this,"DefaultServiceDiscoveryNamespace",{name:options.name});break;default:throw new Error(`Namespace type ${namespaceType} is not supported.`)}return this._defaultCloudMapNamespace=sdNamespace,options.useForServiceConnect&&(this._cfnCluster.serviceConnectDefaults={namespace:sdNamespace.namespaceArn}),sdNamespace}get defaultCapacityProviderStrategy(){return this._defaultCapacityProviderStrategy}get capacityProviderNames(){return this._capacityProviderNames}get defaultCloudMapNamespace(){return this._defaultCloudMapNamespace}addCapacity(id,options){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_ecs_AddCapacityOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addCapacity),error}const machineImage=options.machineImage??(options.machineImageType===MachineImageType.BOTTLEROCKET?new(amis_1()).BottleRocketImage({architecture:options.instanceType.architecture}):new(amis_1()).EcsOptimizedAmi),machineImageType=options.machineImageType??(amis_1().BottleRocketImage.isBottleRocketImage(machineImage)?MachineImageType.BOTTLEROCKET:MachineImageType.AMAZON_LINUX_2),autoScalingGroup=new(autoscaling()).AutoScalingGroup(this,id,{vpc:this.vpc,machineImage,updateType:options.updatePolicy?void 0:options.updateType||autoscaling().UpdateType.REPLACING_UPDATE,...options});return this.addAutoScalingGroup(autoScalingGroup,{machineImageType,...options}),autoScalingGroup}addAsgCapacityProvider(provider,options={}){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_ecs_AsgCapacityProvider(provider),jsiiDeprecationWarnings().aws_cdk_lib_aws_ecs_AddAutoScalingGroupCapacityOptions(options)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.addAsgCapacityProvider),error}this._capacityProviderNames.includes(provider.capacityProviderName)||(this._hasEc2Capacity=!0,this.configureAutoScalingGroup(provider.autoScalingGroup,{...options,machineImageType:provider.machineImageType,taskDrainTime:provider.enableManagedTerminationProtection||provider.enableManagedDraining?core_1().Duration.seconds(0):options.taskDrainTime,canContainersAccessInstanceRole:getCanContainersAccessInstanceRoleDefault(options.canContainersAccessInstanceRole??provider.canContainersAccessInstanceRole,core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking))}),this._capacityProviderNames.push(provider.capacityProviderName))}addAutoScalingGroup(autoScalingGroup,options={}){this._hasEc2Capacity=!0,this.connections.connections.addSecurityGroup(...autoScalingGroup.connections.securityGroups),this.configureAutoScalingGroup(autoScalingGroup,options)}configureAutoScalingGroup(autoScalingGroup,options={}){const optionsClone={...options,machineImageType:options.machineImageType??MachineImageType.AMAZON_LINUX_2,canContainersAccessInstanceRole:getCanContainersAccessInstanceRoleDefault(options.canContainersAccessInstanceRole,core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking))};if(!(autoScalingGroup instanceof autoscaling().AutoScalingGroup))throw new Error("Cannot configure the AutoScalingGroup because it is an imported resource.");if(autoScalingGroup.osType===ec2().OperatingSystemType.WINDOWS)this.configureWindowsAutoScalingGroup(autoScalingGroup,optionsClone);else switch(optionsClone.machineImageType){case MachineImageType.BOTTLEROCKET:{autoScalingGroup.addUserData("[settings.ecs]",`cluster = "${this.clusterName}"`),autoScalingGroup.role.addManagedPolicy(iam().ManagedPolicy.fromAwsManagedPolicyName("AmazonSSMManagedInstanceCore")),autoScalingGroup.role.addManagedPolicy(iam().ManagedPolicy.fromAwsManagedPolicyName("service-role/AmazonEC2ContainerServiceforEC2Role")),this.handleCanContainersAccessInstanceRoleForBottleRocket(optionsClone);break}case MachineImageType.AMAZON_LINUX_2:{autoScalingGroup.addUserData(`echo ECS_CLUSTER=${this.clusterName} >> /etc/ecs/ecs.config`),this.handleCanContainersAccessInstanceRoleForAL2(autoScalingGroup,optionsClone),autoScalingGroup.spotPrice&&optionsClone.spotInstanceDraining&&autoScalingGroup.addUserData("echo ECS_ENABLE_SPOT_INSTANCE_DRAINING=true >> /etc/ecs/ecs.config");break}default:{if(core_1().Annotations.of(this).addWarningV2("@aws-cdk/aws-ecs:unknownImageType",`Unknown ECS Image type: ${optionsClone.machineImageType}.`),optionsClone.canContainersAccessInstanceRole===!1)throw new Error("The canContainersAccessInstanceRole option is not supported. See https://github.com/aws/aws-cdk/discussions/32609");break}}autoScalingGroup.addToRolePolicy(new(iam()).PolicyStatement({actions:["ecs:DeregisterContainerInstance","ecs:RegisterContainerInstance","ecs:Submit*"],resources:[this.clusterArn]})),autoScalingGroup.addToRolePolicy(new(iam()).PolicyStatement({actions:["ecs:Poll","ecs:StartTelemetrySession"],resources:["*"],conditions:{ArnEquals:{"ecs:cluster":this.clusterArn}}})),autoScalingGroup.addToRolePolicy(new(iam()).PolicyStatement({actions:["ecs:DiscoverPollEndpoint","ecr:GetAuthorizationToken","logs:CreateLogStream","logs:PutLogEvents"],resources:["*"]})),(!options.taskDrainTime||options.taskDrainTime.toSeconds()!==0)&&new(instance_drain_hook_1()).InstanceDrainHook(autoScalingGroup,"DrainECSHook",{autoScalingGroup,cluster:this,drainTime:options.taskDrainTime,topicEncryptionKey:options.topicEncryptionKey})}handleCanContainersAccessInstanceRoleForBottleRocket(options){if((options.canContainersAccessInstanceRole===!1||options.canContainersAccessInstanceRole===void 0)&&!core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking)&&core_1().Annotations.of(this).addWarningV2("@aws-cdk/aws-ecs:deprecatedImdsBlocking","Blocking container accessing instance role is not supported. See https://github.com/aws/aws-cdk/discussions/32609"),options.canContainersAccessInstanceRole===!1&&core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking))throw new Error("The canContainersAccessInstanceRole option is not supported. See https://github.com/aws/aws-cdk/discussions/32609")}handleCanContainersAccessInstanceRoleForAL2(autoScalingGroup,options){if(options.canContainersAccessInstanceRole===!1&&core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking))throw new Error("The canContainersAccessInstanceRole option is not supported. See https://github.com/aws/aws-cdk/discussions/32609");(options.canContainersAccessInstanceRole===!1||options.canContainersAccessInstanceRole===void 0)&&(!core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking)&&core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Enable_IMDS_Blocking_Deprecated_Feature)?(autoScalingGroup.addUserData("sudo yum install -y iptables-services; sudo iptables --insert DOCKER-USER 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP"),autoScalingGroup.addUserData("sudo iptables-save | sudo tee /etc/sysconfig/iptables && sudo systemctl enable --now iptables")):!core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking)&&!core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Enable_IMDS_Blocking_Deprecated_Feature)&&(autoScalingGroup.addUserData("sudo iptables --insert FORWARD 1 --in-interface docker+ --destination 169.254.169.254/32 --jump DROP"),autoScalingGroup.addUserData("sudo service iptables save"),core_1().Annotations.of(this).addWarningV2("@aws-cdk/aws-ecs:deprecatedImdsBlocking","Blocking container access to instance role will be deprecated. Use the @aws-cdk/aws-ecs:enableImdsBlockingDeprecatedFeature feature flagto keep this feature temporarily. See https://github.com/aws/aws-cdk/discussions/32609")),autoScalingGroup.addUserData("echo ECS_AWSVPC_BLOCK_IMDS=true >> /etc/ecs/ecs.config"))}addCapacityProvider(provider){if(!(provider==="FARGATE"||provider==="FARGATE_SPOT"))throw new Error("CapacityProvider not supported");this._capacityProviderNames.includes(provider)||this._capacityProviderNames.push(provider)}arnForTasks(keyPattern){return core_1().Stack.of(this).formatArn({service:"ecs",resource:"task",resourceName:`${this.clusterName}/${keyPattern}`,arnFormat:core_1().ArnFormat.SLASH_RESOURCE_NAME})}grantTaskProtection(grantee){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_iam_IGrantable(grantee)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.grantTaskProtection),error}return iam().Grant.addToPrincipal({grantee,actions:["ecs:UpdateTaskProtection"],resourceArns:[this.arnForTasks("*")]})}configureWindowsAutoScalingGroup(autoScalingGroup,options={}){if((options.canContainersAccessInstanceRole===!1||options.canContainersAccessInstanceRole===void 0)&&!core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking)&&core_1().Annotations.of(this).addWarningV2("@aws-cdk/aws-ecs:deprecatedImdsBlocking","Blocking container accessing instance role is not supported. See https://github.com/aws/aws-cdk/discussions/32609"),options.canContainersAccessInstanceRole===!1&&core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking))throw new Error("The canContainersAccessInstanceRole option is not supported. See https://github.com/aws/aws-cdk/discussions/32609");autoScalingGroup.addUserData("Remove-Item -Recurse C:\\ProgramData\\Amazon\\ECS\\Cache"),autoScalingGroup.addUserData("Import-Module ECSTools"),autoScalingGroup.addUserData(`[Environment]::SetEnvironmentVariable("ECS_CLUSTER", "${this.clusterName}", "Machine")`),autoScalingGroup.addUserData('[Environment]::SetEnvironmentVariable("ECS_ENABLE_AWSLOGS_EXECUTIONROLE_OVERRIDE", "true", "Machine")'),autoScalingGroup.addUserData(`[Environment]::SetEnvironmentVariable("ECS_AVAILABLE_LOGGING_DRIVERS", '["json-file","awslogs"]', "Machine")`),autoScalingGroup.spotPrice&&options.spotInstanceDraining&&autoScalingGroup.addUserData('[Environment]::SetEnvironmentVariable("ECS_ENABLE_SPOT_INSTANCE_DRAINING", "true", "Machine")'),options.canContainersAccessInstanceRole?autoScalingGroup.addUserData(`Initialize-ECSAgent -Cluster '${this.clusterName}'`):(autoScalingGroup.addUserData('[Environment]::SetEnvironmentVariable("ECS_ENABLE_TASK_IAM_ROLE", "true", "Machine")'),autoScalingGroup.addUserData(`Initialize-ECSAgent -Cluster '${this.clusterName}' -EnableTaskIAMRole`))}get autoscalingGroup(){return this._autoscalingGroup}get hasEc2Capacity(){return this._hasEc2Capacity}get executeCommandConfiguration(){return this._executeCommandConfiguration}metricCpuReservation(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricCpuReservation),error}return this.cannedMetric(ecs_canned_metrics_generated_1().ECSMetrics.cpuReservationAverage,props)}metricCpuUtilization(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricCpuUtilization),error}return this.cannedMetric(ecs_canned_metrics_generated_1().ECSMetrics.cpuUtilizationAverage,props)}metricMemoryReservation(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricMemoryReservation),error}return this.cannedMetric(ecs_canned_metrics_generated_1().ECSMetrics.memoryReservationAverage,props)}metricMemoryUtilization(props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metricMemoryUtilization),error}return this.cannedMetric(ecs_canned_metrics_generated_1().ECSMetrics.memoryUtilizationAverage,props)}metric(metricName,props){try{jsiiDeprecationWarnings().aws_cdk_lib_aws_cloudwatch_MetricOptions(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,this.metric),error}return new(cloudwatch()).Metric({namespace:"AWS/ECS",metricName,dimensionsMap:{ClusterName:this.clusterName},...props}).attachTo(this)}cannedMetric(fn,props){return new(cloudwatch()).Metric({...fn({ClusterName:this.clusterName}),...props}).attachTo(this)}}exports.Cluster=Cluster,_a=JSII_RTTI_SYMBOL_1,Cluster[_a]={fqn:"aws-cdk-lib.aws_ecs.Cluster",version:"2.185.0"},__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"enableFargateCapacityProviders",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"addDefaultCapacityProviderStrategy",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"addDefaultCloudMapNamespace",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"addCapacity",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"addAsgCapacityProvider",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"addAutoScalingGroup",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"addCapacityProvider",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"arnForTasks",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"grantTaskProtection",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"metricCpuReservation",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"metricCpuUtilization",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"metricMemoryReservation",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"metricMemoryUtilization",null),__decorate([(0,metadata_resource_1().MethodMetadata)()],Cluster.prototype,"metric",null),Object.defineProperty(Cluster.prototype,CLUSTER_SYMBOL,{value:!0,enumerable:!1,writable:!1});class ImportedCluster extends core_1().Resource{constructor(scope,id,props){super(scope,id),this.connections=new(ec2()).Connections,(0,metadata_resource_1().addConstructMetadata)(this,props),this.clusterName=props.clusterName,this.vpc=props.vpc,this.hasEc2Capacity=props.hasEc2Capacity!==!1,this._defaultCloudMapNamespace=props.defaultCloudMapNamespace,this._executeCommandConfiguration=props.executeCommandConfiguration,this.autoscalingGroup=props.autoscalingGroup,this.clusterArn=props.clusterArn??core_1().Stack.of(this).formatArn({service:"ecs",resource:"cluster",resourceName:props.clusterName}),this.connections=new(ec2()).Connections({securityGroups:props.securityGroups})}get defaultCloudMapNamespace(){return this._defaultCloudMapNamespace}get executeCommandConfiguration(){return this._executeCommandConfiguration}}var ContainerInsights;(function(ContainerInsights2){ContainerInsights2.ENABLED="enabled",ContainerInsights2.DISABLED="disabled",ContainerInsights2.ENHANCED="enhanced"})(ContainerInsights||(exports.ContainerInsights=ContainerInsights={}));var ExecuteCommandLogging;(function(ExecuteCommandLogging2){ExecuteCommandLogging2.NONE="NONE",ExecuteCommandLogging2.DEFAULT="DEFAULT",ExecuteCommandLogging2.OVERRIDE="OVERRIDE"})(ExecuteCommandLogging||(exports.ExecuteCommandLogging=ExecuteCommandLogging={}));class AsgCapacityProvider extends constructs_1().Construct{constructor(scope,id,props){super(scope,id);try{jsiiDeprecationWarnings().aws_cdk_lib_aws_ecs_AsgCapacityProviderProps(props)}catch(error){throw process.env.JSII_DEBUG!=="1"&&error.name==="DeprecationError"&&Error.captureStackTrace(error,AsgCapacityProvider),error}let capacityProviderName=props.capacityProviderName;this.autoScalingGroup=props.autoScalingGroup,this.machineImageType=props.machineImageType??MachineImageType.AMAZON_LINUX_2,this.canContainersAccessInstanceRole=getCanContainersAccessInstanceRoleDefault(props.canContainersAccessInstanceRole,core_1().FeatureFlags.of(this).isEnabled(cx_api_1().Disable_ECS_IMDS_Blocking)),this.enableManagedTerminationProtection=props.enableManagedTerminationProtection??!0,this.enableManagedDraining=props.enableManagedDraining;let managedDraining;if(this.enableManagedDraining!=null&&(managedDraining=this.enableManagedDraining?"ENABLED":"DISABLED"),this.enableManagedTerminationProtection&&props.enableManagedScaling===!1)throw new Error("Cannot enable Managed Termination Protection on a Capacity Provider when Managed Scaling is disabled. Either enable Managed Scaling or disable Managed Termination Protection.");if(this.enableManagedTerminationProtection)if(this.autoScalingGroup instanceof autoscaling().AutoScalingGroup)this.autoScalingGroup.protectNewInstancesFromScaleIn();else throw new Error("Cannot enable Managed Termination Protection on a Capacity Provider when providing an imported AutoScalingGroup.");const capacityProviderNameRegex=/^(?!aws|ecs|fargate).+/gm;if(capacityProviderName){if(!capacityProviderNameRegex.test(capacityProviderName))throw new Error(`Invalid Capacity Provider Name: ${capacityProviderName}, If a name is specified, it cannot start with aws, ecs, or fargate.`)}else capacityProviderNameRegex.test(core_1().Stack.of(this).stackName)||(capacityProviderName="cp-"+core_1().Names.uniqueResourceName(this,{maxLength:252,allowedSpecialCharacters:"-_"}));if(props.instanceWarmupPeriod&&!core_1().Token.isUnresolved(props.instanceWarmupPeriod)&&(props.instanceWarmupPeriod<0||props.instanceWarmupPeriod>1e4))throw new Error(`InstanceWarmupPeriod must be between 0 and 10000 inclusive, got: ${props.instanceWarmupPeriod}.`);const capacityProvider=new(ecs_generated_1()).CfnCapacityProvider(this,id,{name:capacityProviderName,autoScalingGroupProvider:{autoScalingGroupArn:this.autoScalingGroup.autoScalingGroupName,managedScaling:props.enableManagedScaling===!1?void 0:{status:"ENABLED",targetCapacity:props.targetCapacityPercent||100,maximumScalingStepSize:props.maximumScalingStepSize,minimumScalingStepSize:props.minimumScalingStepSize,instanceWarmupPeriod:props.instanceWarmupPeriod},managedTerminationProtection:this.enableManagedTerminationProtection?"ENABLED":"DISABLED",managedDraining}});this.capacityProviderName=capacityProvider.ref}}exports.AsgCapacityProvider=AsgCapacityProvider,_b=JSII_RTTI_SYMBOL_1,AsgCapacityProvider[_b]={fqn:"aws-cdk-lib.aws_ecs.AsgCapacityProvider",version:"2.185.0"};class MaybeCreateCapacityProviderAssociations{constructor(scope,id){this.scope=scope,this.id=id}visit(node){Cluster.isCluster(node)&&(this.scope.defaultCapacityProviderStrategy.length>0||this.scope.capacityProviderNames.length>0&&!this.resource)&&(this.resource=new(ecs_generated_1()).CfnClusterCapacityProviderAssociations(this.scope,this.id,{cluster:node.clusterName,defaultCapacityProviderStrategy:this.scope.defaultCapacityProviderStrategy,capacityProviders:this.scope.capacityProviderNames}))}}