選取您的 Cookie 偏好設定

我們使用提供自身網站和服務所需的基本 Cookie 和類似工具。我們使用效能 Cookie 收集匿名統計資料,以便了解客戶如何使用我們的網站並進行改進。基本 Cookie 無法停用,但可以按一下「自訂」或「拒絕」以拒絕效能 Cookie。

如果您同意,AWS 與經核准的第三方也會使用 Cookie 提供實用的網站功能、記住您的偏好設定,並顯示相關內容,包括相關廣告。若要接受或拒絕所有非必要 Cookie,請按一下「接受」或「拒絕」。若要進行更詳細的選擇,請按一下「自訂」。

資產和 AWS CDK

焦點模式
資產和 AWS CDK - AWS Cloud Development Kit (AWS CDK) v2

這是 AWS CDK v2 開發人員指南。較舊的 CDK v1 已於 2022 年 6 月 1 日進入維護,並於 2023 年 6 月 1 日結束支援。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

這是 AWS CDK v2 開發人員指南。較舊的 CDK v1 已於 2022 年 6 月 1 日進入維護,並於 2023 年 6 月 1 日結束支援。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

資產是可以捆綁到 AWS CDK 庫和應用程序中的本地文件,目錄或 Docker 映像。例如,資產可能是包含 AWS Lambda 函數處理常式程式碼的目錄。資產可以代表應用程序需要操作的任何成品。

下面的教程視頻提供了CDK資產的全面概述,並解釋了如何在你的 insfrastructure 作為代碼(IaC)使用它們。

您可以透過特定 AWS 建構顯APIs示的資產來加入資產。例如,當您定義 Lambda.Function 建構時,程式碼屬性可讓您傳遞資產 (目錄)。 Function使用 assets 來捆綁目錄的內容,並將其用於函數的代碼。同樣,ECS。 ContainerImage。 fromAsset定義 Amazon ECS 任務定義時,會使用從本機目錄建立的 Docker 映像檔。

詳細資產

當您參考應用程式中的資產時,從應用程式合成的雲端組件會包含中繼資料資訊,以及. AWS CDK CLI 這些說明包括在本機磁碟上尋找資產的位置,以及要根據資產類型執行的捆綁類型,例如要壓縮的目錄 (zip) 或要建置的 Docker 映像。

產 AWS CDK 生資產的來源雜湊。這可以在構建時使用,以確定資產的內容是否已更改。

依預設,會在雲端組件目錄中 AWS CDK 建立資產的複本,預設為cdk.out,在來源雜湊下。這樣,雲組件是獨立的,因此,如果它移動到不同的主機進行部署,它仍然可以部署。如需詳細資訊,請參閱 雲端組件

當部 AWS CDK 署參考資產的應用程式時 (直接透過應用程式程式碼或透過程式庫), AWS CDK CLI首先會準備資產並將其發佈到 Amazon S3 儲存貯體或 Amazon ECR 儲存庫。S3 儲存貯體或儲存庫是在啟動載入期間建立的。) 只有這樣才會部署在堆疊中定義的資源。

本節介紹框架中APIs可用的低級別。

資產類型

AWS CDK 支援下列類型的資產:

Amazon S3 資產

這些是 AWS CDK 上傳到 Amazon S3 的本機檔案和目錄。

Docker 影像

這些是 AWS CDK 上傳到 Amazon ECR 的 Docker 圖片。

這些資產類型將在下列各節中說明。

Amazon S3 資產

您可以將本機檔案和目錄定義為資產,並透過 aws- S3 資產模組將其 AWS CDK 封裝和上傳到 Amazon S3。

下列範例會定義本機目錄資產和檔案資產。

