# @aws-cdk/aws-imagebuilder-alpha 中文文档

规范地址：https://npmcn.com/package/%40aws-cdk/aws-imagebuilder-alpha/

版本：2\.275\.0-alpha\.0
npm 元数据更新时间：2026-10-26T19:18:30.495Z
中文译文更新时间：2026-11-07T20:04:52.462Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40aws-cdk/aws-imagebuilder-alpha
原文对照：https://npmcn.com/package/%40aws-cdk/aws-imagebuilder-alpha/?lang=original
项目主页：https://github.com/aws/aws-cdk
源码仓库：https://github.com/aws/aws-cdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：2.5 MB，107 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- Node.js 要求：\>= 20\.0\.0
- 运行依赖：1 个
- peer 依赖：constructs ^10\.5\.0，aws-cdk-lib ^2\.275\.0
- 首次发布：2025-11-13T17:40:23.942Z
- 最新版本发布：2026-10-26T19:18:26.192Z
- 近 30 天下载量：2754（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：63（近 12 个月 63 个）

## 中文简介

EC2 图像构建器的 CDK 构造库

## 安装

```sh
npm install @aws-cdk/aws-imagebuilder-alpha
```

也可以使用：`pnpm add @aws-cdk/aws-imagebuilder-alpha`、`yarn add @aws-cdk/aws-imagebuilder-alpha`、`bun add @aws-cdk/aws-imagebuilder-alpha`

## README

# EC2 图像构建器构建库

* * *

![cdk-constructs: Experimental](https://img.shields.io/badge/cdk--constructs-experimental-important.svg?style=for-the-badge)

> 本单元中更高层次的构件的API是实验性的并正在积极开发中. 在今后任何版本中,它们都须作非背向相容的修改或去除。 这些是 不适用 [语义版本](https://semver.org/) 模型和断开的更改 在发行笔记中宣布. 这意味着虽然你可能使用它们,但可能需要更新 当更新到此软件包的更新版本时,您的源代码.

* * *

这个模块是 [AWS 云开发套件](https://github.com/aws/aws-cdk) 项目.

## 读取

[Amazon EC2 图像构建器](https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html) 是一个 全面管理AWS服务,帮助您实现定制、安全和部署自动化 最新服务器图像. 您可以使用图像构建器创建 Amazon Machine Images (AMI) 和容器图像以供使用 跨AWS地区.

这个模块是 [AWS 云开发套件](https://github.com/aws/aws-cdk) 项目。 它允许您定义 图像构建器管道,图像,食谱,组件,工作流程,以及生命周期政策. 组件定义在图像创建(构建组件)或 测试从创建图像(测试组件)中启动的实例。 组件由声明的YAML或JSON创建 用于描述构建、验证或测试实例的运行时间配置的文档。 构成部分已包括在内 用于图像构建的图像食谱或容器食谱.

EC2 图像构建器支持 AWS 管理的组件,用于共同的任务, AWS 市场组件和自定义组件 那是你们所创造的。 在具体工作流程阶段运行的部件:在建设阶段建设和验证阶段 试验阶段.

### 图像管道

一个图像管道为建造安全的AMI和容器图像提供了自动化框架。 输油管 通过将图像食谱或容器食谱与基础设施相结合,来协调整个图像创建过程 配置和分配配置。 管道可以按时间表运行或手动触发,它们可以管理 自动构建、测试和分配阶段.

#### 图像管道基本使用

创建一个简单的 AMI 管道, 只需一个图像配方 :

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'MyImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  )
});

const imagePipeline = new imagebuilder.ImagePipeline(this, 'MyImagePipeline', {
  recipe: exampleImageRecipe
});
```

创建一个简单的集装箱管道,只配有集装箱配方:

```ts
const containerRecipe = new imagebuilder.ContainerRecipe(this, 'MyContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  )
});

const containerPipeline = new imagebuilder.ImagePipeline(this, 'MyContainerPipeline', {
  recipe: exampleContainerRecipe
});
```

#### 图像管道排程

##### 手动管道执行

创建仅在手动触发时运行的管道 :

```ts
const manualPipeline = new imagebuilder.ImagePipeline(this, 'ManualPipeline', {
  imagePipelineName: 'my-manual-pipeline',
  description: 'Pipeline triggered manually for production builds',
  recipe: exampleImageRecipe
  // No schedule property - manual execution only
});

// Grant Lambda function permission to trigger the pipeline
manualPipeline.grantStartExecution(lambdaRole);
```

##### 自动管道调度

计划使用克龙表达式自动运行的管道 :

```ts
const weeklyPipeline = new imagebuilder.ImagePipeline(this, 'WeeklyPipeline', {
  imagePipelineName: 'weekly-build-pipeline',
  recipe: exampleImageRecipe,
  schedule: {
    expression: events.Schedule.cron({
      minute: '0',
      hour: '6',
      weekDay: 'MON'
    })
  }
});
```

正则间隔使用速率表达式 :

```ts
const dailyPipeline = new imagebuilder.ImagePipeline(this, 'DailyPipeline', {
  recipe: exampleContainerRecipe,
  schedule: {
    expression: events.Schedule.rate(Duration.days(1))
  }
});
```

##### 管道调度配置

配置高级调度选项 :

```ts
const advancedSchedulePipeline = new imagebuilder.ImagePipeline(this, 'AdvancedSchedulePipeline', {
  recipe: exampleImageRecipe,
  schedule: {
    expression: events.Schedule.rate(Duration.days(7)),
    // Only trigger when dependencies are updated (new base images, components, etc.)
    startCondition: imagebuilder.ScheduleStartCondition.EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE,
    // Automatically disable after 3 consecutive failures
    autoDisableFailureCount: 3
  },
  // Start enabled
  status: imagebuilder.ImagePipelineStatus.ENABLED
});
```

#### 图像管道配置

##### 图像管道的基础设施和分布

配置自定义基础设施和发行设置 :

```ts
const infrastructureConfiguration = new imagebuilder.InfrastructureConfiguration(this, 'Infrastructure', {
  infrastructureConfigurationName: 'production-infrastructure',
  instanceTypes: [
    ec2.InstanceType.of(ec2.InstanceClass.COMPUTE7_INTEL, ec2.InstanceSize.LARGE)
  ],
  vpc: vpc,
  subnetSelection: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS }
});

const distributionConfiguration = new imagebuilder.DistributionConfiguration(this, 'Distribution');
distributionConfiguration.addAmiDistributions({
  amiName: 'production-ami-{{ imagebuilder:buildDate }}',
  amiTargetAccountIds: ['123456789012', '098765432109']
});

const productionPipeline = new imagebuilder.ImagePipeline(this, 'ProductionPipeline', {
  recipe: exampleImageRecipe,
  infrastructureConfiguration: infrastructureConfiguration,
  distributionConfiguration: distributionConfiguration
});
```

##### 管道日志配置

为管道和图像日志配置自定义的 Cloud Watch 日志组 :

```ts
const pipelineLogGroup = new logs.LogGroup(this, 'PipelineLogGroup', {
  logGroupName: '/custom/imagebuilder/pipeline/logs',
  retention: logs.RetentionDays.ONE_MONTH
});

