Skip to main content

The CDK Construct Library for AWS::Batch

Project description

AWS Batch Construct Library

---

cfn-resources: Stable

All classes with the Cfn prefix in this module (CFN Resources) are always stable and safe to use.

cdk-constructs: Experimental

The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the 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 the AWS Cloud Development Kit project.

AWS Batch is a batch processing tool for efficiently running hundreds of thousands computing jobs in AWS. Batch can dynamically provision different types of compute resources based on the resource requirements of submitted jobs.

AWS Batch simplifies the planning, scheduling, and executions of your batch workloads across a full range of compute services like Amazon EC2 and Spot Resources.

Batch achieves this by utilizing queue processing of batch job requests. To successfully submit a job for execution, you need the following resources:

  1. Job Definition - Group various job properties (container image, resource requirements, env variables...) into a single definition. These definitions are used at job submission time.
  2. Compute Environment - the execution runtime of submitted batch jobs
  3. Job Queue - the queue where batch jobs can be submitted to via AWS SDK/CLI

For more information on AWS Batch visit the AWS Docs for Batch.

Compute Environment

At the core of AWS Batch is the compute environment. All batch jobs are processed within a compute environment, which uses resource like OnDemand/Spot EC2 instances or Fargate.

In MANAGED mode, AWS will handle the provisioning of compute resources to accommodate the demand. Otherwise, in UNMANAGED mode, you will need to manage the provisioning of those resources.

Below is an example of each available type of compute environment:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
default_vpc = ec2.Vpc(self, "VPC")

# default is managed
aws_managed_environment = batch.ComputeEnvironment(stack, "AWS-Managed-Compute-Env",
    compute_resources={
        "vpc": vpc
    }
)

customer_managed_environment = batch.ComputeEnvironment(stack, "Customer-Managed-Compute-Env",
    managed=False
)

Spot-Based Compute Environment

It is possible to have AWS Batch submit spotfleet requests for obtaining compute resources. Below is an example of how this can be done:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
vpc = ec2.Vpc(self, "VPC")

spot_environment = batch.ComputeEnvironment(stack, "MySpotEnvironment",
    compute_resources={
        "type": batch.ComputeResourceType.SPOT,
        "bid_percentage": 75,  # Bids for resources at 75% of the on-demand price
        "vpc": vpc
    }
)

Fargate Compute Environment

It is possible to have AWS Batch submit jobs to be run on Fargate compute resources. Below is an example of how this can be done:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
vpc = ec2.Vpc(self, "VPC")

fargate_spot_environment = batch.ComputeEnvironment(stack, "MyFargateEnvironment",
    compute_resources={
        "type": batch.ComputeResourceType.FARGATE_SPOT,
        "vpc": vpc
    }
)

Understanding Progressive Allocation Strategies

AWS Batch uses an allocation strategy to determine what compute resource will efficiently handle incoming job requests. By default, BEST_FIT will 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 vCPU
Job Queue:
---------
| A | B |
---------

Job Requirements:
A => 4 vCPU - ALLOCATED TO m5.xlarge
B => 2 vCPU - WAITING

In this situation, Batch will allocate Job A to compute resource #1 because it is the most cost efficient resource that matches the vCPU requirement. However, with this BEST_FIT strategy, Job B will 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 similar m5.xlarge resource to be provisioned.

The alternative would be to use the BEST_FIT_PROGRESSIVE strategy in order for the remaining job to be handled in larger containers regardless of vCPU requirement and costs.

Launch template support

Simply define your Launch Template:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_launch_template = ec2.CfnLaunchTemplate(self, "LaunchTemplate",
    launch_template_name="extra-storage-template",
    launch_template_data={
        "block_device_mappings": [{
            "device_name": "/dev/xvdcz",
            "ebs": {
                "encrypted": True,
                "volume_size": 100,
                "volume_type": "gp2"
            }
        }
        ]
    }
)

and use it:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_compute_env = batch.ComputeEnvironment(self, "ComputeEnv",
    compute_resources={
        "launch_template": {
            "launch_template_name": my_launch_template.launch_template_name
        },
        "vpc": vpc
    },
    compute_environment_name="MyStorageCapableComputeEnvironment"
)

Importing an existing Compute Environment

To import an existing batch compute environment, call ComputeEnvironment.fromComputeEnvironmentArn().

Below is an example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
compute_env = batch.ComputeEnvironment.from_compute_environment_arn(self, "imported-compute-env", "arn:aws:batch:us-east-1:555555555555:compute-environment/My-Compute-Env")

Change the baseline AMI of the compute resources

Occasionally, you will need to deviate from the default processing AMI.

ECS Optimized Amazon Linux 2 example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_compute_env = batch.ComputeEnvironment(self, "ComputeEnv",
    compute_resources={
        "image": ecs.EcsOptimizedAmi(
            generation=ec2.AmazonLinuxGeneration.AMAZON_LINUX_2
        ),
        "vpc": vpc
    }
)

Custom based AMI example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
my_compute_env = batch.ComputeEnvironment(self, "ComputeEnv",
    compute_resources={
        "image": ec2.MachineImage.generic_linux(
            [aws-region]="[ami-ID]"
        ),
        "vpc": vpc
    }
)

Job Queue

