@aws-cdk/aws-batch

中文文档
1.204.0发布于 2023/06/20Apache-2.0TypeScriptCommonJS近 30 天下载 7.1万

The CDK Construct Library for AWS::Batch

此软件包已被标记为弃用

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html

原始使用文档
文档目录14 节
  1. Compute Environment
  2. Spot-Based Compute Environment
  3. Fargate Compute Environment
  4. Understanding Progressive Allocation Strategies
  5. Launch template support
  6. Importing an existing Compute Environment
  7. Change the baseline AMI of the compute resources
  8. Job Queue
  9. Priorty-Based Queue Example
  10. Importing an existing Job Queue
  11. Job Definition
  12. Using a local Docker project
  13. Providing custom log configuration
  14. Importing an existing Job Definition

AWS Batch Construct Library


End-of-Support

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2.

For more information on how to migrate, see the Migrating to AWS CDK v2 guide.


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:

declare const vpc: ec2.Vpc;

// default is managed
const awsManagedEnvironment = new batch.ComputeEnvironment(this, 'AWS-Managed-Compute-Env', {
  computeResources: {
    vpc,
  }
});

const customerManagedEnvironment = new batch.ComputeEnvironment(this, 'Customer-Managed-Compute-Env', {
  managed: false, // unmanaged environment
});

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:

const vpc = new ec2.Vpc(this, 'VPC');

const spotEnvironment = new batch.ComputeEnvironment(this, 'MySpotEnvironment', {
  computeResources: {
    type: batch.ComputeResourceType.SPOT,
    bidPercentage: 75, // Bids for resources at 75% of the on-demand price
    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:

const vpc = new ec2.Vpc(this, 'VPC');

const fargateSpotEnvironment = new batch.ComputeEnvironment(this, 'MyFargateEnvironment', {
  computeResources: {
    type: batch.ComputeResourceType.FARGATE_SPOT,
    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:

// This example is only available in TypeScript
const myLaunchTemplate = new ec2.CfnLaunchTemplate(this, 'LaunchTemplate', {
  launchTemplateName: 'extra-storage-template',
  launchTemplateData: {
    blockDeviceMappings: [
      {
        deviceName: '/dev/xvdcz',
        ebs: {
          encrypted: true,
          volumeSize: 100,
          volumeType: 'gp2',
        },
      },
    ],
  },
});

and use it:

declare const vpc: ec2.Vpc;
declare const myLaunchTemplate: ec2.CfnLaunchTemplate;

const myComputeEnv = new batch.ComputeEnvironment(this, 'ComputeEnv', {
  computeResources: {
    launchTemplate: {
      launchTemplateName: myLaunchTemplate.launchTemplateName as string, //or simply use an existing template name
    },
    vpc,
  },
  computeEnvironmentName: 'MyStorageCapableComputeEnvironment',
});

Importing an existing Compute Environment

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

Below is an example:

const computeEnv = batch.ComputeEnvironment.fromComputeEnvironmentArn(this, '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:

declare const vpc: ec2.Vpc;
const myComputeEnv = new batch.ComputeEnvironment(this, 'ComputeEnv', {
  computeResources: {
    image: new ecs.EcsOptimizedAmi({
      generation: ec2.AmazonLinuxGeneration.AMAZON_LINUX_2,
    }),
    vpc,
  }
});

Custom based AMI example:

declare const vpc: ec2.Vpc;
const myComputeEnv = new batch.ComputeEnvironment(this, 'ComputeEnv', {
  computeResources: {
    image: ec2.MachineImage.genericLinux({
      "[aws-region]": "[ami-ID]",
    }),
    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.

declare const computeEnvironment: batch.ComputeEnvironment;
const jobQueue = new batch.JobQueue(this, 'JobQueue', {
  computeEnvironments: [
    {
      // Defines a collection of compute resources to handle assigned batch jobs
      computeEnvironment,
      // 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:

declare const sharedComputeEnvs: batch.ComputeEnvironment;
const highPrioQueue = new batch.JobQueue(this, 'JobQueue', {
  computeEnvironments: [{
    computeEnvironment: sharedComputeEnvs,
    order: 1,
  }],
  priority: 2,
});

const lowPrioQueue = new batch.JobQueue(this, 'JobQueue', {
  computeEnvironments: [{
    computeEnvironment: sharedComputeEnvs,
    order: 1,
  }],
  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:

const jobQueue = batch.JobQueue.fromJobQueueArn(this, '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:

import * as ecr from '@aws-cdk/aws-ecr';

const repo = ecr.Repository.fromRepositoryName(this, 'batch-job-repo', 'todo-list');

new batch.JobDefinition(this, 'batch-job-def-from-ecr', {
  container: {
    image: new 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.

new batch.JobDefinition(this, 'batch-job-def-from-local', {
  container: {
    // todo-list is a directory containing a Dockerfile to build the application
    image: ecs.ContainerImage.fromAsset('../todo-list'),
  },
});

Providing custom log configuration

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

import * as ssm from '@aws-cdk/aws-ssm';

new batch.JobDefinition(this, 'job-def', {
  container: {
    image: ecs.EcrImage.fromRegistry('docker/whalesay'),
    logConfiguration: {
      logDriver: batch.LogDriver.AWSLOGS,
      options: { 'awslogs-region': 'us-east-1' },
      secretOptions: [
        batch.ExposedSecret.fromParametersStore('xyz', ssm.StringParameter.fromStringParameterName(this, '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:

const job = batch.JobDefinition.fromJobDefinitionArn(this, '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:

// Without revision
const job1 = batch.JobDefinition.fromJobDefinitionName(this, 'imported-job-definition', 'my-job-definition');

// With revision
const job2 = batch.JobDefinition.fromJobDefinitionName(this, 'imported-job-definition', 'my-job-definition:3');

版本与发布记录

@aws-cdk/aws-batch 共发布 288 个版本,首次发布于 2018/07/31;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.204.0latest2023/06/203 年前
1.203.02023/06/013 年前
1.202.02023/05/223 年前
1.201.02023/05/113 年前
1.200.02023/04/273 年前
1.199.02023/04/213 年前

关于 @aws-cdk/aws-batch 的常见问题

@aws-cdk/aws-batch 是什么?

The CDK Construct Library for AWS::Batch注意:该包已被作者标记为弃用——AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html

如何安装 @aws-cdk/aws-batch?

在项目目录运行 npm install @aws-cdk/aws-batch,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@aws-cdk/aws-ec2(1.204.0)、@aws-cdk/aws-ecr(1.204.0)、@aws-cdk/aws-ecs(1.204.0)、@aws-cdk/aws-iam(1.204.0)、@aws-cdk/aws-secretsmanager(1.204.0)、@aws-cdk/aws-ssm(1.204.0)、@aws-cdk/core(1.204.0)、constructs(^3.3.69)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-cdk/aws-batch 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-cdk/aws-batch 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@aws-cdk/aws-batch 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 14.15.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aws-cdk/aws-batch 可以商用吗?

@aws-cdk/aws-batch 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-cdk/aws-batch 的下载量有多少?

根据 npm 官方下载统计,@aws-cdk/aws-batch 在 2026/10/07 – 2026/11/05 这 30 天内被下载 70,621 次,日均约 2,354 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-cdk/aws-batch 还在维护吗?

最新版本 1.204.0 发布于 2023/06/20(3 年前);至今共发布 288 个版本,其中过去 12 个月发布了 0 个;首次发布于 2018/07/31。作者已将其标记为弃用,新项目建议寻找替代方案。