const imageLogGroup = new logs.LogGroup(this, 'ImageLogGroup', {
  logGroupName: '/custom/imagebuilder/image/logs',
  retention: logs.RetentionDays.ONE_WEEK
});

const loggedPipeline = new imagebuilder.ImagePipeline(this, 'LoggedPipeline', {
  recipe: exampleImageRecipe,
  imagePipelineLogGroup: pipelineLogGroup,
  imageLogGroup: imageLogGroup
});
```

##### 图像管道中的工作流程集成

在共同管道阶段使用AWS管理的工作流程:

```ts
const workflowPipeline = new imagebuilder.ImagePipeline(this, 'WorkflowPipeline', {
  recipe: exampleImageRecipe,
  workflows: [
    { workflow: imagebuilder.AmazonManagedWorkflow.buildImage(this, 'BuildWorkflow') },
    { workflow: imagebuilder.AmazonManagedWorkflow.testImage(this, 'TestWorkflow') }
  ]
});
```

对于集装箱管道,使用集装箱专用工作流程:

```ts
const containerWorkflowPipeline = new imagebuilder.ImagePipeline(this, 'ContainerWorkflowPipeline', {
  recipe: exampleContainerRecipe,
  workflows: [
    { workflow: imagebuilder.AmazonManagedWorkflow.buildContainer(this, 'BuildContainer') },
    { workflow: imagebuilder.AmazonManagedWorkflow.testContainer(this, 'TestContainer') },
    { workflow: imagebuilder.AmazonManagedWorkflow.distributeContainer(this, 'DistributeContainer') }
  ]
});
```

##### 图像管道的高级特性

配置容器管道的图像扫描 :

```ts
const scanningRepository = new ecr.Repository(this, 'ScanningRepo');

const scannedContainerPipeline = new imagebuilder.ImagePipeline(this, 'ScannedContainerPipeline', {
  recipe: exampleContainerRecipe,
  imageScanningEnabled: true,
  imageScanningEcrRepository: scanningRepository,
  imageScanningEcrTags: ['security-scan', 'latest']
});
```

控制元数据的收集和测试:

```ts
const controlledPipeline = new imagebuilder.ImagePipeline(this, 'ControlledPipeline', {
  recipe: exampleImageRecipe,
  enhancedImageMetadataEnabled: true,  // Collect detailed OS and package info
  imageTestsEnabled: false  // Skip testing phase for faster builds
});
```

#### 图像管道事件

##### 管道事件处理

处理具体的管道活动:

```ts
// Monitor CVE detection
examplePipeline.onCVEDetected('CVEAlert', {
  target: new targets.SnsTopic(topic)
});

// Handle pipeline auto-disable events
examplePipeline.onImagePipelineAutoDisabled('PipelineDisabledAlert', {
  target: new targets.LambdaFunction(lambdaFunction)
});
```

#### 导入图像管道

参考在CDK之外创建的现有管道:

```ts
// Import by name
const existingPipelineByName = imagebuilder.ImagePipeline.fromImagePipelineName(
  this,
  'ExistingPipelineByName',
  'my-existing-pipeline'
);

// Import by ARN
const existingPipelineByArn = imagebuilder.ImagePipeline.fromImagePipelineArn(
  this,
  'ExistingPipelineByArn',
  'arn:aws:imagebuilder:us-east-1:123456789012:image-pipeline/imported-pipeline'
);

// Grant permissions to imported pipelines
const automationRole = new iam.Role(this, 'AutomationRole', {
  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com')
});

existingPipelineByName.grantStartExecution(automationRole);
existingPipelineByArn.grantRead(lambdaRole);
```

### 图像

图像是图像构建器创建的输出资源, 由 AMI 或容器图像加元数据组成, 如 版本、平台和创建细节。 图像作为未来构建的基础图像,可在AWS之间共享 账户。 虽然图像是图像管道处决的输出,但它们也可以以临时方式生成 在管道之外,定义为一个独立的资源.

#### 图像基本使用

从图像配方创建一个简单的基于 AMI 的图像 :

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'MyImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  )
});

const amiImage = new imagebuilder.Image(this, 'MyAmiImage', {
  recipe: imageRecipe
});
```

从容器配方创建简单的容器图像 :

```ts
const containerRecipe = new imagebuilder.ContainerRecipe(this, 'MyContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  )
});

const containerImage = new imagebuilder.Image(this, 'MyContainerImage', {
  recipe: containerRecipe
});
```

#### AWS 管理图像

##### 预定义的 OS 图像

使用 AWS 管理的图像用于常见操作系统 :

```ts
// Amazon Linux 2023 AMI for x86_64
const amazonLinux2023Ami = imagebuilder.AmazonManagedImage.amazonLinux2023(this, 'AmazonLinux2023', {
  imageType: imagebuilder.ImageType.AMI,
  imageArchitecture: imagebuilder.ImageArchitecture.X86_64
});

// Ubuntu 22.04 AMI for ARM64
const ubuntu2204Ami = imagebuilder.AmazonManagedImage.ubuntuServer2204(this, 'Ubuntu2204', {
  imageType: imagebuilder.ImageType.AMI,
  imageArchitecture: imagebuilder.ImageArchitecture.ARM64
});

// Windows Server 2022 Full AMI
const windows2022Ami = imagebuilder.AmazonManagedImage.windowsServer2022Full(this, 'Windows2022', {
  imageType: imagebuilder.ImageType.AMI,
  imageArchitecture: imagebuilder.ImageArchitecture.X86_64
});

// Use as base image in recipe
const managedImageRecipe = new imagebuilder.ImageRecipe(this, 'ManagedImageRecipe', {
  baseImage: amazonLinux2023Ami.toBaseImage()
});
```

##### 自定义 AWS 管理图像

以名称或属性导入 AWS 管理图像 :

```ts
// Import by name
const managedImageByName = imagebuilder.AmazonManagedImage.fromAmazonManagedImageName(
  this,
  'ManagedImageByName',
  'amazon-linux-2023-x86'
);

// Import by attributes with specific version
const managedImageByAttributes = imagebuilder.AmazonManagedImage.fromAmazonManagedImageAttributes(this, 'ManagedImageByAttributes', {
  imageName: 'ubuntu-server-22-lts-x86',
  imageVersion: '2024.11.25'
});
```

#### 图像配置

##### 基础设施与图像分布

配置自定义基础设施和发行设置 :

```ts
const infrastructureConfiguration = new imagebuilder.InfrastructureConfiguration(this, 'Infrastructure', {
  infrastructureConfigurationName: 'production-infrastructure',
  instanceTypes: [
    ec2.InstanceType.of(ec2.InstanceClass.COMPUTE7_INTEL, ec2.InstanceSize.LARGE)
  ],
  vpc: vpc,
  subnetSelection: { subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS }
});

const distributionConfiguration = new imagebuilder.DistributionConfiguration(this, 'Distribution');
distributionConfiguration.addAmiDistributions({
  amiName: 'production-ami-{{ imagebuilder:buildDate }}',
  amiTargetAccountIds: ['123456789012', '098765432109']
});

const productionImage = new imagebuilder.Image(this, 'ProductionImage', {
  recipe: exampleImageRecipe,
  infrastructureConfiguration: infrastructureConfiguration,
  distributionConfiguration: distributionConfiguration
});
```