TypeScript
import { Asset } from 'aws-cdk-lib/aws-s3-assets'; // Archived and uploaded to Amazon S3 as a .zip file const directoryAsset = new Asset(this, "SampleZippedDirAsset", { path: path.join(__dirname, "sample-asset-directory") }); // Uploaded to Amazon S3 as-is const fileAsset = new Asset(this, 'SampleSingleFileAsset', { path: path.join(__dirname, 'file-asset.txt') });
JavaScript
const { Asset } = require('aws-cdk-lib/aws-s3-assets'); // Archived and uploaded to Amazon S3 as a .zip file const directoryAsset = new Asset(this, "SampleZippedDirAsset", { path: path.join(__dirname, "sample-asset-directory") }); // Uploaded to Amazon S3 as-is const fileAsset = new Asset(this, 'SampleSingleFileAsset', { path: path.join(__dirname, 'file-asset.txt') });
Python
import os.path dirname = os.path.dirname(__file__) from aws_cdk.aws_s3_assets import Asset # Archived and uploaded to Amazon S3 as a .zip file directory_asset = Asset(self, "SampleZippedDirAsset", path=os.path.join(dirname, "sample-asset-directory") ) # Uploaded to Amazon S3 as-is file_asset = Asset(self, 'SampleSingleFileAsset', path=os.path.join(dirname, 'file-asset.txt') )
Java
import java.io.File; import software.amazon.awscdk.services.s3.assets.Asset; // Directory where app was started File startDir = new File(System.getProperty("user.dir")); // Archived and uploaded to Amazon S3 as a .zip file Asset directoryAsset = Asset.Builder.create(this, "SampleZippedDirAsset") .path(new File(startDir, "sample-asset-directory").toString()).build(); // Uploaded to Amazon S3 as-is Asset fileAsset = Asset.Builder.create(this, "SampleSingleFileAsset") .path(new File(startDir, "file-asset.txt").toString()).build();
C#
using System.IO; using Amazon.CDK.AWS.S3.Assets; // Archived and uploaded to Amazon S3 as a .zip file var directoryAsset = new Asset(this, "SampleZippedDirAsset", new AssetProps { Path = Path.Combine(Directory.GetCurrentDirectory(), "sample-asset-directory") }); // Uploaded to Amazon S3 as-is var fileAsset = new Asset(this, "SampleSingleFileAsset", new AssetProps { Path = Path.Combine(Directory.GetCurrentDirectory(), "file-asset.txt") });
Go
dirName, err := os.Getwd() if err != nil { panic(err) } awss3assets.NewAsset(stack, jsii.String("SampleZippedDirAsset"), &awss3assets.AssetProps{ Path: jsii.String(path.Join(dirName, "sample-asset-directory")), }) awss3assets.NewAsset(stack, jsii.String("SampleSingleFileAsset"), &awss3assets.AssetProps{ Path: jsii.String(path.Join(dirName, "file-asset.txt")), })
import { Asset } from 'aws-cdk-lib/aws-s3-assets'; // Archived and uploaded to Amazon S3 as a .zip file const directoryAsset = new Asset(this, "SampleZippedDirAsset", { path: path.join(__dirname, "sample-asset-directory") }); // Uploaded to Amazon S3 as-is const fileAsset = new Asset(this, 'SampleSingleFileAsset', { path: path.join(__dirname, 'file-asset.txt') });

在大多數情況下,您不需要直接使用aws-s3-assets模組APIs中的。支援資產的模組 (例如) 具有便利的方法aws-lambda,以便您可以使用資產。對於 Lambda 函數,fromAsset() 靜態方法可讓您在本機檔案系統中指定目錄或 .zip 檔案。

Lambda 函數示例

常見的使用案例是使用處理常式程式碼建立 Lambda 函數作為 Amazon S3 資產。

下列範例使用 Amazon S3 資產在本機目錄中定義 Python 處理常式handler。它也會建立以本機目錄資產做為code屬性的 Lambda 函數。以下是處理程序的 Python 代碼。

def lambda_handler(event, context): message = 'Hello World!' return { 'message': message }

主應用程式的 AWS CDK 程式碼應如下所示。

