Skip to main content

CDK Constructs for AWS CodeBuild

Project description

AWS CodeBuild Construct Library

<html></html>---

Stability: Stable


<html></html>

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.

Installation

Install the module:

$ npm i @aws-cdk/aws-codebuild

Import it into your code:

# Example may have issues. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_codebuild as codebuild

The codebuild.Project construct represents a build project resource. See the reference documentation for a comprehensive list of initialization properties, methods and attributes.

Source

Build projects are usually associated with a source, which is specified via the source property which accepts a class that extends the Source abstract base class. The default is to have no source associated with the build project; the buildSpec option is required in that case.

Here's a CodeBuild project with no source which simply prints Hello, CodeBuild!:

# Example may have issues. See https://github.com/aws/jsii/issues/826
codebuild.Project(self, "MyProject",
    build_spec=codebuild.BuildSpec.from_object(
        version="0.2",
        phases={
            "build": {
                "commands": ["echo \"Hello, CodeBuild!\""
                ]
            }
        }
    )
)

CodeCommitSource

Use an AWS CodeCommit repository as the source of this build:

# Example may have issues. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_codebuild as codebuild
import aws_cdk.aws_codecommit as codecommit

repository = codecommit.Repository(self, "MyRepo", repository_name="foo")
codebuild.Project(self, "MyFirstCodeCommitProject",
    source=codebuild.Source.code_commit(repository=repository)
)

S3Source

Create a CodeBuild project with an S3 bucket as the source:

# Example may have issues. See https://github.com/aws/jsii/issues/826
import aws_cdk.aws_codebuild as codebuild
import aws_cdk.aws_s3 as s3

bucket = s3.Bucket(self, "MyBucket")
codebuild.Project(self, "MyProject",
    source=codebuild.Source.s3(
        bucket=bucket,
        path="path/to/file.zip"
    )
)

GitHubSource and GitHubEnterpriseSource

These source types can be used to build code from a GitHub repository. Example:

# Example may have issues. See https://github.com/aws/jsii/issues/826
git_hub_source = codebuild.Source.git_hub(
    owner="awslabs",
    repo="aws-cdk",
    webhook=True, # optional, default: true if `webhookFilteres` were provided, false otherwise
    webhook_filters=[
        codebuild.FilterGroup.in_event_of(codebuild.EventAction.PUSH).and_branch_is("master")
    ]
)

To provide GitHub credentials, please either go to AWS CodeBuild Console to connect or call ImportSourceCredentials to persist your personal access token. Example:

aws codebuild import-source-credentials --server-type GITHUB --auth-type PERSONAL_ACCESS_TOKEN --token <token_value>

BitBucketSource

This source type can be used to build code from a BitBucket repository.

# Example may have issues. See https://github.com/aws/jsii/issues/826
bb_source = codebuild.Source.bit_bucket(
    owner="owner",
    repo="repo"
)

CodePipeline

To add a CodeBuild Project as an Action to CodePipeline, use the PipelineProject class instead of Project. It's a simple class that doesn't allow you to specify sources, secondarySources, artifacts or secondaryArtifacts, as these are handled by setting input and output CodePipeline Artifact instances on the Action, instead of setting them on the Project.

# Example may have issues. See https://github.com/aws/jsii/issues/826
project = codebuild.PipelineProject(self, "Project")

For more details, see the readme of the @aws-cdk/@aws-codepipeline package.

Caching

You 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 Caching

With S3 caching, the cache is stored in an S3 bucket which is available from multiple hosts.

# Example may have issues. See https://github.com/aws/jsii/issues/826
codebuild.Project(self, "Project",
    source=codebuild.Source.bit_bucket(
        owner="awslabs",
        repo="aws-cdk"
    ),
    cache=codebuild.Cache.bucket(Bucket(self, "Bucket"))
)

Local Caching

With 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.Source caches Git metadata for primary and secondary sources.
  • LocalCacheMode.DockerLayer caches existing Docker layers.
  • LocalCacheMode.Custom caches directories you specify in the buildspec file.
# Example may have issues. See https://github.com/aws/jsii/issues/826
codebuild.Project(self, "Project",
    source=codebuild.Source.git_hub_enterprise(
        https_clone_url="https://my-github-enterprise.com/owner/repo"
    ),

    # Enable Docker AND custom caching
    cache=codebuild.Cache.local(LocalCacheMode.DockerLayer, LocalCacheMode.Custom)
)