##### 日志配置

配置图像的自定义云表日志组 :

```ts
const logGroup = new logs.LogGroup(this, 'ImageLogGroup', {
  logGroupName: '/custom/imagebuilder/image/logs',
  retention: logs.RetentionDays.ONE_MONTH
});

const loggedImage = new imagebuilder.Image(this, 'LoggedImage', {
  recipe: exampleImageRecipe,
  logGroup: logGroup
});
```

##### 图像中的工作流程集成

使用工作流程进行自定义构建、测试和分发过程:

```ts
const imageWithWorkflows = new imagebuilder.Image(this, 'ImageWithWorkflows', {
  recipe: exampleImageRecipe,
  workflows: [
    { workflow: imagebuilder.AmazonManagedWorkflow.buildImage(this, 'BuildWorkflow') },
    { workflow: imagebuilder.AmazonManagedWorkflow.testImage(this, 'TestWorkflow') }
  ]
});
```

##### 图像中的高级特性

配置图像扫描、元数据采集和测试 :

```ts
const scanningRepository = new ecr.Repository(this, 'ScanningRepository');

const advancedContainerImage = new imagebuilder.Image(this, 'AdvancedContainerImage', {
  recipe: exampleContainerRecipe,
  imageScanningEnabled: true,
  imageScanningEcrRepository: scanningRepository,
  imageScanningEcrTags: ['security-scan', 'latest'],
  enhancedImageMetadataEnabled: true,
  imageTestsEnabled: false  // Skip testing for faster builds
});
```

#### 导入图像

引用在 CDK 外部创建的现有图像 :

```ts
// Import by name
const existingImageByName = imagebuilder.Image.fromImageName(
  this,
  'ExistingImageByName',
  'my-existing-image'
);

// Import by ARN
const existingImageByArn = imagebuilder.Image.fromImageArn(
  this,
  'ExistingImageByArn',
  'arn:aws:imagebuilder:us-east-1:123456789012:image/imported-image/1.0.0'
);

// Import by attributes
const existingImageByAttributes = imagebuilder.Image.fromImageAttributes(this, 'ExistingImageByAttributes', {
  imageName: 'shared-base-image',
  imageVersion: '2024.11.25'
});

// Grant permissions to imported images
const role = new iam.Role(this, 'ImageAccessRole', {
  assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com')
});

existingImageByName.grantRead(role);
existingImageByArn.grant(role, 'imagebuilder:GetImage', 'imagebuilder:ListImagePackages');
```

### 图像辅助工具

#### 图像辅助基本用途

创建带有所需底图的图像配方 :

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'MyImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  )
});
```

#### 图像辅助基础图像

要创建食谱,必须选择一个基础图像来构建和自定义. 此基本图像可以从 各种来源,例如来自SSM参数,AWS Marketplace产品,以及AMI ID直接.

##### SSM 参数

使用 SSM 参数引用 :

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'SsmImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  )
});

// Using an SSM parameter construct
const parameter = ssm.StringParameter.fromStringParameterName(
  this,
  'BaseImageParameter',
  '/aws/service/ami-windows-latest/Windows_Server-2022-English-Full-Base'
);
const windowsRecipe = new imagebuilder.ImageRecipe(this, 'WindowsImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameter(parameter)
});
```

##### AMI 身份证

当您有特定AMI时:

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'AmiImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromAmiId('ami-12345678')
});
```

##### 市场图像

对于市场基础图像:

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'MarketplaceImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromMarketplaceProductId('prod-1234567890abcdef0')
});
```

#### 图像辅助组件

各种来源的部件,如自订、AWS自有或AWS市场自有等,可选列入 在食谱。 对于参数化的组件,您可以提供食谱中使用的参数,即: 执行组件时在图像构建中应用.

##### 自定义图像食谱中的组件

在配方中添加您自己的组件 :

```ts
const customComponent = new imagebuilder.Component(this, 'MyComponent', {
  platform: imagebuilder.Platform.LINUX,
  data: imagebuilder.ComponentData.fromJsonObject({
    schemaVersion: imagebuilder.ComponentSchemaVersion.V1_0,
    phases: [
      {
        name: imagebuilder.ComponentPhaseName.BUILD,
        steps: [
          {
            name: 'install-app',
            action: imagebuilder.ComponentAction.EXECUTE_BASH,
            inputs: {
              commands: ['yum install -y my-application']
            }
          }
        ]
      }
    ]
  })
});

const imageRecipe = new imagebuilder.ImageRecipe(this, 'ComponentImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  ),
  components: [
    {
      component: customComponent
    }
  ]
});
```

##### 图像配方中的 AWS 管理部件

使用预建的 AWS 组件 :

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'AmazonManagedImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  ),
  components: [
    {
      component: imagebuilder.AmazonManagedComponent.updateOs(this, 'UpdateOS', {
        platform: imagebuilder.Platform.LINUX
      })
    },
    {
      component: imagebuilder.AmazonManagedComponent.awsCliV2(this, 'AwsCli', {
        platform: imagebuilder.Platform.LINUX
      })
    }
  ]
});
```

##### 图像食谱中的组件参数

传递参数到接受它们的组件:

```ts
const parameterizedComponent = imagebuilder.Component.fromComponentName(
  this,
  'ParameterizedComponent',
  'my-parameterized-component'
);

const imageRecipe = new imagebuilder.ImageRecipe(this, 'ParameterizedImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  ),
  components: [
    {
      component: parameterizedComponent,
      parameters: {
        environment: imagebuilder.ComponentParameterValue.fromString('production'),
        version: imagebuilder.ComponentParameterValue.fromString('1.0.0')
      }
    }
  ]
});
```

#### 图像辅助配置

##### 块设备配置

配置构建实例的存储 :

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'BlockDeviceImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  ),
  blockDevices: [
    {
      deviceName: '/dev/sda1',
      volume: ec2.BlockDeviceVolume.ebs(100, {
        encrypted: true,
        volumeType: ec2.EbsDeviceVolumeType.GENERAL_PURPOSE_SSD_GP3
      })
    }
  ]
});
```

##### AMI 拖线

标记输出 AMI :

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'TaggedImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  ),
  amiTags: {
    Environment: 'Production',
    Application: 'WebServer',
    Owner: 'DevOps Team'
  }
});
```

### 集装箱配料

容器食谱与图像食谱相类似,但具体适用于容器图像。 它定义了底容器 图像和组件用于为输出容器图像制作所需的配置。 集装箱食谱工作 以多克克从多克Hub,亚马逊ECR,或亚马逊管理的容器图像为起点.

#### 集装箱辅助工具基本用途

创建包含所需底图和目标存储器的容器食谱 :

```ts
const containerRecipe = new imagebuilder.ContainerRecipe(this, 'MyContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  )
});
```

#### 容器辅助工具基础图像

##### DockerHub 图像

使用公共多克枢纽图像 :

```ts
const containerRecipe = new imagebuilder.ContainerRecipe(this, 'DockerHubContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  )
});
```

##### ECR 图像

使用您自己的 ECR 寄存器中的图像 :

```ts
const sourceRepo = ecr.Repository.fromRepositoryName(this, 'SourceRepo', 'my-base-image');
const targetRepo = ecr.Repository.fromRepositoryName(this, 'TargetRepo', 'my-container-repo');