TypeScript
import * as cdk from 'aws-cdk-lib'; import { Constructs } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as path from 'path'; export class HelloAssetStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); new lambda.Function(this, 'myLambdaFunction', { code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), runtime: lambda.Runtime.PYTHON_3_6, handler: 'index.lambda_handler' }); } }
JavaScript
const cdk = require('aws-cdk-lib'); const lambda = require('aws-cdk-lib/aws-lambda'); const path = require('path'); class HelloAssetStack extends cdk.Stack { constructor(scope, id, props) { super(scope, id, props); new lambda.Function(this, 'myLambdaFunction', { code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), runtime: lambda.Runtime.PYTHON_3_6, handler: 'index.lambda_handler' }); } } module.exports = { HelloAssetStack }
Python
from aws_cdk import Stack from constructs import Construct from aws_cdk import aws_lambda as lambda_ import os.path dirname = os.path.dirname(__file__) class HelloAssetStack(Stack): def __init__(self, scope: Construct, id: str, **kwargs): super().__init__(scope, id, **kwargs) lambda_.Function(self, 'myLambdaFunction', code=lambda_.Code.from_asset(os.path.join(dirname, 'handler')), runtime=lambda_.Runtime.PYTHON_3_6, handler="index.lambda_handler")
Java
import java.io.File; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.lambda.Runtime; public class HelloAssetStack extends Stack { public HelloAssetStack(final App scope, final String id) { this(scope, id, null); } public HelloAssetStack(final App scope, final String id, final StackProps props) { super(scope, id, props); File startDir = new File(System.getProperty("user.dir")); Function.Builder.create(this, "myLambdaFunction") .code(Code.fromAsset(new File(startDir, "handler").toString())) .runtime(Runtime.PYTHON_3_6) .handler("index.lambda_handler").build(); } }
C#
using Amazon.CDK; using Amazon.CDK.AWS.Lambda; using System.IO; public class HelloAssetStack : Stack { public HelloAssetStack(Construct scope, string id, StackProps props) : base(scope, id, props) { new Function(this, "myLambdaFunction", new FunctionProps { Code = Code.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "handler")), Runtime = Runtime.PYTHON_3_6, Handler = "index.lambda_handler" }); } }
Go
import ( "os" "path" "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/aws-cdk-go/awscdk/v2/awslambda" "github.com/aws/aws-cdk-go/awscdk/v2/awss3assets" "github.com/aws/constructs-go/constructs/v10" "github.com/aws/jsii-runtime-go" ) func HelloAssetStack(scope constructs.Construct, id string, props *HelloAssetStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack(scope, &id, &sprops) dirName, err := os.Getwd() if err != nil { panic(err) } awslambda.NewFunction(stack, jsii.String("myLambdaFunction"), &awslambda.FunctionProps{ Code: awslambda.AssetCode_FromAsset(jsii.String(path.Join(dirName, "handler")), &awss3assets.AssetOptions{}), Runtime: awslambda.Runtime_PYTHON_3_6(), Handler: jsii.String("index.lambda_handler"), }) return stack }
import * as cdk from 'aws-cdk-lib'; import { Constructs } from 'constructs'; import * as lambda from 'aws-cdk-lib/aws-lambda'; import * as path from 'path'; export class HelloAssetStack extends cdk.Stack { constructor(scope: Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); new lambda.Function(this, 'myLambdaFunction', { code: lambda.Code.fromAsset(path.join(__dirname, 'handler')), runtime: lambda.Runtime.PYTHON_3_6, handler: 'index.lambda_handler' }); } }

Function方法使用 assets 來捆綁目錄的內容,並將其用於函數的代碼。

提示

Java .jar 文ZIP件是具有不同擴展名的文件。這些檔案會按原樣上傳至 Amazon S3,但是當部署為 Lambda 函數時,會擷取它們包含的檔案,而您可能不想要這些檔案。若要避免這種情況,請將.jar檔案放在目錄中,並將該目錄指定為資產。

部署時間屬性範例

Amazon S3 資產類型也會公開 AWS CDK 程式庫和應用程式中可參考的部署時間屬性。指 AWS CDK CLI令cdk synth會將資產性質顯示為 AWS CloudFormation 參數。

下列範例會使用部署時間屬性,將影像資產的位置作為環境變數傳遞至 Lambda 函數。(文件的種類並不重要; 這裡使用的PNG圖像只是一個例子。)