Jobs are always submitted to a specific queue. This means that you have to create a queue before you can start submitting jobs. Each queue is mapped to at least one (and no more than three) compute environment. When the job is scheduled for execution, AWS Batch will select the compute environment based on ordinal priority and available capacity in each environment.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
job_queue = batch.JobQueue(stack, "JobQueue",
    compute_environments=[{
        # Defines a collection of compute resources to handle assigned batch jobs
        "compute_environment": compute_environment,
        # Order determines the allocation order for jobs (i.e. Lower means higher preference for job assignment)
        "order": 1
    }
    ]
)

Priorty-Based Queue Example

Sometimes you might have jobs that are more important than others, and when submitted, should take precedence over the existing jobs. To achieve this, you can create a priority based execution strategy, by assigning each queue its own priority:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
high_prio_queue = batch.JobQueue(stack, "JobQueue",
    compute_environments=shared_compute_envs,
    priority=2
)

low_prio_queue = batch.JobQueue(stack, "JobQueue",
    compute_environments=shared_compute_envs,
    priority=1
)

By making sure to use the same compute environments between both job queues, we will give precedence to the highPrioQueue for the assigning of jobs to available compute environments.

Importing an existing Job Queue

To import an existing batch job queue, call JobQueue.fromJobQueueArn().

Below is an example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
job_queue = batch.JobQueue.from_job_queue_arn(self, "imported-job-queue", "arn:aws:batch:us-east-1:555555555555:job-queue/High-Prio-Queue")

Job Definition

A Batch Job definition helps AWS Batch understand important details about how to run your application in the scope of a Batch Job. This involves key information like resource requirements, what containers to run, how the compute environment should be prepared, and more. Below is a simple example of how to create a job definition:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
repo = ecr.Repository.from_repository_name(stack, "batch-job-repo", "todo-list")

batch.JobDefinition(stack, "batch-job-def-from-ecr",
    container={
        "image": ecs.EcrImage(repo, "latest")
    }
)

Using a local Docker project

Below is an example of how you can create a Batch Job Definition from a local Docker application.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
batch.JobDefinition(stack, "batch-job-def-from-local",
    container={
        # todo-list is a directory containing a Dockerfile to build the application
        "image": ecs.ContainerImage.from_asset("../todo-list")
    }
)

Providing custom log configuration

You can provide custom log driver and its configuration for the container.

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
batch.JobDefinition(stack, "job-def",
    container={
        "image": ecs.EcrImage.from_registry("docker/whalesay"),
        "log_configuration": {
            "log_driver": batch.LogDriver.AWSLOGS,
            "options": {"awslogs-region": "us-east-1"},
            "secret_options": [
                batch.ExposedSecret.from_parameters_store("xyz", ssm.StringParameter.from_string_parameter_name(stack, "parameter", "xyz"))
            ]
        }
    }
)

Importing an existing Job Definition

From ARN

To import an existing batch job definition from its ARN, call JobDefinition.fromJobDefinitionArn().

Below is an example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
job = batch.JobDefinition.from_job_definition_arn(self, "imported-job-definition", "arn:aws:batch:us-east-1:555555555555:job-definition/my-job-definition")

From Name

To import an existing batch job definition from its name, call JobDefinition.fromJobDefinitionName(). If name is specified without a revision then the latest active revision is used.

Below is an example:

# Example automatically generated without compilation. See https://github.com/aws/jsii/issues/826
# Without revision
job = batch.JobDefinition.from_job_definition_name(self, "imported-job-definition", "my-job-definition")

# With revision
job = batch.JobDefinition.from_job_definition_name(self, "imported-job-definition", "my-job-definition:3")

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

aws-cdk.aws-batch-alpha-2.0.0a1.tar.gz (342.2 kB view details)

Uploaded Source

Built Distribution

aws_cdk.aws_batch_alpha-2.0.0a1-py3-none-any.whl (340.7 kB view details)

Uploaded Python 3

File details

Details for the file aws-cdk.aws-batch-alpha-2.0.0a1.tar.gz.

File metadata

  • Download URL: aws-cdk.aws-batch-alpha-2.0.0a1.tar.gz
  • Upload date:
  • Size: 342.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.6.5

File hashes

Hashes for aws-cdk.aws-batch-alpha-2.0.0a1.tar.gz
Algorithm Hash digest
SHA256 3c3494fdc9a3cc6c7d2f91e8d54844620f5dcf1d35b545cd14b75922e7570e1a
MD5 a029eb68ef491269142e8eda499a903e
BLAKE2b-256 7bd98549ab98ab0b099910462120d1d2651ad5b493673721074f0c6ba5043cc0

See more details on using hashes here.

File details

Details for the file aws_cdk.aws_batch_alpha-2.0.0a1-py3-none-any.whl.

File metadata

  • Download URL: aws_cdk.aws_batch_alpha-2.0.0a1-py3-none-any.whl
  • Upload date:
  • Size: 340.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.4.2 importlib_metadata/4.8.1 pkginfo/1.7.1 requests/2.26.0 requests-toolbelt/0.9.1 tqdm/4.62.3 CPython/3.6.5

File hashes

Hashes for aws_cdk.aws_batch_alpha-2.0.0a1-py3-none-any.whl
Algorithm Hash digest
SHA256 3711dcf24d44371b2a5c8a2b813b0f74eb6480dc8948b0bdc3be3b37367d7734
MD5 3bec90dbaf996275ae7870d4fac81c74
BLAKE2b-256 1893d796716dad4949308a864e926da968d67bb845b2f29bd13d8a9e93ef3435

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page