const containerRecipe = new imagebuilder.ContainerRecipe(this, 'EcrContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromEcr(sourceRepo, '1.0.0'),
  targetRepository: imagebuilder.Repository.fromEcr(targetRepo)
});
```

##### ECR 公共图像

使用 Amazon ECR Public 的图像 :

```ts
const containerRecipe = new imagebuilder.ContainerRecipe(this, 'EcrPublicContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromEcrPublic('amazonlinux', 'amazonlinux', '2023'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  )
});
```

#### 容器辅助部件

##### 集装箱食谱中的自定义组件

在容器配方中添加您自己的组件 :

```ts
const customComponent = new imagebuilder.Component(this, 'MyComponent', {
  platform: imagebuilder.Platform.LINUX,
  data: imagebuilder.ComponentData.fromJsonObject({
    schemaVersion: imagebuilder.ComponentSchemaVersion.V1_0,
    phases: [
      {
        name: imagebuilder.ComponentPhaseName.BUILD,
        steps: [
          {
            name: 'install-app',
            action: imagebuilder.ComponentAction.EXECUTE_BASH,
            inputs: {
              commands: ['yum install -y my-container-application']
            }
          }
        ]
      }
    ]
  })
});

const containerRecipe = new imagebuilder.ContainerRecipe(this, 'ComponentContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  ),
  components: [
    {
      component: customComponent
    }
  ]
});
```

##### 集装箱食谱中的AWS-管理部件

使用预建的 AWS 组件 :

```ts
const containerRecipe = new imagebuilder.ContainerRecipe(this, 'AmazonManagedContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  ),
  components: [
    {
      component: imagebuilder.AmazonManagedComponent.updateOs(this, 'UpdateOS', {
        platform: imagebuilder.Platform.LINUX
      })
    },
    {
      component: imagebuilder.AmazonManagedComponent.awsCliV2(this, 'AwsCli', {
        platform: imagebuilder.Platform.LINUX
      })
    }
  ]
});
```

#### 容器辅助配置

##### 自定义嵌入文件

提供您自己的 Docker 文件模板 :

```ts
const containerRecipe = new imagebuilder.ContainerRecipe(this, 'CustomDockerfileContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  ),
  dockerfile: imagebuilder.DockerfileData.fromInline(`
FROM {{{ imagebuilder:parentImage }}}
CMD ["echo", "Hello, world!"]
{{{ imagebuilder:environments }}}
{{{ imagebuilder:components }}}
`)
});
```

##### 实例配置

配置构建实例 :

```ts
const containerRecipe = new imagebuilder.ContainerRecipe(this, 'InstanceConfigContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  ),
  // Custom ECS-optimized AMI for building
  instanceImage: imagebuilder.ContainerInstanceImage.fromSsmParameterName(
    '/aws/service/ecs/optimized-ami/amazon-linux-2023/recommended/image_id'
  ),
  // Additional storage for build process
  instanceBlockDevices: [
    {
      deviceName: '/dev/xvda',
      volume: ec2.BlockDeviceVolume.ebs(50, {
        encrypted: true,
        volumeType: ec2.EbsDeviceVolumeType.GENERAL_PURPOSE_SSD_GP3
      })
    }
  ]
});
```

### 构成部分

组件定义在图像创建(构建组件)或 测试从创建图像(测试组件)中启动的实例。 组件由声明的YAML或JSON创建 用于描述构建、验证或测试实例的运行时间配置的文档。 构成部分已包括在内 用于图像构建的图像食谱或容器食谱.

EC2 图像构建器支持 AWS 管理的组件,用于共同的任务, AWS 市场组件和自定义组件 那是你们所创造的。 在具体工作流程阶段运行的部件:在建设阶段建设和验证阶段 试验阶段.

#### 基本组件使用量

创建一个具有所需属性的组件:平台和组件数据.

```ts
const component = new imagebuilder.Component(this, 'MyComponent', {
  platform: imagebuilder.Platform.LINUX,
  data: imagebuilder.ComponentData.fromJsonObject({
    schemaVersion: imagebuilder.ComponentSchemaVersion.V1_0,
    phases: [
      {
        name: imagebuilder.ComponentPhaseName.BUILD,
        steps: [
          {
            name: 'install-app',
            action: imagebuilder.ComponentAction.EXECUTE_BASH,
            inputs: {
              commands: ['echo "Installing my application..."', 'yum update -y'],
            },
          },
        ],
      },
    ],
  }),
});
```

#### 数据来源

##### 内置组件数据

使用 `ComponentData.fromInline()` 用于现有YAML/JSON定义:

```ts
const component = new imagebuilder.Component(this, 'InlineComponent', {
  platform: imagebuilder.Platform.LINUX,
  data: imagebuilder.ComponentData.fromInline(`
name: my-component
schemaVersion: 1.0
phases:
  - name: build
    steps:
      - name: update-os
        action: ExecuteBash
        inputs:
          commands: ['yum update -y']
`)
});
```

##### JSON 对象组件数据

使用对象的大多数开发者友好方法:

```ts

const component = new imagebuilder.Component(this, 'JsonComponent', {
  platform: imagebuilder.Platform.LINUX,
  data: imagebuilder.ComponentData.fromJsonObject({
    schemaVersion: imagebuilder.ComponentSchemaVersion.V1_0,
    phases: [
      {
        name: imagebuilder.ComponentPhaseName.BUILD,
        steps: [
          {
            name: 'configure-app',
            action: imagebuilder.ComponentAction.CREATE_FILE,
            inputs: {
              path: '/etc/myapp/config.json',
              content: '{"env": "production"}'
            }
          }
        ]
      }
    ]
  })
});
```

##### 结构化组件文档

对于类型安全,CDK-内在定义具有增强属性,例如: `timeout` 财务报告和审定财务报表 `onFailure`。 。 。 .

###### 定义组成部分步骤

您可以定义组件中的步骤, 当组件被应用时将执行 :

```ts
const step: imagebuilder.ComponentDocumentStep = {
  name: 'configure-app',
  action: imagebuilder.ComponentAction.CREATE_FILE,
  inputs: imagebuilder.ComponentStepInputs.fromObject({
    path: '/etc/myapp/config.json',
    content: '{"env": "production"}'
  })
};
```

###### 界定构成部分阶段

相位组合步骤,在组件中构建、验证或测试时按顺序运行:

```ts
const phase: imagebuilder.ComponentDocumentPhase = {
  name: imagebuilder.ComponentPhaseName.BUILD,
  steps: [
    {
      name: 'configure-app',
      action: imagebuilder.ComponentAction.CREATE_FILE,
      inputs: imagebuilder.ComponentStepInputs.fromObject({
        path: '/etc/myapp/config.json',
        content: '{"env": "production"}'
      })
    }
  ]
};
```

###### 定义一个组件

组成部分数据界定了在所提供阶段中执行的所有步骤:

```ts
const component = new imagebuilder.Component(this, 'StructuredComponent', {
  platform: imagebuilder.Platform.LINUX,
  data: imagebuilder.ComponentData.fromComponentDocumentJsonObject({
    schemaVersion: imagebuilder.ComponentSchemaVersion.V1_0,
    phases: [
      {
        name: imagebuilder.ComponentPhaseName.BUILD,
        steps: [
          {
            name: 'install-with-timeout',
            action: imagebuilder.ComponentAction.EXECUTE_BASH,
            timeout: Duration.minutes(10),
            onFailure: imagebuilder.ComponentOnFailure.CONTINUE,
            inputs: imagebuilder.ComponentStepInputs.fromObject({
              commands: ['./install-script.sh']
            })
          }
        ]
      }
    ]
  })
});
```

##### S3 组件数据

您想要上传或已经上传到 S3 的组件 :

```ts
// Upload a local file
const componentFromAsset = new imagebuilder.Component(this, 'AssetComponent', {
  platform: imagebuilder.Platform.LINUX,
  data: imagebuilder.ComponentData.fromAsset(this, 'ComponentAsset', './my-component.yml'),
});