TypeScript
import { Asset } from 'aws-cdk-lib/aws-s3-assets'; import * as path from 'path'; const imageAsset = new Asset(this, "SampleAsset", { path: path.join(__dirname, "images/my-image.png") }); new lambda.Function(this, "myLambdaFunction", { code: lambda.Code.asset(path.join(__dirname, "handler")), runtime: lambda.Runtime.PYTHON_3_6, handler: "index.lambda_handler", environment: { 'S3_BUCKET_NAME': imageAsset.s3BucketName, 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, 'S3_OBJECT_URL': imageAsset.s3ObjectUrl } });
JavaScript
const { Asset } = require('aws-cdk-lib/aws-s3-assets'); const path = require('path'); const imageAsset = new Asset(this, "SampleAsset", { path: path.join(__dirname, "images/my-image.png") }); new lambda.Function(this, "myLambdaFunction", { code: lambda.Code.asset(path.join(__dirname, "handler")), runtime: lambda.Runtime.PYTHON_3_6, handler: "index.lambda_handler", environment: { 'S3_BUCKET_NAME': imageAsset.s3BucketName, 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, 'S3_OBJECT_URL': imageAsset.s3ObjectUrl } });
Python
import os.path import aws_cdk.aws_lambda as lambda_ from aws_cdk.aws_s3_assets import Asset dirname = os.path.dirname(__file__) image_asset = Asset(self, "SampleAsset", path=os.path.join(dirname, "images/my-image.png")) lambda_.Function(self, "myLambdaFunction", code=lambda_.Code.asset(os.path.join(dirname, "handler")), runtime=lambda_.Runtime.PYTHON_3_6, handler="index.lambda_handler", environment=dict( S3_BUCKET_NAME=image_asset.s3_bucket_name, S3_OBJECT_KEY=image_asset.s3_object_key, S3_OBJECT_URL=image_asset.s3_object_url))
Java
import java.io.File; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.services.lambda.Function; import software.amazon.awscdk.services.lambda.Runtime; import software.amazon.awscdk.services.s3.assets.Asset; public class FunctionStack extends Stack { public FunctionStack(final App scope, final String id, final StackProps props) { super(scope, id, props); File startDir = new File(System.getProperty("user.dir")); Asset imageAsset = Asset.Builder.create(this, "SampleAsset") .path(new File(startDir, "images/my-image.png").toString()).build()) Function.Builder.create(this, "myLambdaFunction") .code(Code.fromAsset(new File(startDir, "handler").toString())) .runtime(Runtime.PYTHON_3_6) .handler("index.lambda_handler") .environment(java.util.Map.of( // Java 9 or later "S3_BUCKET_NAME", imageAsset.getS3BucketName(), "S3_OBJECT_KEY", imageAsset.getS3ObjectKey(), "S3_OBJECT_URL", imageAsset.getS3ObjectUrl())) .build(); } }
C#
using Amazon.CDK; using Amazon.CDK.AWS.Lambda; using Amazon.CDK.AWS.S3.Assets; using System.IO; using System.Collections.Generic; var imageAsset = new Asset(this, "SampleAsset", new AssetProps { Path = Path.Combine(Directory.GetCurrentDirectory(), @"images\my-image.png") }); new Function(this, "myLambdaFunction", new FunctionProps { Code = Code.FromAsset(Path.Combine(Directory.GetCurrentDirectory(), "handler")), Runtime = Runtime.PYTHON_3_6, Handler = "index.lambda_handler", Environment = new Dictionary<string, string> { ["S3_BUCKET_NAME"] = imageAsset.S3BucketName, ["S3_OBJECT_KEY"] = imageAsset.S3ObjectKey, ["S3_OBJECT_URL"] = imageAsset.S3ObjectUrl } });
Go
import ( "os" "path" "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/aws-cdk-go/awscdk/v2/awslambda" "github.com/aws/aws-cdk-go/awscdk/v2/awss3assets" ) dirName, err := os.Getwd() if err != nil { panic(err) } imageAsset := awss3assets.NewAsset(stack, jsii.String("SampleAsset"), &awss3assets.AssetProps{ Path: jsii.String(path.Join(dirName, "images/my-image.png")), }) awslambda.NewFunction(stack, jsii.String("myLambdaFunction"), &awslambda.FunctionProps{ Code: awslambda.AssetCode_FromAsset(jsii.String(path.Join(dirName, "handler"))), Runtime: awslambda.Runtime_PYTHON_3_6(), Handler: jsii.String("index.lambda_handler"), Environment: &map[string]*string{ "S3_BUCKET_NAME": imageAsset.S3BucketName(), "S3_OBJECT_KEY": imageAsset.S3ObjectKey(), "S3_URL": imageAsset.S3ObjectUrl(), }, })
import { Asset } from 'aws-cdk-lib/aws-s3-assets'; import * as path from 'path'; const imageAsset = new Asset(this, "SampleAsset", { path: path.join(__dirname, "images/my-image.png") }); new lambda.Function(this, "myLambdaFunction", { code: lambda.Code.asset(path.join(__dirname, "handler")), runtime: lambda.Runtime.PYTHON_3_6, handler: "index.lambda_handler", environment: { 'S3_BUCKET_NAME': imageAsset.s3BucketName, 'S3_OBJECT_KEY': imageAsset.s3ObjectKey, 'S3_OBJECT_URL': imageAsset.s3ObjectUrl } });

許可

如果您直接透過 aws-s3-assets 模組、IAM角色、使用者或群組使用 Amazon S3 資產,而且需要在執行階段讀取資產,請透過資產授予這些資產IAM許可。 grantRead方法。

下列範例會授與檔案資產的IAM群組讀取權限。

TypeScript
import { Asset } from 'aws-cdk-lib/aws-s3-assets'; import * as path from 'path'; const asset = new Asset(this, 'MyFile', { path: path.join(__dirname, 'my-image.png') }); const group = new iam.Group(this, 'MyUserGroup'); asset.grantRead(group);
JavaScript
const { Asset } = require('aws-cdk-lib/aws-s3-assets'); const path = require('path'); const asset = new Asset(this, 'MyFile', { path: path.join(__dirname, 'my-image.png') }); const group = new iam.Group(this, 'MyUserGroup'); asset.grantRead(group);
Python
from aws_cdk.aws_s3_assets import Asset import aws_cdk.aws_iam as iam import os.path dirname = os.path.dirname(__file__) asset = Asset(self, "MyFile", path=os.path.join(dirname, "my-image.png")) group = iam.Group(self, "MyUserGroup") asset.grant_read(group)
Java
import java.io.File; import software.amazon.awscdk.Stack; import software.amazon.awscdk.StackProps; import software.amazon.awscdk.services.iam.Group; import software.amazon.awscdk.services.s3.assets.Asset; public class GrantStack extends Stack { public GrantStack(final App scope, final String id, final StackProps props) { super(scope, id, props); File startDir = new File(System.getProperty("user.dir")); Asset asset = Asset.Builder.create(this, "SampleAsset") .path(new File(startDir, "images/my-image.png").toString()).build(); Group group = new Group(this, "MyUserGroup"); asset.grantRead(group); } }
C#
using Amazon.CDK; using Amazon.CDK.AWS.IAM; using Amazon.CDK.AWS.S3.Assets; using System.IO; var asset = new Asset(this, "MyFile", new AssetProps { Path = Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), @"images\my-image.png")) }); var group = new Group(this, "MyUserGroup"); asset.GrantRead(group);
Go
import ( "os" "path" "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/aws-cdk-go/awscdk/v2/awsiam" "github.com/aws/aws-cdk-go/awscdk/v2/awss3assets" ) dirName, err := os.Getwd() if err != nil { panic(err) } asset := awss3assets.NewAsset(stack, jsii.String("MyFile"), &awss3assets.AssetProps{ Path: jsii.String(path.Join(dirName, "my-image.png")), }) group := awsiam.NewGroup(stack, jsii.String("MyUserGroup"), &awsiam.GroupProps{}) asset.GrantRead(group)
import { Asset } from 'aws-cdk-lib/aws-s3-assets'; import * as path from 'path'; const asset = new Asset(this, 'MyFile', { path: path.join(__dirname, 'my-image.png') }); const group = new iam.Group(this, 'MyUserGroup'); asset.grantRead(group);

