Package: aws-cdk.aws-batch-alpha
AWS Batch Construct Library---The APIs of higher level constructs in this module are indeveloper previewbefore they
become stable. We will only make breaking changes to address unforeseen API issues. Therefore,
these APIs are not subject toSemantic Versioning, and breaking changes
will be announced in release notes. This means that while you may use them, you may need to
update your source code when upgrading to a newer version of this package.This module is part of theAWS Cloud Development Kitproject.AWS Batch is a batch processing tool for efficiently running hundreds of thousands computing jobs in AWS.
Batch can dynamically provisionAmazon EC2Instances to meet the resource requirements of submitted jobs
and simplifies the planning, scheduling, and executions of your batch workloads. Batch achieves this through four different resources:ComputeEnvironments: Contain the resources used to execute JobsJobDefinitions: Define a type of Job that can be submittedJobQueues: Route waiting Jobs to ComputeEnvironmentsSchedulingPolicies: Applied to Queues to control how and when Jobs exit the JobQueue and enter the ComputeEnvironmentComputeEnvironments can be managed or unmanaged. Batch will automatically provision EC2 Instances in a managedComputeEnvironmentand will
not provision any Instances in an unmanagedComputeEnvironment. ManagedComputeEnvironments can use ECS, Fargate, or EKS resources to spin up
EC2 Instances in (ensure your EKS Cluster hasbeen configuredto support a Batch ComputeEnvironment before linking it). You can use Launch Templates and Placement Groups to configure exactly how these resources
will be provisioned.JobDefinitions can use either ECS resources or EKS resources. ECSJobDefinitions can use multiple containers to execute distributed workloads.
EKSJobDefinitions can only execute a single container. Submitted Jobs useJobDefinitions as templates.JobQueues must link at least oneComputeEnvironment. Jobs exit the Queue in FIFO order unless aSchedulingPolicyis specified.SchedulingPolicys tell the Scheduler how to choose which Jobs should be executed next by the ComputeEnvironment.Use Cases & ExamplesCost OptimizationSpot InstancesSpot instances are significantly discounted EC2 instances that can be reclaimed at any time by AWS.
Workloads that are fault-tolerant or stateless can take advantage of spot pricing.
To use spot spot instances, setspottotrueon a managed Ec2 or Fargate Compute Environment:vpc=ec2.Vpc(self,"VPC")batch.FargateComputeEnvironment(self,"myFargateComputeEnv",vpc=vpc,spot=True)Batch allows you to specify the percentage of the on-demand instance that the current spot price
must be to provision the instance using thespotBidPercentage.
This defaults to 100%, which is the recommended value.
This value cannot be specified forFargateComputeEnvironments
and only applies toManagedEc2EcsComputeEnvironments.
The following code configures a Compute Environment to only use spot instances that
are at most 20% the price of the on-demand instance price:vpc=ec2.Vpc(self,"VPC")batch.ManagedEc2EcsComputeEnvironment(self,"myEc2ComputeEnv",vpc=vpc,spot=True,spot_bid_percentage=20)For stateful or otherwise non-interruption-tolerant workflows, omitspotor set it tofalseto only provision on-demand instances.Choosing Your Instance TypesBatch allows you to choose the instance types or classes that will run your workload.
This example configures yourComputeEnvironmentto use only theM5AD.largeinstance:vpc=ec2.Vpc(self,"VPC")batch.ManagedEc2EcsComputeEnvironment(self,"myEc2ComputeEnv",vpc=vpc,instance_types=[ec2.InstanceType.of(ec2.InstanceClass.M5AD,ec2.InstanceSize.LARGE)])Batch allows you to specify only the instance class and to let it choose the size, which you can do like this:# compute_env: batch.IManagedEc2EcsComputeEnvironmentvpc=ec2.Vpc(self,"VPC")compute_env.add_instance_class(ec2.InstanceClass.M5AD)# Or, specify it on the constructor:batch.ManagedEc2EcsComputeEnvironment(self,"myEc2ComputeEnv",vpc=vpc,instance_classes=[ec2.InstanceClass.R4])Unless you explicitly specifyuseOptimalInstanceClasses: false, this compute environment will use'optimal'instances,
which tells Batch to pick an instance from the C4, M4, and R4 instance families.Note: Batch does not allow specifying instance types or classes with different architectures.
For example,InstanceClass.A1cannot be specified alongside'optimal',
becauseA1uses ARM and'optimal'uses x86_64.
You can specify both'optimal'alongside several different instance types in the same compute environment:# vpc: ec2.IVpccompute_env=batch.ManagedEc2EcsComputeEnvironment(self,"myEc2ComputeEnv",instance_types=[ec2.InstanceType.of(ec2.InstanceClass.M5AD,ec2.InstanceSize.LARGE)],use_optimal_instance_classes=True,# defaultvpc=vpc)# Note: this is equivalent to specifyingcompute_env.add_instance_type(ec2.InstanceType.of(ec2.InstanceClass.M5AD,ec2.InstanceSize.LARGE))compute_env.add_instance_class(ec2.InstanceClass.C4)compute_env.add_instance_class(ec2.InstanceClass.M4)compute_env.add_instance_class(ec2.InstanceClass.R4)Allocation StrategiesAllocation StrategyOptimized forDownsidesBEST_FITCostMay limit throughputBEST_FIT_PROGRESSIVEThroughputMay increase costSPOT_CAPACITY_OPTIMIZEDLeast interruptionOnly useful on Spot instancesSPOT_PRICE_CAPACITY_OPTIMIZEDLeast interruption + PriceOnly useful on Spot instancesBatch provides different Allocation Strategies to help it choose which instances to provision.
If your workflow tolerates interruptions, you should enablespoton yourComputeEnvironmentand useSPOT_PRICE_CAPACITY_OPTIMIZED(this is the default ifspotis enabled).
This will tell Batch to choose the instance types from the ones you’ve specified that have
the most spot capacity available to minimize the chance of interruption and have the lowest price.
To get the most benefit from your spot instances,
you should allow Batch to choose from as many different instance types as possible.
If you only care about minimal interruptions and not want Batch to optimize for cost, useSPOT_CAPACITY_OPTIMIZED.SPOT_PRICE_CAPACITY_OPTIMIZEDis recommended overSPOT_CAPACITY_OPTIMIZEDfor most use cases.If your workflow does not tolerate interruptions and you want to minimize your costs at the expense
of potentially longer waiting times, useAllocationStrategy.BEST_FIT.
This will choose the lowest-cost instance type that fits all the jobs in the queue.
If instances of that type are not available,
the queue will not choose a new type; instead, it will wait for the instance to become available.
This can stall yourQueue, with your compute environment only using part of its max capacity
(or none at all) until theBEST_FITinstance becomes available.If you are running a workflow that does not tolerate interruptions and you want to maximize throughput,
you can useAllocationStrategy.BEST_FIT_PROGRESSIVE.
This is the default Allocation Strategy ifspotisfalseor unspecified.
This strategy will examine the Jobs in the queue and choose whichever instance type meets the requirements
of the jobs in the queue and with the lowest cost per vCPU, just asBEST_FIT.
However, if not all of the capacity can be filled with this instance type,
it will choose a new next-best instance type to run any jobs that couldn’t fit into theBEST_FITcapacity.
To make the most use of this allocation strategy,
it is recommended to use as many instance classes as is feasible for your workload.
This example shows aComputeEnvironmentthat usesBEST_FIT_PROGRESSIVEwith'optimal'andInstanceClass.M5instance types:# vpc: ec2.IVpccompute_env=batch.ManagedEc2EcsComputeEnvironment(self,"myEc2ComputeEnv",vpc=vpc,instance_classes=[ec2.InstanceClass.M5])This example shows aComputeEnvironmentthat usesBEST_FITwith'optimal'instances:# vpc: ec2.IVpccompute_env=batch.ManagedEc2EcsComputeEnvironment(self,"myEc2ComputeEnv",vpc=vpc,allocation_strategy=batch.AllocationStrategy.BEST_FIT)Note:allocationStrategycannot be specified on Fargate Compute Environments.Controlling vCPU allocationYou can specify the maximum and minimum vCPUs a managedComputeEnvironmentcan have at any given time.
Batch willalwaysmaintainminvCpusworth of instances in your ComputeEnvironment, even if it is not executing any jobs,
and even if it is disabled. Batch will scale the instances up tomaxvCpusworth of instances as
jobs exit the JobQueue and enter the ComputeEnvironment. If you useAllocationStrategy.BEST_FIT_PROGRESSIVE,AllocationStrategy.SPOT_PRICE_CAPACITY_OPTIMIZED, orAllocationStrategy.SPOT_CAPACITY_OPTIMIZED,
batch may exceedmaxvCpus; it will never exceedmaxvCpusby more than a single instance type. This example configures aminvCpusof 10 and amaxvCpusof 100:# vpc: ec2.IVpcbatch.ManagedEc2EcsComputeEnvironment(self,"myEc2ComputeEnv",vpc=vpc,instance_classes=[ec2.InstanceClass.R4],minv_cpus=10,maxv_cpus=100)Tagging InstancesYou can tag any instances launched by your managed EC2 ComputeEnvironments by using the CDKTagsAPI:fromaws_cdkimportTags# vpc: ec2.IVpctag_cE=batch.ManagedEc2EcsComputeEnvironment(self,"CEThatMakesTaggedInstnaces",vpc=vpc)Tags.of(tag_cE).add("super","salamander")UnmanagedComputeEnvironments do not supportmaxvCpusorminvCpusbecause you must provision and manage the instances yourself;
that is, Batch will not scale them up and down as needed.Sharing a ComputeEnvironment between multiple JobQueuesMultipleJobQueues can share the sameComputeEnvironment.
If multiple Queues are attempting to submit Jobs to the sameComputeEnvironment,
Batch will pick the Job from the Queue with the highest priority.
This example creates twoJobQueues that share aComputeEnvironment:# vpc: ec2.IVpcshared_compute_env=batch.FargateComputeEnvironment(self,"spotEnv",vpc=vpc,spot=True)low_priority_queue=batch.JobQueue(self,"JobQueue",priority=1)high_priority_queue=batch.JobQueue(self,"JobQueue",priority=10)low_priority_queue.add_compute_environment(shared_compute_env,1)high_priority_queue.add_compute_environment(shared_compute_env,1)Fairshare SchedulingBatchJobQueues execute Jobs submitted to them in FIFO order unless you specify aSchedulingPolicy.
FIFO queuing can cause short-running jobs to be starved while long-running jobs fill the compute environment.
To solve this, Jobs can be associated with a share.Shares consist of ashareIdentifierand aweightFactor, which is inversely correlated with the vCPU allocated to that share identifier.
When submitting a Job, you can specify itsshareIdentifierto associate that particular job with that share.
Let's see how the scheduler uses this information to schedule jobs.For example, if there are two shares defined as follows:Share IdentifierWeight FactorA1B1The weight factors share the following relationship:A_{vCpus} / A_{Weight} = B_{vCpus} / B_{Weight}whereBvCpusis the number of vCPUs allocated to jobs with share identifier'B', andB_weightis the weight factor ofB.The total number of vCpus allocated to a share is equal to the amount of jobs in that share times the number of vCpus necessary for every job.
Let's say that each A job needs 32 VCpus (A_requirement= 32) and each B job needs 64 vCpus (B_requirement= 64):A_{vCpus} = A_{Jobs} * A_{Requirement}B_{vCpus} = B_{Jobs} * B_{Requirement}We have:A_{vCpus} / A_{Weight} = B_{vCpus} / B_{Weight}A_{Jobs} * A_{Requirement} / A_{Weight} = B_{Jobs} * B_{Requirement} / B_{Weight}A_{Jobs} * 32 / 1 = B_{Jobs} * 64 / 1A_{Jobs} * 32 = B_{Jobs} * 64A_{Jobs} = B_{Jobs} * 2Thus the scheduler will schedule two'A'jobs for each'B'job.You can control the weight factors to change these ratios, but note that
weight factors are inversely correlated with the vCpus allocated to the corresponding share.This example would be configured like this:fairshare_policy=batch.FairshareSchedulingPolicy(self,"myFairsharePolicy")fairshare_policy.add_share(share_identifier="A",weight_factor=1)fairshare_policy.add_share(share_identifier="B",weight_factor=1)batch.JobQueue(self,"JobQueue",scheduling_policy=fairshare_policy)Note: The scheduler will only consider the current usage of the compute environment unless you specifyshareDecay.
For example, ashareDecayof 5 minutes in the above example means that at any given point in time, twice as many'A'jobs
will be scheduled for each'B'job, but only for the past 5 minutes. If'B'jobs run longer than 5 minutes, then
the scheduler is allowed to put more than two'A'jobs for each'B'job, because the usage of those long-running'B'jobs will no longer be considered after 5 minutes.shareDecaylinearly decreases the usage of
long running jobs for calculation purposes. For example if share decay is 60 seconds,
then jobs that run for 30 seconds have their usage considered to be only 50% of what it actually is,
but after a whole minute the scheduler pretends they don't exist for fairness calculations.The following code specifies ashareDecayof 5 minutes:importaws_cdkascdkfairshare_policy=batch.FairshareSchedulingPolicy(self,"myFairsharePolicy",share_decay=cdk.Duration.minutes(5))If you have high priority jobs that should always be executed as soon as they arrive,
you can define acomputeReservationto specify the percentage of the
maximum vCPU capacity that should be reserved for shares that arenot in the queue.
The actual reserved percentage is defined by Batch as:(\frac{computeReservation}{100}) ^ {ActiveFairShares}whereActiveFairSharesis the number of shares for which there exists
at least one job in the queue with a unique share identifier.This is best illustrated with an example.
Suppose there are three shares with share identifiersA,BandCrespectively
and we specify thecomputeReservationto be 75%. The queue is currently empty,
and no other shares exist.There are no active fair shares, since the queue is empty.
Thus (75/100)^0 = 1 = 100% of the maximum vCpus are reserved for all shares.A job with identifierAenters the queue.The number of active fair shares is now 1, hence
(75/100)^1 = .75 = 75% of the maximum vCpus are reserved for all shares that do not have the identifierA;
for this example, this isBandC,
(but if jobs are submitted with a share identifier not covered by this fairshare policy, those would be considered just asBandCare).Now aBjob enters the queue. The number of active fair shares is now 2,
so (75/100)^2 = .5625 = 56.25% of the maximum vCpus are reserved for all shares that do not have the identifierAorB.Now a secondAjob enters the queue. The number of active fair shares is still 2,
so the percentage reserved is still 56.25%Now aCjob enters the queue. The number of active fair shares is now 3,
so (75/100)^3 = .421875 = 42.1875% of the maximum vCpus are reserved for all shares that do not have the identifierA,B, orC.If there are no other shares that your jobs can specify, this means that 42.1875% of your capacity will never be used!Now,A,B, andCcan only consume 100% - 42.1875% = 57.8125% of the maximum vCpus.
Note that the this percentage isnotsplit betweenA,B, andC.
Instead, the scheduler will use theirweightFactors to decide which jobs to schedule;
the only difference is that instead of competing for 100% of the max capacity, jobs compete for 57.8125% of the max capacity.This example specifies acomputeReservationof 75% that will behave as explained in the example above:batch.FairshareSchedulingPolicy(self,"myFairsharePolicy",compute_reservation=75,shares=[batch.Share(weight_factor=1,share_identifier="A"),batch.Share(weight_factor=0.5,share_identifier="B"),batch.Share(weight_factor=2,share_identifier="C")])You can specify apriorityon yourJobDefinitions to tell the scheduler to prioritize certain jobs that share the same share identifier.Configuring Job Retry PoliciesCertain workflows may result in Jobs failing due to intermittent issues.
Jobs can specify retry policies to respond to different failures with different actions.
There are three different ways information about the way a Job exited can be conveyed;exitCode: the exit code returned from the process executed by the container. Will only match non-zero exit codes.reason: any middleware errors, like your Docker registry being down.statusReason: infrastructure errors, most commonly your spot instance being reclaimed.For most use cases, only one of these will be associated with a particular action at a time.
To specify commonexitCodes,reasons, orstatusReasons, use the corresponding value from
theReasonclass. This example shows some common failure reasons:importaws_cdkascdkjob_defn=batch.EcsJobDefinition(self,"JobDefn",container=batch.EcsEc2ContainerDefinition(self,"containerDefn",image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),memory=cdk.Size.mebibytes(2048),cpu=256),retry_attempts=5,retry_strategies=[batch.RetryStrategy.of(batch.Action.EXIT,batch.Reason.CANNOT_PULL_CONTAINER)])job_defn.add_retry_strategy(batch.RetryStrategy.of(batch.Action.EXIT,batch.Reason.SPOT_INSTANCE_RECLAIMED))job_defn.add_retry_strategy(batch.RetryStrategy.of(batch.Action.EXIT,batch.Reason.CANNOT_PULL_CONTAINER))job_defn.add_retry_strategy(batch.RetryStrategy.of(batch.Action.EXIT,batch.Reason.custom(on_exit_code="40*",on_reason="some reason")))When specifying a custom reason,
you can specify a glob string to match each of these and react to different failures accordingly.
Up to five different retry strategies can be configured for each Job,
and each strategy can match against some or all ofexitCode,reason, andstatusReason.
You can optionally configure the number of times a job will be retried,
but you cannot configure different retry counts for different strategies; they all share the same count.
If multiple conditions are specified in a given retry strategy,
they must all match for the action to be taken; the conditions are ANDed together, not ORed.Running single-container ECS workflowsBatch can run jobs on ECS or EKS. ECS jobs can be defined as single container or multinode.
This example creates aJobDefinitionthat runs a single container with ECS:importaws_cdkascdkimportaws_cdk.aws_iamasiamimportaws_cdk.aws_efsasefs# my_file_system: efs.IFileSystem# my_job_role: iam.Rolemy_file_system.grant_read(my_job_role)job_defn=batch.EcsJobDefinition(self,"JobDefn",container=batch.EcsEc2ContainerDefinition(self,"containerDefn",image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),memory=cdk.Size.mebibytes(2048),cpu=256,volumes=[batch.EcsVolume.efs(name="myVolume",file_system=my_file_system,container_path="/Volumes/myVolume",use_job_role=True)],job_role=my_job_role))For workflows that need persistent storage, batch supports mountingVolumes to the container.
You can both provision the volume and mount it to the container in a single operation:importaws_cdk.aws_efsasefs# my_file_system: efs.IFileSystem# job_defn: batch.EcsJobDefinitionjob_defn.container.add_volume(batch.EcsVolume.efs(name="myVolume",file_system=my_file_system,container_path="/Volumes/myVolume"))SecretsYou can expose SecretsManager Secret ARNs or SSM Parameters to your container as environment variables.
The following example defines theMY_SECRET_ENV_VARenvironment variable that contains the
ARN of the Secret defined bymySecret:importaws_cdkascdk# my_secret: secretsmanager.ISecretjob_defn=batch.EcsJobDefinition(self,"JobDefn",container=batch.EcsEc2ContainerDefinition(self,"containerDefn",image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),memory=cdk.Size.mebibytes(2048),cpu=256,secrets={"MY_SECRET_ENV_VAR":batch.Secret.from_secrets_manager(my_secret)}))Running Kubernetes WorkflowsBatch also supports running workflows on EKS. The following example creates aJobDefinitionthat runs on EKS:importaws_cdkascdkjob_defn=batch.EksJobDefinition(self,"eksf2",container=batch.EksContainerDefinition(self,"container",image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),volumes=[batch.EksVolume.empty_dir(name="myEmptyDirVolume",mount_path="/mount/path",medium=batch.EmptyDirMediumType.MEMORY,readonly=True,size_limit=cdk.Size.mebibytes(2048))]))You can mountVolumes to these containers in a single operation:# job_defn: batch.EksJobDefinitionjob_defn.container.add_volume(batch.EksVolume.empty_dir(name="emptyDir",mount_path="/Volumes/emptyDir"))job_defn.container.add_volume(batch.EksVolume.host_path(name="hostPath",host_path="/sys",mount_path="/Volumes/hostPath"))job_defn.container.add_volume(batch.EksVolume.secret(name="secret",optional=True,mount_path="/Volumes/secret",secret_name="mySecret"))Running Distributed WorkflowsSome workflows benefit from parallellization and are most powerful when run in a distributed environment,
such as certain numerical calculations or simulations. Batch offersMultiNodeJobDefinitions,
which allow a single job to run on multiple instances in parallel, for this purpose.
Message Passing Interface (MPI) is often used with these workflows.
You must configure your containers to use MPI properly,
but Batch allows different nodes running different containers to communicate easily with one another.
You must configure your containers to use certain environment variables that Batch will provide them,
which lets them know which one is the main node, among other information.
For an in-depth example on using MPI to perform numerical computations on Batch,
see thisblog postIn particular, the environment variable that tells the containers which one is the main node can be configured on yourMultiNodeJobDefinitionas follows:importaws_cdkascdkmulti_node_job=batch.MultiNodeJobDefinition(self,"JobDefinition",instance_type=ec2.InstanceType.of(ec2.InstanceClass.R4,ec2.InstanceSize.LARGE),containers=[batch.MultiNodeContainer(container=batch.EcsEc2ContainerDefinition(self,"mainMPIContainer",image=ecs.ContainerImage.from_registry("yourregsitry.com/yourMPIImage:latest"),cpu=256,memory=cdk.Size.mebibytes(2048)),start_node=0,end_node=5)])# convenience methodmulti_node_job.add_container(start_node=6,end_node=10,container=batch.EcsEc2ContainerDefinition(self,"multiContainer",image=ecs.ContainerImage.from_registry("amazon/amazon-ecs-sample"),cpu=256,memory=cdk.Size.mebibytes(2048)))If you need to set the control node to an index other than 0, specify it in directly:multi_node_job=batch.MultiNodeJobDefinition(self,"JobDefinition",main_node=5,instance_type=ec2.InstanceType.of(ec2.InstanceClass.R4,ec2.InstanceSize.LARGE))Pass Parameters to a JobBatch allows you define parameters in yourJobDefinition, which can be referenced in the container command. For example:importaws_cdkascdkbatch.EcsJobDefinition(self,"JobDefn",parameters={"echo_param":"foobar"},container=batch.EcsEc2ContainerDefinition(self,"containerDefn",image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),memory=cdk.Size.mebibytes(2048),cpu=256,command=["echo","Ref::echoParam"]))Understanding Progressive Allocation StrategiesAWS Batch uses anallocation strategyto determine what compute resource will efficiently handle incoming job requests. By default,BEST_FITwill pick an available compute instance based on vCPU requirements. If none exist, the job will wait until resources become available. However, with this strategy, you may have jobs waiting in the queue unnecessarily despite having more powerful instances available. Below is an example of how that situation might look like:Compute Environment:

1. m5.xlarge => 4 vCPU
2. m5.2xlarge => 8 vCPUJob Queue:
---------
| A | B |
---------

Job Requirements:
A => 4 vCPU - ALLOCATED TO m5.xlarge
B => 2 vCPU - WAITINGIn this situation, Batch will allocateJob Ato compute resource #1 because it is the most cost efficient resource that matches the vCPU requirement. However, with thisBEST_FITstrategy,Job Bwill not be allocated to our other available compute resource even though it is strong enough to handle it. Instead, it will wait until the first job is finished processing or wait a similarm5.xlargeresource to be provisioned.The alternative would be to use theBEST_FIT_PROGRESSIVEstrategy in order for the remaining job to be handled in larger containers regardless of vCPU requirement and costs.PermissionsYou can grant any Principal thebatch:submitJobpermission on both a job definition and a job queue like this:importaws_cdkascdkimportaws_cdk.aws_iamasiam# vpc: ec2.IVpcecs_job=batch.EcsJobDefinition(self,"JobDefn",container=batch.EcsEc2ContainerDefinition(self,"containerDefn",image=ecs.ContainerImage.from_registry("public.ecr.aws/amazonlinux/amazonlinux:latest"),memory=cdk.Size.mebibytes(2048),cpu=256))queue=batch.JobQueue(self,"JobQueue",compute_environments=[batch.OrderedComputeEnvironment(compute_environment=batch.ManagedEc2EcsComputeEnvironment(self,"managedEc2CE",vpc=vpc),order=1)],priority=10)user=iam.User(self,"MyUser")ecs_job.grant_submit_job(user,queue)