// Reference an existing S3 object
const bucket = s3.Bucket.fromBucketName(this, 'ComponentBucket', 'my-components-bucket');
const componentFromS3 = new imagebuilder.Component(this, 'S3Component', {
  platform: imagebuilder.Platform.LINUX,
  data: imagebuilder.ComponentData.fromS3(bucket, 'components/my-component.yml'),
});
```

#### 用 KMS 密钥加密组件数据

您可以用 KMS 密钥加密组件数据, 这样只有能够用密钥解密的主机才能 访问组件数据.

```ts
const component = new imagebuilder.Component(this, 'EncryptedComponent', {
  platform: imagebuilder.Platform.LINUX,
  kmsKey: new kms.Key(this, 'ComponentKey'),
  data: imagebuilder.ComponentData.fromJsonObject({
    schemaVersion: imagebuilder.ComponentSchemaVersion.V1_0,
    phases: [
      {
        name: imagebuilder.ComponentPhaseName.BUILD,
        steps: [
          {
            name: 'secure-setup',
            action: imagebuilder.ComponentAction.EXECUTE_BASH,
            inputs: {
              commands: ['echo "This component data is encrypted with KMS"']
            }
          }
        ]
      }
    ]
  })
});
```

#### AWS 管理的组件

AWS为共同的任务提供一套管理下的组件:

```ts
// Install AWS CLI v2
const awsCliComponent = imagebuilder.AmazonManagedComponent.awsCliV2(this, 'AwsCli', {
  platform: imagebuilder.Platform.LINUX
});

// Update the operating system
const updateComponent = imagebuilder.AmazonManagedComponent.updateOs(this, 'UpdateOS', {
  platform: imagebuilder.Platform.LINUX
});

// Reference any AWS-managed component by name
const customAwsComponent = imagebuilder.AmazonManagedComponent.fromAmazonManagedComponentName(
  this,
  'CloudWatchAgent',
  'amazon-cloudwatch-agent-linux'
);
```

#### AWS 市场组件

您可以使用市场组件名称及其产品标识来参考 AWS Marketplace 组件:

```ts
const marketplaceComponent = imagebuilder.AwsMarketplaceComponent.fromAwsMarketplaceComponentAttributes(
  this,
  'MarketplaceComponent',
  {
    componentName: 'my-marketplace-component',
    marketplaceProductId: 'prod-1234567890abcdef0',
  }
);
```

### 基础设施配置

基础设施配置定义图像构建中使用的计算资源和环境设置 进程。 这包括实例类型、IAM实例描述、VPC设置、子网、安全组、SNS专题 通知、 日志配置和排除出故障设置, 如失败时是否终止事件或 保持它们运行调试。 这些设置被应用到图像或图像管道中的构建中.

```ts
const infrastructureConfiguration = new imagebuilder.InfrastructureConfiguration(this, 'InfrastructureConfiguration', {
  infrastructureConfigurationName: 'test-infrastructure-configuration',
  description: 'An Infrastructure Configuration',
  // Optional - instance types to use for build/test
  instanceTypes: [
    ec2.InstanceType.of(ec2.InstanceClass.STANDARD7_INTEL, ec2.InstanceSize.LARGE),
    ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3, ec2.InstanceSize.LARGE)
  ],
  // Optional - create an instance profile with necessary permissions
  instanceProfile: new iam.InstanceProfile(this, 'InstanceProfile', {
    instanceProfileName: 'test-instance-profile',
    role: new iam.Role(this, 'InstanceProfileRole', {
      assumedBy: iam.ServicePrincipal.fromStaticServicePrincipleName('ec2.amazonaws.com'),
      managedPolicies: [
        iam.ManagedPolicy.fromAwsManagedPolicyName('AmazonSSMManagedInstanceCore'),
        iam.ManagedPolicy.fromAwsManagedPolicyName('EC2InstanceProfileForImageBuilder')
      ]
    })
  }),
  // Use VPC network configuration
  vpc,
  subnetSelection: { subnetType: ec2.SubnetType.PUBLIC },
  securityGroups: [ec2.SecurityGroup.fromSecurityGroupId(this, 'SecurityGroup', vpc.vpcDefaultSecurityGroup)],
  keyPair: ec2.KeyPair.fromKeyPairName(this, 'KeyPair', 'imagebuilder-instance-key-pair'),
  terminateInstanceOnFailure: true,
  // Optional - IMDSv2 settings
  httpTokens: imagebuilder.HttpTokens.REQUIRED,
  httpPutResponseHopLimit: 1,
  // Optional - publish image completion messages to an SNS topic
  notificationTopic: sns.Topic.fromTopicArn(
    this,
    'Topic',
    this.formatArn({ service: 'sns', resource: 'image-builder-topic' })
  ),
  // Optional - log settings. Logging is enabled by default
  logging: {
    s3Bucket: s3.Bucket.fromBucketName(this, 'LogBucket', `imagebuilder-logging-${Aws.ACCOUNT_ID}`),
    s3KeyPrefix: 'imagebuilder-logs'
  },
  // Optional - host placement settings
  ec2InstanceAvailabilityZone: Stack.of(this).availabilityZones[0],
  ec2InstanceHostId: dedicatedHost.attrHostId,
  ec2InstanceTenancy: imagebuilder.Tenancy.HOST,
  resourceTags: {
    Environment: 'production'
  }
});
```

### 分发配置

发行配置定义了您的已建图像在成功创建后如何和在哪里分布 。 对于AMIS, 这包括目标AWS区域、KMS加密密钥、账户共享权限、许可证管理者协会以及 发射模板配置. 对于容器图像,它具体规定了跨区域的亚马逊ECR存储器的目标. 分布配置可以与图像或图像管道相接,以定义这些分布设置 用于图像构建.

#### AMI 分发

AMI分布可以被定义为复制和修改不同账户和区域的AMI,并将其应用来启动 模板、 SSM 参数等:

```ts
const distributionConfiguration = new imagebuilder.DistributionConfiguration(this, 'DistributionConfiguration', {
  distributionConfigurationName: 'test-distribution-configuration',
  description: 'A Distribution Configuration',
  amiDistributions: [
    {
      // Distribute AMI to us-east-2 and publish the AMI ID to an SSM parameter
      region: 'us-east-2',
      ssmParameters: [
        {
          parameter: ssm.StringParameter.fromStringParameterAttributes(this, 'CrossRegionParameter', {
            parameterName: '/imagebuilder/ami',
            forceDynamicReference: true
          })
        }
      ]
    }
  ]
});