泊塢視窗影像資產

AWS CDK 支持通過模塊將本地 Docker 圖像捆綁為資產。aws-ecr-assets

下列範例會定義在本機建置並推送至 Amazon ECR 的 Docker 映像檔。映像是從本地 Docker 上下文目錄(使用 Docker 文件)構建的,並ECR通過 AWS CDK CLI或您的應用程序的 CI/CD 管道上傳到 Amazon。圖像可以在您的 AWS CDK 應用程序中自然引用。

TypeScript
import { DockerImageAsset } from 'aws-cdk-lib/aws-ecr-assets'; const asset = new DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image') });
JavaScript
const { DockerImageAsset } = require('aws-cdk-lib/aws-ecr-assets'); const asset = new DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image') });
Python
from aws_cdk.aws_ecr_assets import DockerImageAsset import os.path dirname = os.path.dirname(__file__) asset = DockerImageAsset(self, 'MyBuildImage', directory=os.path.join(dirname, 'my-image'))
Java
import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; File startDir = new File(System.getProperty("user.dir")); DockerImageAsset asset = DockerImageAsset.Builder.create(this, "MyBuildImage") .directory(new File(startDir, "my-image").toString()).build();
C#
using System.IO; using Amazon.CDK.AWS.ECR.Assets; var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps { Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image") });
Go
import ( "os" "path" "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/aws-cdk-go/awscdk/v2/awsecrassets" ) dirName, err := os.Getwd() if err != nil { panic(err) } asset := awsecrassets.NewDockerImageAsset(stack, jsii.String("MyBuildImage"), &awsecrassets.DockerImageAssetProps{ Directory: jsii.String(path.Join(dirName, "my-image")), })
import { DockerImageAsset } from 'aws-cdk-lib/aws-ecr-assets'; const asset = new DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image') });

my-image目錄必須包含一個碼頭文件。從中 AWS CDK CLI構建 Docker 映像my-image,將其推送到 Amazon ECR 存儲庫,並將存儲庫的名稱指定為堆棧的 AWS CloudFormation 參數。Docker 映像資產類型會公開可在 AWS CDK 程式庫和應用程式中參考的部署時間屬性。指 AWS CDK CLI令cdk synth會將資產性質顯示為 AWS CloudFormation 參數。

Amazon ECS 任務定義示例

一個常見的用例是創建一個 Amazon ECS TaskDefinition來運行 Docker 容器。下列範例會指定在本機 AWS CDK 建置並推送至 Amazon 的 Docker 映像資產的位置。ECR

TypeScript
import * as ecs from 'aws-cdk-lib/aws-ecs'; import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets'; import * as path from 'path'; const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, cpu: 512 }); const asset = new ecr_assets.DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image') }); taskDefinition.addContainer("my-other-container", { image: ecs.ContainerImage.fromDockerImageAsset(asset) });
JavaScript
const ecs = require('aws-cdk-lib/aws-ecs'); const ecr_assets = require('aws-cdk-lib/aws-ecr-assets'); const path = require('path'); const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, cpu: 512 }); const asset = new ecr_assets.DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image') }); taskDefinition.addContainer("my-other-container", { image: ecs.ContainerImage.fromDockerImageAsset(asset) });
Python
import aws_cdk.aws_ecs as ecs import aws_cdk.aws_ecr_assets as ecr_assets import os.path dirname = os.path.dirname(__file__) task_definition = ecs.FargateTaskDefinition(self, "TaskDef", memory_limit_mib=1024, cpu=512) asset = ecr_assets.DockerImageAsset(self, 'MyBuildImage', directory=os.path.join(dirname, 'my-image')) task_definition.add_container("my-other-container", image=ecs.ContainerImage.from_docker_image_asset(asset))
Java
import java.io.File; import software.amazon.awscdk.services.ecs.FargateTaskDefinition; import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; import software.amazon.awscdk.services.ecs.ContainerImage; import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; File startDir = new File(System.getProperty("user.dir")); FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); DockerImageAsset asset = DockerImageAsset.Builder.create(this, "MyBuildImage") .directory(new File(startDir, "my-image").toString()).build(); taskDefinition.addContainer("my-other-container", ContainerDefinitionOptions.builder() .image(ContainerImage.fromDockerImageAsset(asset)) .build();
C#
using System.IO; using Amazon.CDK.AWS.ECS; using Amazon.CDK.AWS.Ecr.Assets; var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps { MemoryLimitMiB = 1024, Cpu = 512 }); var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps { Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image") }); taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions { Image = ContainerImage.FromDockerImageAsset(asset) });
Go
import ( "os" "path" "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/aws-cdk-go/awscdk/v2/awsecrassets" "github.com/aws/aws-cdk-go/awscdk/v2/awsecs" ) dirName, err := os.Getwd() if err != nil { panic(err) } taskDefinition := awsecs.NewTaskDefinition(stack, jsii.String("TaskDef"), &awsecs.TaskDefinitionProps{ MemoryMiB: jsii.String("1024"), Cpu: jsii.String("512"), }) asset := awsecrassets.NewDockerImageAsset(stack, jsii.String("MyBuildImage"), &awsecrassets.DockerImageAssetProps{ Directory: jsii.String(path.Join(dirName, "my-image")), }) taskDefinition.AddContainer(jsii.String("MyOtherContainer"), &awsecs.ContainerDefinitionOptions{ Image: awsecs.ContainerImage_FromDockerImageAsset(asset), })
import * as ecs from 'aws-cdk-lib/aws-ecs'; import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets'; import * as path from 'path'; const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, cpu: 512 }); const asset = new ecr_assets.DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image') }); taskDefinition.addContainer("my-other-container", { image: ecs.ContainerImage.fromDockerImageAsset(asset) });