Environment

By default, projects use a small instance with an Ubuntu 18.04 image. You can use the environment property to customize the build environment:

  • buildImage defines the Docker image used. See Images below for details on how to define build images.
  • computeType defines the instance type used for the build.
  • privileged can be set to true to allow privileged access.
  • environmentVariables can be set at this level (and also at the project level).

Images

The CodeBuild library supports both Linux and Windows images via the LinuxBuildImage and WindowsBuildImage classes, respectively.

You can either specify one of the predefined Windows/Linux images by using one of the constants such as WindowsBuildImage.WIN_SERVER_CORE_2016_BASE or LinuxBuildImage.UBUNTU_14_04_RUBY_2_5_1.

Alternatively, you can specify a custom image using one of the static methods on XxxBuildImage:

  • Use .fromDockerRegistry(image[, { secretsManagerCredentials }]) to reference an image in any public or private Docker registry.
  • Use .fromEcrRepository(repo[, tag]) to reference an image available in an ECR repository.
  • Use .fromAsset(directory) to use an image created from a local asset.

The following example shows how to define an image from a Docker asset:

# Example may have issues. See https://github.com/aws/jsii/issues/826
environment: {
  buildImage: codebuild.LinuxBuildImage.fromAsset(this, 'MyImage', {
    directory: path.join(__dirname, 'demo-image')
  })
}

The following example shows how to define an image from an ECR repository:

# Example may have issues. See https://github.com/aws/jsii/issues/826
environment: {
  buildImage: codebuild.LinuxBuildImage.fromEcrRepository(ecrRepository, "v1.0")
}

The following example shows how to define an image from a private docker registry:

# Example may have issues. See https://github.com/aws/jsii/issues/826
environment: {
  buildImage: codebuild.LinuxBuildImage.fromDockerRegistry('my-registry/my-repo', {
    secretsManagerCredentials: secrets,
  }),
}

Events

CodeBuild projects can be used either as a source for events or be triggered by events via an event rule.

Using Project as an event target

The @aws-cdk/aws-events-targets.CodeBuildProject allows using an AWS CodeBuild project as a AWS CloudWatch event rule target:

# Example may have issues. See https://github.com/aws/jsii/issues/826
# start build when a commit is pushed
targets = require("@aws-cdk/aws-events-targets")

code_commit_repository.on_commit("OnCommit", targets.CodeBuildProject(project))

Using Project as an event source

To define Amazon CloudWatch event rules for build projects, use one of the onXxx methods:

# Example may have issues. See https://github.com/aws/jsii/issues/826
rule = project.on_state_change("BuildStateChange",
    target=targets.LambdaFunction(fn)
)

Secondary sources and artifacts

CodeBuild Projects can get their sources from multiple places, and produce multiple outputs. For example:

# Example may have issues. See https://github.com/aws/jsii/issues/826
project = 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 the identifier property is required for both secondary sources and artifacts.

The contents of the secondary source is available to the build under the directory specified by the CODEBUILD_SRC_DIR_<identifier> environment variable (so, CODEBUILD_SRC_DIR_source2 in the above case).

The secondary artifacts have their own section in the buildspec, under the regular artifacts one. Each secondary artifact has its own section, beginning with their identifier.

So, a buildspec for the above Project could look something like this:

# Example may have issues. See https://github.com/aws/jsii/issues/826
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 Project

Typically, 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 see https://docs.aws.amazon.com/codebuild/latest/userguide/vpc-support.html

Use Cases VPC 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 Projects

Pass 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 the connections object.

For example:

# Example may have issues. See https://github.com/aws/jsii/issues/826
vpc = 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 details


Release history Release notifications | RSS feed

Download files

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

Files for aws-cdk.aws-codebuild, version 1.13.0
Filename, size File type Python version Upload date Hashes
Filename, size aws_cdk.aws_codebuild-1.13.0-py3-none-any.whl (206.8 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size aws-cdk.aws-codebuild-1.13.0.tar.gz (213.7 kB) File type Source Python version None Upload date Hashes View

Supported by

Pingdom Pingdom Monitoring Google Google Object Storage and Download Analytics Sentry Sentry Error logging AWS AWS Cloud computing DataDog DataDog Monitoring Fastly Fastly CDN DigiCert DigiCert EV certificate StatusPage StatusPage Status page