// For AMI-based image builds - add an AMI distribution in the current region
distributionConfiguration.addAmiDistributions({
  amiName: 'imagebuilder-{{ imagebuilder:buildDate }}',
  amiDescription: 'Build AMI',
  amiKmsKey: kms.Key.fromLookup(this, 'ComponentKey', { aliasName: 'alias/distribution-encryption-key' }),
  // Copy the AMI to different accounts
  amiTargetAccountIds: ['123456789012', '098765432109'],
  // Add launch permissions on the AMI
  amiLaunchPermission: {
    organizationArns: [
      this.formatArn({ region: '', service: 'organizations', resource: 'organization', resourceName: 'o-1234567abc' })
    ],
    organizationalUnitArns: [
      this.formatArn({
        region: '',
        service: 'organizations',
        resource: 'ou',
        resourceName: 'o-1234567abc/ou-a123-b4567890'
      })
    ],
    isPublicUserGroup: true,
    accountIds: ['234567890123']
  },
  // Attach tags to the AMI
  amiTags: {
    Environment: 'production',
    Version: '{{ imagebuilder:buildVersion }}'
  },
  // Optional - publish the distributed AMI ID to an SSM parameter
  ssmParameters: [
    {
      parameter: ssm.StringParameter.fromStringParameterAttributes(this, 'Parameter', {
        parameterName: '/imagebuilder/ami',
        forceDynamicReference: true
      })
    },
    {
      amiAccount: '098765432109',
      dataType: ssm.ParameterDataType.TEXT,
      parameter: ssm.StringParameter.fromStringParameterAttributes(this, 'CrossAccountParameter', {
        parameterName: 'imagebuilder-prod-ami',
        forceDynamicReference: true
      })
    }
  ],
  // Optional - create a new launch template version with the distributed AMI ID
  launchTemplates: [
    {
      launchTemplate: ec2.LaunchTemplate.fromLaunchTemplateAttributes(this, 'LaunchTemplate', {
        launchTemplateId: 'lt-1234'
      }),
      setDefaultVersion: true
    },
    {
      accountId: '123456789012',
      launchTemplate: ec2.LaunchTemplate.fromLaunchTemplateAttributes(this, 'CrossAccountLaunchTemplate', {
        launchTemplateId: 'lt-5678'
      }),
      setDefaultVersion: true
    }
  ],
  // Optional - enable Fast Launch on an imported launch template
  fastLaunchConfigurations: [
    {
      enabled: true,
      launchTemplate: ec2.LaunchTemplate.fromLaunchTemplateAttributes(this, 'FastLaunchLT', {
        launchTemplateName: 'fast-launch-lt'
      }),
      maxParallelLaunches: 10,
      targetSnapshotCount: 2
    }
  ],
  // Optional - license configurations to apply to the AMI
  licenseConfigurationArns: [
    'arn:aws:license-manager:us-west-2:123456789012:license-configuration:lic-abcdefghijklmnopqrstuvwxyz'
  ]
});
```

#### 集装箱销售

##### 集装箱存放处

可以配置容器分发器,以分发给ECR寄存器:

```ts
const ecrRepository = ecr.Repository.fromRepositoryName(this, 'ECRRepository', 'my-repo');
const imageBuilderRepository = imagebuilder.Repository.fromEcr(ecrRepository);
```

##### 界定容器的分布

您可以配置容器寄存器以及适用于所分发容器的描述和标记 图像 :

```ts
const ecrRepository = ecr.Repository.fromRepositoryName(this, 'ECRRepository', 'my-repo');
const containerRepository = imagebuilder.Repository.fromEcr(ecrRepository);
const containerDistributionConfiguration = new imagebuilder.DistributionConfiguration(
  this,
  'ContainerDistributionConfiguration'
);

containerDistributionConfiguration.addContainerDistributions({
  containerRepository,
  containerDescription: 'Test container image',
  containerTags: ['latest', 'latest-1.0']
});
```

### 工作流程

工作流定义了图像构建器在图像创建过程中所执行的步骤的顺序. 有三个工作流程 类型: BUILD(图像建筑)、TEST(测试图像)和分发(分发容器图像).

#### 基本工作流程使用情况

创建具有所需属性的工作流程:工作流程类型和工作流程数据.

```ts
const workflow = new imagebuilder.Workflow(this, 'MyWorkflow', {
  workflowType: imagebuilder.WorkflowType.BUILD,
  data: imagebuilder.WorkflowData.fromJsonObject({
    schemaVersion: imagebuilder.WorkflowSchemaVersion.V1_0,
    steps: [
      {
        name: 'LaunchBuildInstance',
        action: imagebuilder.WorkflowAction.LAUNCH_INSTANCE,
        onFailure: imagebuilder.WorkflowOnFailure.ABORT,
        inputs: {
          waitFor: 'ssmAgent',
        },
      },
      {
        name: 'ExecuteComponents',
        action: imagebuilder.WorkflowAction.EXECUTE_COMPONENTS,
        onFailure: imagebuilder.WorkflowOnFailure.ABORT,
        inputs: {
          'instanceId': 'i-123',
        },
      },
      {
        name: 'CreateImage',
        action: imagebuilder.WorkflowAction.CREATE_IMAGE,
        onFailure: imagebuilder.WorkflowOnFailure.ABORT,
        inputs: {
          'instanceId': 'i-123',
        },
      },
      {
        name: 'TerminateInstance',
        action: imagebuilder.WorkflowAction.TERMINATE_INSTANCE,
        onFailure: imagebuilder.WorkflowOnFailure.CONTINUE,
        inputs: {
          'instanceId': 'i-123',
        },
      },
    ],
    outputs: [
      {
        name: 'ImageId',
        value: '$.stepOutputs.CreateImage.imageId',
      },
    ],
  }),
});
```

#### 工作流程数据源

##### 内置工作流程数据

使用 `WorkflowData.fromInline()` 用于现有YAML/JSON定义:

```ts
const workflow = new imagebuilder.Workflow(this, 'InlineWorkflow', {
  workflowType: imagebuilder.WorkflowType.TEST,
  data: imagebuilder.WorkflowData.fromInline(`
schemaVersion: 1.0
steps:
  - name: LaunchTestInstance
    action: LaunchInstance
    onFailure: Abort
    inputs:
      waitFor: ssmAgent
  - name: RunTests
    action: RunCommand
    onFailure: Abort
    inputs:
      instanceId.$: "$.stepOutputs.LaunchTestInstance.instanceId"
      commands: ['./run-tests.sh']
  - name: TerminateTestInstance
    action: TerminateInstance
    onFailure: Continue
    inputs:
      instanceId.$: "$.stepOutputs.LaunchTestInstance.instanceId"
`),
});
```

##### JSON 对象工作流程数据

使用 JavaScript 对象的大多数开发者友好方法 :

```ts
const workflow = new imagebuilder.Workflow(this, 'JsonWorkflow', {
  workflowType: imagebuilder.WorkflowType.BUILD,
  data: imagebuilder.WorkflowData.fromJsonObject({
    schemaVersion: imagebuilder.WorkflowSchemaVersion.V1_0,
    steps: [
      {
        name: 'LaunchBuildInstance',
        action: imagebuilder.WorkflowAction.LAUNCH_INSTANCE,
        onFailure: imagebuilder.WorkflowOnFailure.ABORT,
        inputs: {
          waitFor: 'ssmAgent'
        }
      },
      {
        name: 'ExecuteComponents',
        action: imagebuilder.WorkflowAction.EXECUTE_COMPONENTS,
        onFailure: imagebuilder.WorkflowOnFailure.ABORT,
        inputs: {
          'instanceId': 'i-123'
        }
      },
      {
        name: 'CreateImage',
        action: imagebuilder.WorkflowAction.CREATE_IMAGE,
        onFailure: imagebuilder.WorkflowOnFailure.ABORT,
        inputs: {
          'instanceId': 'i-123'
        }
      },
      {
        name: 'TerminateInstance',
        action: imagebuilder.WorkflowAction.TERMINATE_INSTANCE,
        onFailure: imagebuilder.WorkflowOnFailure.CONTINUE,
        inputs: {
          'instanceId': 'i-123'
        }
      }
    ],
    outputs: [
      {
        name: 'ImageId',
        value: '$.stepOutputs.CreateImage.imageId'
      }
    ]
  })
});
```

##### S3 工作流程数据

对于您要上传或已经上传到 S3 的工作流程 :

```ts
// Upload a local file
const workflowFromAsset = new imagebuilder.Workflow(this, 'AssetWorkflow', {
  workflowType: imagebuilder.WorkflowType.BUILD,
  data: imagebuilder.WorkflowData.fromAsset(this, 'WorkflowAsset', './my-workflow.yml'),
});