部署時間屬性範例

下列範例顯示如何使用部署時間屬性,以repository及如imageUri何使用 AWS Fargate 啟動類型建立 Amazon ECS 任務定義。請注意,Amazon ECR repo 查找需要圖像的標籤,而不是它的標籤URI,因此我們將其從資產的末尾進行剪切。URI

TypeScript
import * as ecs from 'aws-cdk-lib/aws-ecs'; import * as path from 'path'; import { DockerImageAsset } from 'aws-cdk-lib/aws-ecr-assets'; const asset = new DockerImageAsset(this, 'my-image', { directory: path.join(__dirname, "..", "demo-image") }); const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, cpu: 512 }); taskDefinition.addContainer("my-other-container", { image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) });
JavaScript
const ecs = require('aws-cdk-lib/aws-ecs'); const path = require('path'); const { DockerImageAsset } = require('aws-cdk-lib/aws-ecr-assets'); const asset = new DockerImageAsset(this, 'my-image', { directory: path.join(__dirname, "..", "demo-image") }); const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, cpu: 512 }); taskDefinition.addContainer("my-other-container", { image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) });
Python
import aws_cdk.aws_ecs as ecs from aws_cdk.aws_ecr_assets import DockerImageAsset import os.path dirname = os.path.dirname(__file__) asset = DockerImageAsset(self, 'my-image', directory=os.path.join(dirname, "..", "demo-image")) task_definition = ecs.FargateTaskDefinition(self, "TaskDef", memory_limit_mib=1024, cpu=512) task_definition.add_container("my-other-container", image=ecs.ContainerImage.from_ecr_repository( asset.repository, asset.image_uri.rpartition(":")[-1]))
Java
import java.io.File; import software.amazon.awscdk.services.ecr.assets.DockerImageAsset; import software.amazon.awscdk.services.ecs.FargateTaskDefinition; import software.amazon.awscdk.services.ecs.ContainerDefinitionOptions; import software.amazon.awscdk.services.ecs.ContainerImage; File startDir = new File(System.getProperty("user.dir")); DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image") .directory(new File(startDir, "demo-image").toString()).build(); FargateTaskDefinition taskDefinition = FargateTaskDefinition.Builder.create( this, "TaskDef").memoryLimitMiB(1024).cpu(512).build(); // extract the tag from the asset's image URI for use in ECR repo lookup String imageUri = asset.getImageUri(); String imageTag = imageUri.substring(imageUri.lastIndexOf(":") + 1); taskDefinition.addContainer("my-other-container", ContainerDefinitionOptions.builder().image(ContainerImage.fromEcrRepository( asset.getRepository(), imageTag)).build());
C#
using System.IO; using Amazon.CDK.AWS.ECS; using Amazon.CDK.AWS.ECR.Assets; var asset = new DockerImageAsset(this, "my-image", new DockerImageAssetProps { Directory = Path.Combine(Directory.GetCurrentDirectory(), "demo-image") }); var taskDefinition = new FargateTaskDefinition(this, "TaskDef", new FargateTaskDefinitionProps { MemoryLimitMiB = 1024, Cpu = 512 }); taskDefinition.AddContainer("my-other-container", new ContainerDefinitionOptions { Image = ContainerImage.FromEcrRepository(asset.Repository, asset.ImageUri.Split(":").Last()) });
Go
import ( "os" "path" "github.com/aws/aws-cdk-go/awscdk/v2" "github.com/aws/aws-cdk-go/awscdk/v2/awsecrassets" "github.com/aws/aws-cdk-go/awscdk/v2/awsecs" ) dirName, err := os.Getwd() if err != nil { panic(err) } asset := awsecrassets.NewDockerImageAsset(stack, jsii.String("MyImage"), &awsecrassets.DockerImageAssetProps{ Directory: jsii.String(path.Join(dirName, "demo-image")), }) taskDefinition := awsecs.NewFargateTaskDefinition(stack, jsii.String("TaskDef"), &awsecs.FargateTaskDefinitionProps{ MemoryLimitMiB: jsii.Number(1024), Cpu: jsii.Number(512), }) taskDefinition.AddContainer(jsii.String("MyOtherContainer"), &awsecs.ContainerDefinitionOptions{ Image: awsecs.ContainerImage_FromEcrRepository(asset.Repository(), asset.ImageTag()), })
import * as ecs from 'aws-cdk-lib/aws-ecs'; import * as path from 'path'; import { DockerImageAsset } from 'aws-cdk-lib/aws-ecr-assets'; const asset = new DockerImageAsset(this, 'my-image', { directory: path.join(__dirname, "..", "demo-image") }); const taskDefinition = new ecs.FargateTaskDefinition(this, "TaskDef", { memoryLimitMiB: 1024, cpu: 512 }); taskDefinition.addContainer("my-other-container", { image: ecs.ContainerImage.fromEcrRepository(asset.repository, asset.imageUri.split(":").pop()) });

