Package: aws-cdk.aws-codebuild
AWS CodeBuild Construct Library---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 theMigrating to AWS CDK v2guide.AWS CodeBuild is a fully managed continuous integration service that compiles
source code, runs tests, and produces software packages that are ready to
deploy. With CodeBuild, you don’t need to provision, manage, and scale your own
build servers. CodeBuild scales continuously and processes multiple builds
concurrently, so your builds are not left waiting in a queue. You can get
started quickly by using prepackaged build environments, or you can create
custom build environments that use your own build tools. With CodeBuild, you are
charged by the minute for the compute resources you use.InstallationInstall the module:$npmi@aws-cdk/aws-codebuildImport it into your code:importaws_cdk.aws_codebuildascodebuildThecodebuild.Projectconstruct represents a build project resource. See the
reference documentation for a comprehensive list of initialization properties,
methods and attributes.SourceBuild projects are usually associated with asource, which is specified via
thesourceproperty which accepts a class that extends theSourceabstract base class.
The default is to have no source associated with the build project;
thebuildSpecoption is required in that case.Here's a CodeBuild project with no source which simply printsHello, CodeBuild!:codebuild.Project(self,"MyProject",build_spec=codebuild.BuildSpec.from_object({"version":"0.2","phases":{"build":{"commands":["echo\"Hello, CodeBuild!\""]}}}))CodeCommitSourceUse an AWS CodeCommit repository as the source of this build:importaws_cdk.aws_codecommitascodecommitrepository=codecommit.Repository(self,"MyRepo",repository_name="foo")codebuild.Project(self,"MyFirstCodeCommitProject",source=codebuild.Source.code_commit(repository=repository))S3SourceCreate a CodeBuild project with an S3 bucket as the source:bucket=s3.Bucket(self,"MyBucket")codebuild.Project(self,"MyProject",source=codebuild.Source.s3(bucket=bucket,path="path/to/file.zip"))The CodeBuild role will be granted to read just the given path from the givenbucket.GitHubSourceandGitHubEnterpriseSourceThese source types can be used to build code from a GitHub repository.
Example:git_hub_source=codebuild.Source.git_hub(owner="awslabs",repo="aws-cdk",webhook=True,# optional, default: true if `webhookFilters` were provided, false otherwisewebhook_triggers_batch_build=True,# optional, default is falsewebhook_filters=[codebuild.FilterGroup.in_event_of(codebuild.EventAction.PUSH).and_branch_is("master").and_commit_message_is("the commit message")])To provide GitHub credentials, please either go to AWS CodeBuild Console to connect
or callImportSourceCredentialsto persist your personal access token.
Example:aws codebuild import-source-credentials --server-type GITHUB --auth-type PERSONAL_ACCESS_TOKEN --token <token_value>BitBucketSourceThis source type can be used to build code from a BitBucket repository.bb_source=codebuild.Source.bit_bucket(owner="owner",repo="repo")For all Git sourcesFor all Git sources, you can fetch submodules while cloing git repo.git_hub_source=codebuild.Source.git_hub(owner="awslabs",repo="aws-cdk",fetch_submodules=True)ArtifactsCodeBuild Projects can produce Artifacts and upload them to S3. For example:# bucket: s3.Bucketproject=codebuild.Project(self,"MyProject",build_spec=codebuild.BuildSpec.from_object({"version":"0.2"}),artifacts=codebuild.Artifacts.s3(bucket=bucket,include_build_id=False,package_zip=True,path="another/path",identifier="AddArtifact1"))If you'd prefer your buildspec to be rendered as YAML in the template,
use thefromObjectToYaml()method instead offromObject().Because we've not set thenameproperty, this example will set theoverrideArtifactNameparameter, and produce an artifact named as defined in
the Buildspec file, uploaded to an S3 bucket (bucket). The path will beanother/pathand the artifact will be a zipfile.CodePipelineTo add a CodeBuild Project as an Action to CodePipeline,
use thePipelineProjectclass instead ofProject.
It's a simple class that doesn't allow you to specifysources,secondarySources,artifactsorsecondaryArtifacts,
as these are handled by setting input and output CodePipelineArtifactinstances on the Action,
instead of setting them on the Project.project=codebuild.PipelineProject(self,"Project")For more details, see the readme of the@aws-cdk/@aws-codepipeline-actionspackage.CachingYou can save time when your project builds by using a cache. A cache can store reusable pieces of your build environment and use them across multiple builds. Your build project can use one of two types of caching: Amazon S3 or local. In general, S3 caching is a good option for small and intermediate build artifacts that are more expensive to build than to download. Local caching is a good option for large intermediate build artifacts because the cache is immediately available on the build host.S3 CachingWith S3 caching, the cache is stored in an S3 bucket which is available
regardless from what CodeBuild instance gets selected to run your CodeBuild job
on. When using S3 caching, you must also add in acachesection to your
buildspec which indicates the files to be cached:# my_caching_bucket: s3.Bucketcodebuild.Project(self,"Project",source=codebuild.Source.bit_bucket(owner="awslabs",repo="aws-cdk"),cache=codebuild.Cache.bucket(my_caching_bucket),# BuildSpec with a 'cache' section necessary for S3 caching. This can# also come from 'buildspec.yml' in your source.build_spec=codebuild.BuildSpec.from_object({"version":"0.2","phases":{"build":{"commands":["..."]}},"cache":{"paths":["/root/cachedir/**/*"]}}))Note that two different CodeBuild Projects using the same S3 bucket willnotshare their cache: each Project will get a unique file in the S3 bucket to store
the cache in.Local CachingWith local caching, the cache is stored on the codebuild instance itself. This
is simple, cheap and fast, but CodeBuild cannot guarantee a reuse of instance
and hence cannot guarantee cache hits. For example, when a build starts and
caches files locally, if two subsequent builds start at the same time afterwards
only one of those builds would get the cache. Three different cache modes are
supported, which can be turned on individually.LocalCacheMode.SOURCEcaches Git metadata for primary and secondary sources.LocalCacheMode.DOCKER_LAYERcaches existing Docker layers.LocalCacheMode.CUSTOMcaches directories you specify in the buildspec file.codebuild.Project(self,"Project",source=codebuild.Source.git_hub_enterprise(https_clone_url="https://my-github-enterprise.com/owner/repo"),# Enable Docker AND custom cachingcache=codebuild.Cache.local(codebuild.LocalCacheMode.DOCKER_LAYER,codebuild.LocalCacheMode.CUSTOM),# BuildSpec with a 'cache' section necessary for 'CUSTOM' caching. This can# also come from 'buildspec.yml' in your source.build_spec=codebuild.BuildSpec.from_object({"version":"0.2","phases":{"build":{"commands":["..."]}},"cache":{"paths":["/root/cachedir/**/*"]}}))EnvironmentBy default, projects use a small instance with an Ubuntu 18.04 image. You
can use theenvironmentproperty to customize the build environment:buildImagedefines the Docker image used. SeeImagesbelow for
details on how to define build images.certificatedefines the location of a PEM encoded certificate to import.computeTypedefines the instance type used for the build.privilegedcan be set totrueto allow privileged access.environmentVariablescan be set at this level (and also at the project
level).ImagesThe CodeBuild library supports both Linux and Windows images via theLinuxBuildImage(orLinuxArmBuildImage), andWindowsBuildImageclasses, respectively.You can specify one of the predefined Windows/Linux images by using one
of the constants such asWindowsBuildImage.WIN_SERVER_CORE_2019_BASE,WindowsBuildImage.WINDOWS_BASE_2_0,LinuxBuildImage.STANDARD_2_0, orLinuxArmBuildImage.AMAZON_LINUX_2_ARM.Alternatively, you can specify a custom image using one of the static methods onLinuxBuildImage:LinuxBuildImage.fromDockerRegistry(image[, { secretsManagerCredentials }])to reference an image in any public or private Docker registry.LinuxBuildImage.fromEcrRepository(repo[, tag])to reference an image available in an
ECR repository.LinuxBuildImage.fromAsset(parent, id, props)to use an image created from a
local asset.LinuxBuildImage.fromCodeBuildImageId(id)to reference a pre-defined, CodeBuild-provided Docker image.or one of the corresponding methods onWindowsBuildImage:WindowsBuildImage.fromDockerRegistry(image[, { secretsManagerCredentials }, imageType])WindowsBuildImage.fromEcrRepository(repo[, tag, imageType])WindowsBuildImage.fromAsset(parent, id, props, [, imageType])or one of the corresponding methods onLinuxArmBuildImage:LinuxArmBuildImage.fromEcrRepository(repo[, tag])Note that theWindowsBuildImageversion of the static methods accepts an optional parameter of typeWindowsImageType,
which can be eitherWindowsImageType.STANDARD, the default, orWindowsImageType.SERVER_2019:# ecr_repository: ecr.Repositorycodebuild.Project(self,"Project",environment=codebuild.BuildEnvironment(build_image=codebuild.WindowsBuildImage.from_ecr_repository(ecr_repository,"v1.0",codebuild.WindowsImageType.SERVER_2019),# optional certificate to include in the build imagecertificate=codebuild.BuildEnvironmentCertificate(bucket=s3.Bucket.from_bucket_name(self,"Bucket","my-bucket"),object_key="path/to/cert.pem")))The following example shows how to define an image from a Docker asset:environment=codebuild.BuildEnvironment(build_image=codebuild.LinuxBuildImage.from_asset(self,"MyImage",directory=path.join(__dirname,"demo-image")))The following example shows how to define an image from an ECR repository:environment=codebuild.BuildEnvironment(build_image=codebuild.LinuxBuildImage.from_ecr_repository(ecr_repository,"v1.0"))The following example shows how to define an image from a private docker registry:environment=codebuild.BuildEnvironment(build_image=codebuild.LinuxBuildImage.from_docker_registry("my-registry/my-repo",secrets_manager_credentials=secrets))GPU imagesThe classLinuxGpuBuildImagecontains constants for working withAWS Deep Learning Container images:codebuild.Project(self,"Project",environment=codebuild.BuildEnvironment(build_image=codebuild.LinuxGpuBuildImage.DLC_TENSORFLOW_2_1_0_INFERENCE))One complication is that the repositories for the DLC images are in
different accounts in different AWS regions.
In most cases, the CDK will handle providing the correct account for you;
in rare cases (for example, deploying to new regions)
where our information might be out of date,
you can always specify the account
(along with the repository name and tag)
explicitly using theawsDeepLearningContainersImagemethod:codebuild.Project(self,"Project",environment=codebuild.BuildEnvironment(build_image=codebuild.LinuxGpuBuildImage.aws_deep_learning_containers_image("tensorflow-inference","2.1.0-gpu-py36-cu101-ubuntu18.04","123456789012")))Alternatively, you can reference an image available in an ECR repository using theLinuxGpuBuildImage.fromEcrRepository(repo[, tag])method.LogsCodeBuild lets you specify an S3 Bucket, CloudWatch Log Group or both to receive logs from your projects.By default, logs will go to cloudwatch.CloudWatch Logs Examplecodebuild.Project(self,"Project",logging=codebuild.LoggingOptions(cloud_watch=codebuild.CloudWatchLoggingOptions(log_group=logs.LogGroup(self,"MyLogGroup"))))S3 Logs Examplecodebuild.Project(self,"Project",logging=codebuild.LoggingOptions(s3=codebuild.S3LoggingOptions(bucket=s3.Bucket(self,"LogBucket"))))CredentialsCodeBuild allows you to store credentials used when communicating with various sources,
like GitHub:codebuild.GitHubSourceCredentials(self,"CodeBuildGitHubCreds",access_token=SecretValue.secrets_manager("my-token"))and BitBucket:codebuild.BitBucketSourceCredentials(self,"CodeBuildBitBucketCreds",username=SecretValue.secrets_manager("my-bitbucket-creds",json_field="username"),password=SecretValue.secrets_manager("my-bitbucket-creds",json_field="password"))Note: the credentials are global to a given account in a given region -
they are not defined per CodeBuild project.
CodeBuild only allows storing a single credential of a given type
(GitHub, GitHub Enterprise or BitBucket)
in a given account in a given region -
any attempt to save more than one will result in an error.
You can use thelist-source-credentialsAWS CLI operationto inspect what credentials are stored in your account.Test reportsYou can specify a test report in your buildspec:project=codebuild.Project(self,"Project",build_spec=codebuild.BuildSpec.from_object({# ..."reports":{"my_report":{"files":"**/*","base-directory":"build/test-results"}}}))This will create a new test report group,
with the name<ProjectName>-myReport.The project's role in the CDK will always be granted permissions to create and use report groups
with names starting with the project's name;
if you'd rather not have those permissions added,
you can opt out of it when creating the project:# source: codebuild.Sourceproject=codebuild.Project(self,"Project",source=source,grant_report_group_permissions=False)Alternatively, you can specify an ARN of an existing resource group,
instead of a simple name, in your buildspec:# source: codebuild.Source# create a new ReportGroupreport_group=codebuild.ReportGroup(self,"ReportGroup")project=codebuild.Project(self,"Project",source=source,build_spec=codebuild.BuildSpec.from_object({# ..."reports":{"report_group.report_group_arn":{"files":"**/*","base-directory":"build/test-results"}}}))If you do that, you need to grant the project's role permissions to write reports to that report group:# project: codebuild.Project# report_group: codebuild.ReportGroupreport_group.grant_write(project)For more information on the test reports feature,
see theAWS CodeBuild documentation.EventsCodeBuild projects can be used either as a source for events or be triggered
by events via an event rule.Using Project as an event targetThe@aws-cdk/aws-events-targets.CodeBuildProjectallows using an AWS CodeBuild
project as a AWS CloudWatch event rule target:# start build when a commit is pushedimportaws_cdk.aws_codecommitascodecommitimportaws_cdk.aws_events_targetsastargets# code_commit_repository: codecommit.Repository# project: codebuild.Projectcode_commit_repository.on_commit("OnCommit",target=targets.CodeBuildProject(project))Using Project as an event sourceTo define Amazon CloudWatch event rules for build projects, use one of theonXxxmethods:importaws_cdk.aws_events_targetsastargets# fn: lambda.Function# project: codebuild.Projectrule=project.on_state_change("BuildStateChange",target=targets.LambdaFunction(fn))CodeStar NotificationsTo define CodeStar Notification rules for Projects, use one of thenotifyOnXxx()methods.
They are very similar toonXxx()methods for CloudWatch events:importaws_cdk.aws_chatbotaschatbot# project: codebuild.Projecttarget=chatbot.SlackChannelConfiguration(self,"MySlackChannel",slack_channel_configuration_name="YOUR_CHANNEL_NAME",slack_workspace_id="YOUR_SLACK_WORKSPACE_ID",slack_channel_id="YOUR_SLACK_CHANNEL_ID")rule=project.notify_on_build_succeeded("NotifyOnBuildSucceeded",target)Secondary sources and artifactsCodeBuild Projects can get their sources from multiple places, and produce
multiple outputs. For example:importaws_cdk.aws_codecommitascodecommit# repo: codecommit.Repository# bucket: s3.Bucketproject=codebuild.Project(self,"MyProject",secondary_sources=[codebuild.Source.code_commit(identifier="source2",repository=repo)],secondary_artifacts=[codebuild.Artifacts.s3(identifier="artifact2",bucket=bucket,path="some/path",name="file.zip")])Note that theidentifierproperty is required for both secondary sources and
artifacts.The contents of the secondary source is available to the build under the
directory specified by theCODEBUILD_SRC_DIR_<identifier>environment variable
(so,CODEBUILD_SRC_DIR_source2in the above case).The secondary artifacts have their own section in the buildspec, under the
regularartifactsone. Each secondary artifact has its own section, beginning
with their identifier.So, a buildspec for the above Project could look something like this:project=codebuild.Project(self,"MyProject",# secondary sources and artifacts as above...build_spec=codebuild.BuildSpec.from_object({"version":"0.2","phases":{"build":{"commands":["cd $CODEBUILD_SRC_DIR_source2","touch output2.txt"]}},"artifacts":{"secondary-artifacts":{"artifact2":{"base-directory":"$CODEBUILD_SRC_DIR_source2","files":["output2.txt"]}}}}))Definition of VPC configuration in CodeBuild ProjectTypically, resources in an VPC are not accessible by AWS CodeBuild. To enable
access, you must provide additional VPC-specific configuration information as
part of your CodeBuild project configuration. This includes the VPC ID, the
VPC subnet IDs, and the VPC security group IDs. VPC-enabled builds are then
able to access resources inside your VPC.For further Information seehttps://docs.aws.amazon.com/codebuild/latest/userguide/vpc-support.htmlUse CasesVPC connectivity from AWS CodeBuild builds makes it possible to:Run integration tests from your build against data in an Amazon RDS database that's isolated on a private subnet.Query data in an Amazon ElastiCache cluster directly from tests.Interact with internal web services hosted on Amazon EC2, Amazon ECS, or services that use internal Elastic Load Balancing.Retrieve dependencies from self-hosted, internal artifact repositories, such as PyPI for Python, Maven for Java, and npm for Node.js.Access objects in an Amazon S3 bucket configured to allow access through an Amazon VPC endpoint only.Query external web services that require fixed IP addresses through the Elastic IP address of the NAT gateway or NAT instance associated with your subnet(s).Your builds can access any resource that's hosted in your VPC.Enable Amazon VPC Access in your CodeBuild ProjectsPass the VPC when defining your Project, then make sure to
give the CodeBuild's security group the right permissions
to access the resources that it needs by using theconnectionsobject.For example:# load_balancer: elbv2.ApplicationLoadBalancervpc=ec2.Vpc(self,"MyVPC")project=codebuild.Project(self,"MyProject",vpc=vpc,build_spec=codebuild.BuildSpec.from_object({}))project.connections.allow_to(load_balancer,ec2.Port.tcp(443))Project File System Location EFSAdd support for CodeBuild to build on AWS EFS file system mounts using
the new ProjectFileSystemLocation.
ThefileSystemLocationsproperty which accepts a listProjectFileSystemLocationas represented by the interfaceIFileSystemLocations.
The only supported file system type isEFS.For example:codebuild.Project(self,"MyProject",build_spec=codebuild.BuildSpec.from_object({"version":"0.2"}),file_system_locations=[codebuild.FileSystemLocation.efs(identifier="myidentifier2",location="myclodation.mydnsroot.com:/loc",mount_point="/media",mount_options="opts")])Here's a CodeBuild project with a simple example that creates a project mounted on AWS EFS:Minimal ExampleBatch buildsTo enable batch builds you should callenableBatchBuilds()on the project instance.It returns an object containing the batch service role that was created,
orundefinedif batch builds could not be enabled, for example if the project was imported.# source: codebuild.Sourceproject=codebuild.Project(self,"MyProject",source=source)ifproject.enable_batch_builds():print("Batch builds were enabled")TimeoutsThere are two types of timeouts that can be set when creating your Project.
Thetimeoutproperty can be used to set an upper limit on how long your Project is able to run without being marked as completed.
The default is 60 minutes.
An example of overriding the default follows.codebuild.Project(self,"MyProject",timeout=Duration.minutes(90))ThequeuedTimeoutproperty can be used to set an upper limit on how your Project remains queued to run.
There is no default value for this property.
As an example, to allow your Project to queue for up to thirty (30) minutes before the build fails,
use the following code.codebuild.Project(self,"MyProject",queued_timeout=Duration.minutes(30))Limiting concurrencyBy default if a new build is triggered it will be run even if there is a previous build already in progress.
It is possible to limit the maximum concurrent builds to value between 1 and the account specific maximum limit.
By default there is no explicit limit.codebuild.Project(self,"MyProject",concurrent_build_limit=1)