// Reference an existing S3 object
const bucket = s3.Bucket.fromBucketName(this, 'WorkflowBucket', 'my-workflows-bucket');
const workflowFromS3 = new imagebuilder.Workflow(this, 'S3Workflow', {
  workflowType: imagebuilder.WorkflowType.BUILD,
  data: imagebuilder.WorkflowData.fromS3(bucket, 'workflows/my-workflow.yml'),
});
```

#### 用 KMS 密钥加密工作流程数据

您可以用 KMS 密钥加密工作流程数据, 这样只有能够使用密钥解密的主机才能 访问工作流程数据.

```ts
const workflow = new imagebuilder.Workflow(this, 'EncryptedWorkflow', {
  workflowType: imagebuilder.WorkflowType.BUILD,
  kmsKey: new kms.Key(this, 'WorkflowKey'),
  data: imagebuilder.WorkflowData.fromJsonObject({
    schemaVersion: imagebuilder.WorkflowSchemaVersion.V1_0,
    steps: [
      {
        name: 'LaunchBuildInstance',
        action: imagebuilder.WorkflowAction.LAUNCH_INSTANCE,
        onFailure: imagebuilder.WorkflowOnFailure.ABORT,
        inputs: {
          waitFor: 'ssmAgent',
        },
      },
      {
        name: 'CreateImage',
        action: imagebuilder.WorkflowAction.CREATE_IMAGE,
        onFailure: imagebuilder.WorkflowOnFailure.ABORT,
        inputs: {
          'instanceId': 'i-123',
        },
      },
      {
        name: 'TerminateInstance',
        action: imagebuilder.WorkflowAction.TERMINATE_INSTANCE,
        onFailure: imagebuilder.WorkflowOnFailure.CONTINUE,
        inputs: {
          'instanceId': 'i-123',
        },
      },
    ],
    outputs: [
      {
        name: 'ImageId',
        value: '$.stepOutputs.CreateImage.imageId',
      },
    ],
  }),
});
```

#### AWS-管理的工作流量

AWS为常见情景提供一系列工作流程:

```ts
// Build workflows
const buildImageWorkflow = imagebuilder.AmazonManagedWorkflow.buildImage(this, 'BuildImage');
const buildContainerWorkflow = imagebuilder.AmazonManagedWorkflow.buildContainer(this, 'BuildContainer');

// Test workflows  
const testImageWorkflow = imagebuilder.AmazonManagedWorkflow.testImage(this, 'TestImage');
const testContainerWorkflow = imagebuilder.AmazonManagedWorkflow.testContainer(this, 'TestContainer');

// Distribution workflows
const distributeContainerWorkflow = imagebuilder.AmazonManagedWorkflow.distributeContainer(this, 'DistributeContainer');
```

### 生命周期政策

生命周期政策帮助您自动管理图像构建器资源的保存和清理. 这些政策 定义规则,以贬低或删除旧图像版本、管理AMI快照和控制资源成本 根据年龄、数量或其他标准删除未使用的图像.

#### 生命周期政策

创建生命周期策略, 在30天后自动删除旧的 AMI 图像 :

```ts
const lifecyclePolicy = new imagebuilder.LifecyclePolicy(this, 'MyLifecyclePolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.AMI_IMAGE,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { ageFilter: { age: Duration.days(30) } }
    }
  ],
  resourceSelection: {
    tags: { Environment: 'development' }
  }
});
```

创建一个生命周期政策,只保存10个最新的容器图像:

```ts
const containerLifecyclePolicy = new imagebuilder.LifecyclePolicy(this, 'ContainerLifecyclePolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.CONTAINER_IMAGE,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { countFilter: { count: 10 } }
    }
  ],
  resourceSelection: {
    tags: { Application: 'web-app' }
  }
});
```

#### 生命周期政策资源选择

##### 基于标记的资源选择

对带有特定标签的图像应用生命周期政策 :

```ts
const tagBasedPolicy = new imagebuilder.LifecyclePolicy(this, 'TagBasedPolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.AMI_IMAGE,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { ageFilter: { age: Duration.days(90) } }
    }
  ],
  resourceSelection: {
    tags: {
      Environment: 'staging',
      Team: 'backend'
    }
  }
});
```

##### 基于食谱的资源选择

对特定图像或容器配方采用生命周期政策:

```ts
const imageRecipe = new imagebuilder.ImageRecipe(this, 'MyImageRecipe', {
  baseImage: imagebuilder.BaseImage.fromSsmParameterName(
    '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
  )
});

const containerRecipe = new imagebuilder.ContainerRecipe(this, 'MyContainerRecipe', {
  baseImage: imagebuilder.BaseContainerImage.fromDockerHub('amazonlinux', 'latest'),
  targetRepository: imagebuilder.Repository.fromEcr(
    ecr.Repository.fromRepositoryName(this, 'Repository', 'my-container-repo')
  )
});