構建參數示例

您可以在部署期間建置映像時,透過 buildArgs (Python:build_args) 屬性選項,為 Docker 建置步驟提供自訂的 AWS CDK CLI建置引數。

TypeScript
const asset = new DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image'), buildArgs: { HTTP_PROXY: 'http://10.20.30.2:1234' } });
JavaScript
const asset = new DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image'), buildArgs: { HTTP_PROXY: 'http://10.20.30.2:1234' } });
Python
asset = DockerImageAsset(self, "MyBulidImage", directory=os.path.join(dirname, "my-image"), build_args=dict(HTTP_PROXY="http://10.20.30.2:1234"))
Java
DockerImageAsset asset = DockerImageAsset.Builder.create(this, "my-image"), .directory(new File(startDir, "my-image").toString()) .buildArgs(java.util.Map.of( // Java 9 or later "HTTP_PROXY", "http://10.20.30.2:1234")) .build();
C#
var asset = new DockerImageAsset(this, "MyBuildImage", new DockerImageAssetProps { Directory = Path.Combine(Directory.GetCurrentDirectory(), "my-image"), BuildArgs = new Dictionary<string, string> { ["HTTP_PROXY"] = "http://10.20.30.2:1234" } });
Go
dirName, err := os.Getwd() if err != nil { panic(err) } asset := awsecrassets.NewDockerImageAsset(stack, jsii.String("MyBuildImage"), &awsecrassets.DockerImageAssetProps{ Directory: jsii.String(path.Join(dirName, "my-image")), BuildArgs: &map[string]*string{ "HTTP_PROXY": jsii.String("http://10.20.30.2:1234"), }, })
const asset = new DockerImageAsset(this, 'MyBuildImage', { directory: path.join(__dirname, 'my-image'), buildArgs: { HTTP_PROXY: 'http://10.20.30.2:1234' } });

許可

如果您使用支援 Docker 影像資產的模組 (例如 aws-ecs),則當您直接或透過使用資產時,會為您 AWS CDK 管理權限。ContainerImage fromEcrRepository(Python:from_ecr_repository)。如果您直接使用 Docker 影像資產,請確定使用主體具有提取影像的權限。

在大多數情況下,您應該使用資產庫。 grantPull方法 (Python:grant_pull. 這會修改主體的IAM原則,使其能夠從此儲存庫提取影像。 如果提取映像的主體不在同一個帳戶中,或者它是不承擔您帳戶中角色的 AWS 服務 (例如 AWS CodeBuild),您必須授與資源策略的提取權限,而不是對主體的策略授與提取權限。 使用資產存儲庫。 addToResource原則方法 (Python:add_to_resource_policy) 授與適當的主體權限。

AWS CloudFormation 資源元數據

注意

本節僅適用於建構作者。在某些情況下,工具需要知道某個CFN資源正在使用本機資產。例如,您可以使用在本機叫 AWS SAM CLI用 Lambda 函數以進行偵錯。如需詳細資訊,請參閱 AWS SAM 整合

若要啟用此類使用案例,外部工具會在 AWS CloudFormation 資源上查詢一組中繼資料項目:

  • aws:asset:path— 指向資產的本機路徑。

  • aws:asset:property— 使用資產的資源屬性名稱。

使用這兩個中繼資料項目,工具可以識別特定資源使用的資產,並啟用進階本機體驗。

若要將這些中繼資料項目新增至資源,請使用 asset.addResourceMetadata (Python:add_resource_metadata) 方法。

下一個主題:

許可

上一個主題:

標籤
隱私權網站條款Cookie 偏好設定
© 2025, Amazon Web Services, Inc.或其附屬公司。保留所有權利。