const recipeBasedPolicy = new imagebuilder.LifecyclePolicy(this, 'RecipeBasedPolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.AMI_IMAGE,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { countFilter: { count: 5 } }
    }
  ],
  resourceSelection: {
    recipes: [imageRecipe, containerRecipe]
  }
});
```

#### 生命周期政策规则

##### 年龄规则

删除超过特定时间段的图像 :

```ts
const ageBasedPolicy = new imagebuilder.LifecyclePolicy(this, 'AgeBasedPolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.AMI_IMAGE,
  details: [
    {
      action: {
        type: imagebuilder.LifecyclePolicyActionType.DELETE,
        includeAmis: true,
        includeSnapshots: true
      },
      filter: {
        ageFilter: {
          age: Duration.days(60),
          retainAtLeast: 3  // Always keep at least 3 images
        }
      }
    }
  ],
  resourceSelection: {
    tags: { Environment: 'testing' }
  }
});
```

##### 计数规则

只保留最近图像中的特定数量 :

```ts
const countBasedPolicy = new imagebuilder.LifecyclePolicy(this, 'CountBasedPolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.CONTAINER_IMAGE,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { countFilter: { count: 15 } }  // Keep only the 15 most recent images
    }
  ],
  resourceSelection: {
    tags: { Application: 'microservice' }
  }
});
```

##### 多个生命周期规则

采用渐进式方法,采取多种行动:

```ts
const graduatedPolicy = new imagebuilder.LifecyclePolicy(this, 'GraduatedPolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.AMI_IMAGE,
  details: [
    {
      // First: Deprecate images after 30 days
      action: {
        type: imagebuilder.LifecyclePolicyActionType.DEPRECATE,
        includeAmis: true
      },
      filter: {
        ageFilter: {
          age: Duration.days(30),
          retainAtLeast: 5
        }
      }
    },
    {
      // Second: Disable images after 60 days  
      action: {
        type: imagebuilder.LifecyclePolicyActionType.DISABLE,
        includeAmis: true
      },
      filter: {
        ageFilter: {
          age: Duration.days(60),
          retainAtLeast: 3
        }
      }
    },
    {
      // Finally: Delete images after 90 days
      action: {
        type: imagebuilder.LifecyclePolicyActionType.DELETE,
        includeAmis: true,
        includeSnapshots: true
      },
      filter: {
        ageFilter: {
          age: Duration.days(90),
          retainAtLeast: 1
        }
      }
    }
  ],
  resourceSelection: {
    tags: { Environment: 'production' }
  }
});
```

#### 生命周期政策排除规则

##### AMI 排除规则

根据各种标准,将具体的AMI排除在生命周期行动之外:

```ts
const excludeAmisPolicy = new imagebuilder.LifecyclePolicy(this, 'ExcludeAmisPolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.AMI_IMAGE,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { ageFilter: { age: Duration.days(30) } },
      exclusionRules: {
        amiExclusionRules: {
          isPublic: true,  // Exclude public AMIs
          lastLaunched: Duration.days(7),  // Exclude AMIs launched in last 7 days
          regions: ['us-west-2', 'eu-west-1'],  // Exclude AMIs in specific regions
          sharedAccounts: ['123456789012'],  // Exclude AMIs shared with specific accounts
          tags: {
            Protected: 'true',
            Environment: 'production'
          }
        }
      }
    }
  ],
  resourceSelection: {
    tags: { Team: 'infrastructure' }
  }
});
```

##### 图像排除规则

不包括带有保护标记的图像构建器图像 :

```ts
const excludeImagesPolicy = new imagebuilder.LifecyclePolicy(this, 'ExcludeImagesPolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.CONTAINER_IMAGE,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { countFilter: { count: 20 } },
      exclusionRules: {
        imageExclusionRules: {
          tags: {
            DoNotDelete: 'true',
            Critical: 'baseline'
          }
        }
      }
    }
  ],
  resourceSelection: {
    tags: { Application: 'frontend' }
  }
});
```

#### 高级寿命周期配置

##### 自定义执行角色

提供您自己的 IAM 执行角色 :

```ts
const executionRole = new iam.Role(this, 'LifecycleExecutionRole', {
  assumedBy: new iam.ServicePrincipal('imagebuilder.amazonaws.com'),
  managedPolicies: [
    iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/EC2ImageBuilderLifecycleExecutionPolicy')
  ]
});

const customRolePolicy = new imagebuilder.LifecyclePolicy(this, 'CustomRolePolicy', {
  resourceType: imagebuilder.LifecyclePolicyResourceType.AMI_IMAGE,
  executionRole: executionRole,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { ageFilter: { age: Duration.days(45) } }
    }
  ],
  resourceSelection: {
    tags: { Environment: 'development' }
  }
});
```

##### 生命周期政策状况

控制生命周期政策是否有效:

```ts
const disabledPolicy = new imagebuilder.LifecyclePolicy(this, 'DisabledPolicy', {
  lifecyclePolicyName: 'my-disabled-policy',
  description: 'A lifecycle policy that is temporarily disabled',
  status: imagebuilder.LifecyclePolicyStatus.DISABLED,
  resourceType: imagebuilder.LifecyclePolicyResourceType.AMI_IMAGE,
  details: [
    {
      action: { type: imagebuilder.LifecyclePolicyActionType.DELETE },
      filter: { ageFilter: { age: Duration.days(30) } }
    }
  ],
  resourceSelection: {
    tags: { Environment: 'testing' }
  },
  tags: {
    Owner: 'DevOps',
    CostCenter: 'Engineering'
  }
});
```

##### 进口生命周期政策

在CDK之外创建的参考生命周期政策:

```ts
// Import by name
const importedByName = imagebuilder.LifecyclePolicy.fromLifecyclePolicyName(
  this,
  'ImportedByName',
  'existing-lifecycle-policy'
);

// Import by ARN
const importedByArn = imagebuilder.LifecyclePolicy.fromLifecyclePolicyArn(
  this,
  'ImportedByArn',
  'arn:aws:imagebuilder:us-east-1:123456789012:lifecycle-policy/my-policy'
);

importedByName.grantRead(lambdaRole);
importedByArn.grant(lambdaRole, 'imagebuilder:UpdateLifecyclePolicy');
```

## 常见问题

### @aws-cdk/aws-imagebuilder-alpha 是什么？

EC2 图像构建器的 CDK 构造库

### 如何安装 @aws-cdk/aws-imagebuilder-alpha？

在项目目录运行 npm install @aws-cdk/aws-imagebuilder-alpha，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：constructs（^10\.5\.0）、aws-cdk-lib（^2\.275\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @aws-cdk/aws-imagebuilder-alpha 支持 TypeScript 吗？

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

### @aws-cdk/aws-imagebuilder-alpha 支持 ESM 还是 CommonJS？

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

### @aws-cdk/aws-imagebuilder-alpha 需要什么版本的 Node\.js？

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

### @aws-cdk/aws-imagebuilder-alpha 可以商用吗？

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

### @aws-cdk/aws-imagebuilder-alpha 的下载量有多少？

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

### @aws-cdk/aws-imagebuilder-alpha 还在维护吗？

最新版本 2\.275\.0-alpha\.0 发布于 2026/10/27（12 天前）；至今共发布 63 个版本，其中过去 12 个月发布了 63 个；首次发布于 2025/11/14。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

