

# Build projects
<a name="working-with-build-projects"></a>

A *build project* includes information about how to run a build, including where to get the source code, which build environment to use, which build commands to run, and where to store the build output.

You can perform these tasks when working with build projects:

**Topics**
+ [

# Create a build project in AWS CodeBuild
](create-project.md)
+ [

# Create a notification rule
](notification-rule-create.md)
+ [

# Change build project settings in AWS CodeBuild
](change-project.md)
+ [

# Multiple access tokens in CodeBuild
](multiple-access-tokens.md)
+ [

# Delete build projects in AWS CodeBuild
](delete-project.md)
+ [

# Get public build project URLs
](public-builds.md)
+ [

# Share build projects
](project-sharing.md)
+ [

# Tag build projects
](how-to-tag-project.md)
+ [

# Use runners with AWS CodeBuild
](runners.md)
+ [

# Use webhooks with AWS CodeBuild
](webhooks.md)
+ [

# View a build project's details in AWS CodeBuild
](view-project-details.md)
+ [

# View build project names in AWS CodeBuild
](view-project-list.md)

# Create a build project in AWS CodeBuild
<a name="create-project"></a>

You can use the AWS CodeBuild console, AWS CLI, or AWS SDKs to create a build project.

**Topics**
+ [

## Prerequisites
](#create-project-prerequisites)
+ [

## Create a build project (console)
](#create-project-console)
+ [

## Create a build project (AWS CLI)
](#create-project-cli)
+ [

## Create a build project (AWS SDKs)
](#create-project-sdks)
+ [

## Create a build project (CloudFormation)
](#create-project-cloud-formation)

## Prerequisites
<a name="create-project-prerequisites"></a>

Before creating a build project, answer the questions in [Plan a build](planning.md).

## Create a build project (console)
<a name="create-project-console"></a>

Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

 If a CodeBuild information page is displayed, choose **Create build project**. Otherwise, on the navigation pane, expand **Build**, choose **Build projects**, and then choose **Create build project**. 

Choose **Create build project**. 

Fill in the following sections. Once complete, choose **Create build project** at the bottom of the page.

**Topics**
+ [

### Project configuration
](#create-project-console-project-config)
+ [

### Source
](#create-project-console-source)
+ [

### Environment
](#create-project-console-environment)
+ [

### Buildspec
](#create-project-console-buildspec)
+ [

### Batch configuration
](#create-project-console-batch-config)
+ [

### Artifacts
](#create-project-console-artifacts)
+ [

### Logs
](#create-project-console-logs)

### Project configuration
<a name="create-project-console-project-config"></a>

**Project name**  
Enter a name for this build project. Build project names must be unique across each AWS account. 

**Description**  
Enter an optional description of the build project to help other users understand what this project is used for.

**Build badge**  
(Optional) Select **Enable build badge** to make your project's build status visible and embeddable. For more information, see [Build badges sample](sample-build-badges.md).  
Build badge does not apply if your source provider is Amazon S3. 

**Enable concurrent build limit**  <a name="enable-concurrent-build-limit.console"></a>
(Optional) If you want to limit the number of concurrent builds for this project, perform the following steps:  

1. Select **Restrict number of concurrent builds this project can start**.

1. In **Concurrent build limit**, enter the maximum number of concurrent builds that are allowed for this project. This limit cannot be greater than the concurrent build limit set for the account. If you try to enter a number greater than the account limit, an error message is displayed.
New builds are only started if the current number of builds is less than or equal to this limit. If the current build count meets this limit, new builds are throttled and are not run.

**Additional information**  
(Optional) For **Tags**, enter the name and value of any tags that you want supporting AWS services to use. Use **Add row** to add a tag. You can add up to 50 tags. 

### Source
<a name="create-project-console-source"></a>

**Source provider**  
Choose the source code provider type. Use the following lists to make selections appropriate for your source provider:  
CodeBuild does not support Bitbucket Server.

------
#### [ Amazon S3 ]

 **Bucket**   
Choose the name of the input bucket that contains the source code. 

 **S3 object key or S3 folder**   
Enter the name of the ZIP file or the path to the folder that contains the source code. Enter a forward slash (/) to download everything in the S3 bucket. 

 **Source version**   
Enter the version ID of the object that represents the build of your input file. For more information, see[Source version sample with AWS CodeBuild](sample-source-version.md). 

------
#### [ CodeCommit ]

 **Repository**   
Choose the repository you want to use.

**Reference type**  
Choose **Branch**, **Git tag**, or **Commit ID** to specify the version of your source code. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).  
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Git submodules**  
Select **Use Git submodules** if you want to include Git submodules in your repository. 

------
#### [ Bitbucket ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
Choose **CodeConnections**, **OAuth**, **App password**, or **Personal access token** to connect to CodeBuild.

 **Connection**   
Select a Bitbucket connection or a Secrets Manager secret to connect through your specified connection type.

 **Repository**   
Choose **Repository in my Bitbucket account** or **Public repository** and enter the repository URL.

 **Source version**   
Enter a branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md)   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Git submodules**  
Select **Use Git submodules** if you want to include Git submodules in your repository. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).  
For **Status context**, enter the value to be used for the `name` parameter in the Bitbucket commit status. For more information, see [build](https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build) in the Bitbucket API documentation.  
For **Target URL**, enter the value to be used for the `url` parameter in the Bitbucket commit status. For more information, see [build](https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build) in the Bitbucket API documentation.  
The status of a build triggered by a webhook is always reported to the source provider. To have the status of a build that is started from the console or an API call reported to the source provider, you must select this setting.  
If your project's builds are triggered by a webhook, you must push a new commit to the repo for a change to this setting to take effect.

In **Primary source webhook events**, select **Rebuild every time a code change is pushed to this repository ** if you want CodeBuild to build the source code every time a code change is pushed to this repository. For more information about webhooks and filter groups, see [Bitbucket webhook events](bitbucket-webhook.md).

------
#### [ GitHub ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
Choose **GitHub App**, **OAuth**, or **Personal access token** to connect to CodeBuild.

 **Connection**   
Select a GitHub connection or a Secrets Manager secret to connect through your specified connection type.

 **Repository**   
Choose **Repository in my GitHub account**, **Public repository**, or **GitHub scoped webhook** and enter the repository URL.

 **Source version**   
Enter a branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md)   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Git submodules**  
Select **Use Git submodules** if you want to include Git submodules in your repository. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).  
For **Status context**, enter the value to be used for the `context` parameter in the GitHub commit status. For more information, see [Create a commit status](https://developer.github.com/v3/repos/statuses/#create-a-commit-status) in the GitHub developer guide.  
For **Target URL**, enter the value to be used for the `target_url` parameter in the GitHub commit status. For more information, see [Create a commit status](https://developer.github.com/v3/repos/statuses/#create-a-commit-status) in the GitHub developer guide.  
The status of a build triggered by a webhook is always reported to the source provider. To have the status of a build that is started from the console or an API call reported to the source provider, you must select this setting.  
If your project's builds are triggered by a webhook, you must push a new commit to the repo for a change to this setting to take effect.

In **Primary source webhook events**, select **Rebuild every time a code change is pushed to this repository ** if you want CodeBuild to build the source code every time a code change is pushed to this repository. For more information about webhooks and filter groups, see [GitHub webhook events](github-webhook.md).

------
#### [ GitHub Enterprise Server ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
Choose **CodeConnections** or **Personal access token** to connect to CodeBuild.

 **Connection**   
Select a GitHub Enterprise connection or a Secrets Manager secret to connect through your specified connection type.

 **Repository**   
Choose **Repository in my GitHub Enterprise account** or **GitHub Enterprise scoped webhook** and enter the repository URL.

**Source version**  
Enter a pull request, branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

**Git clone depth**  
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Git submodules**  
Select **Use Git submodules** if you want to include Git submodules in your repository. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).  
For **Status context**, enter the value to be used for the `context` parameter in the GitHub commit status. For more information, see [Create a commit status](https://developer.github.com/v3/repos/statuses/#create-a-commit-status) in the GitHub developer guide.  
For **Target URL**, enter the value to be used for the `target_url` parameter in the GitHub commit status. For more information, see [Create a commit status](https://developer.github.com/v3/repos/statuses/#create-a-commit-status) in the GitHub developer guide.  
The status of a build triggered by a webhook is always reported to the source provider. To have the status of a build that is started from the console or an API call reported to the source provider, you must select this setting.  
If your project's builds are triggered by a webhook, you must push a new commit to the repo for a change to this setting to take effect.

**Insecure SSL**  
Select **Enable insecure SSL** to ignore SSL warnings while connecting to your GitHub Enterprise project repository. 

In **Primary source webhook events**, select **Rebuild every time a code change is pushed to this repository ** if you want CodeBuild to build the source code every time a code change is pushed to this repository. For more information about webhooks and filter groups, see [GitHub webhook events](github-webhook.md).

------
#### [ GitLab ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
**CodeConnections** is used to connect GitLab to CodeBuild.

 **Connection**   
Select a GitLab connection to connect through CodeConnections.

 **Repository**   
Choose the repository you want to use.

 **Source version**   
Enter a pull request ID, branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).

------
#### [ GitLab Self Managed ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
**CodeConnections** is used to connect GitLab Self Managed to CodeBuild.

 **Connection**   
Select a GitLab Self Managed connection to connect through CodeConnections.

 **Repository**   
Choose the repository you want to use.

 **Source version**   
Enter a pull request ID, branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).

------

### Environment
<a name="create-project-console-environment"></a>

**Provisioning model**  
Do one of the following:  
+ To use on-demand fleets managed by AWS CodeBuild, choose **On-demand**. With on-demand fleets, CodeBuild provides compute for your builds. The machines are destroyed when the build finishes. On-demand fleets are fully managed, and includes automatic scaling capabilities to handle spikes in demand.
+ To use reserved capacity fleets managed by AWS CodeBuild, choose **Reserved capacity**, and then select a **Fleet name**. With reserved capacity fleets, you configure a set of dedicated instances for your build environment. These machines remain idle, ready to process builds or tests immediately and reduces build durations. With reserved capacity fleets, your machines are always running and will continue to incur costs as long they're provisioned.
For information, see [Run builds on reserved capacity fleets](fleets.md).

**Environment image**  <a name="environment-image.console"></a>
Do one of the following:  
+ To use a Docker image managed by AWS CodeBuild, choose **Managed image**, and then make selections from **Operating system**, **Runtime(s)**, **Image**, and **Image version**. Make a selection from **Environment type** if it is available.
+ To use another Docker image, choose **Custom image**. For **Environment type**, choose **ARM**, **Linux**, **Linux GPU**, or **Windows**. If you choose **Other registry**, for **External registry URL**, enter the name and tag of the Docker image in Docker Hub, using the format `docker repository/docker image name`. If you choose **Amazon ECR**, use **Amazon ECR repository** and **Amazon ECR image** to choose the Docker image in your AWS account.
+ To use a private Docker image, choose **Custom image**. For **Environment type**, choose **ARM**, **Linux**, **Linux GPU**, or **Windows**. For **Image registry**, choose **Other registry**, and then enter the ARN of the credentials for your private Docker image. The credentials must be created by Secrets Manager. For more information, see [What Is AWS Secrets Manager?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/) in the *AWS Secrets Manager User Guide*.
CodeBuild overrides the `ENTRYPOINT` for custom Docker images.

**Compute**  
Do one of the following:  
+ To use EC2 compute, choose **EC2**. EC2 compute offers optimized flexibility during action runs.
+ To use Lambda compute, choose **Lambda**. Lambda compute offers optimized start-up speeds for your builds. Lambda supports faster builds due to a lower start-up latency. Lambda also automatically scales, so builds aren’t waiting in queue to run. For information, see [Run builds on AWS Lambda compute](lambda.md).

**Service role**  
Do one of the following:  
+ If you do not have a CodeBuild service role, choose **New service role**. In **Role name**, enter a name for the new role.
+ If you have a CodeBuild service role, choose **Existing service role**. In **Role ARN**, choose the service role.
When you use the console to create a build project, you can create a CodeBuild service role at the same time. By default, the role works with that build project only. If you use the console to associate this service role with another build project, the role is updated to work with the other build project. A service role can work with up to 10 build projects.

**Additional configuration**    
**Auto-retry limit**  
Specify the number of additional automatic retries after a failed build. For example, if the auto-retry limit is set to 2, CodeBuild will call the `RetryBuild` API to automatically retry your build for up to 2 additional times.  
**Timeout**  
Specify a value, between 5 minutes and 36 hours, after which CodeBuild stops the build if it is not complete. If **hours** and **minutes** are left blank, the default value of 60 minutes is used.  
**Privileged**  
(Optional) Select **Enable this flag if you want to build Docker images or want your builds to get elevated privileges** only if you plan to use this build project to build Docker images. Otherwise, all associated builds that attempt to interact with the Docker daemon fail. You must also start the Docker daemon so that your builds can interact with it. One way to do this is to initialize the Docker daemon in the `install` phase of your build spec by running the following build commands. Do not run these commands if you chose a build environment image provided by CodeBuild with Docker support.  
By default, Docker daemon is enabled for non-VPC builds. If you would like to use Docker containers for VPC builds, see [Runtime Privilege and Linux Capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) on the Docker Docs website and enable privileged mode. Also, Windows does not support privileged mode.

```
- nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2 &
- timeout 15 sh -c "until docker info; do echo .; sleep 1; done"
```  
**VPC**  
If you want CodeBuild to work with your VPC:  
+ For **VPC**, choose the VPC ID that CodeBuild uses.
+ For **VPC Subnets**, choose the subnets that include resources that CodeBuild uses.
+ For **VPC Security groups**, choose the security groups that CodeBuild uses to allow access to resources in the VPCs.
For more information, see [Use AWS CodeBuild with Amazon Virtual Private Cloud](vpc-support.md).  
**Compute**  
Choose one of the available options.  
**Registry credential**  
Specify a registry credential when the project is configured with a non-private registry image.  
This credential will only be utilized if the images are overridden with those from private registries.  
**Environment variables**  
Enter the name and value, and then choose the type of each environment variable for builds to use.   
CodeBuild sets the environment variable for your AWS Region automatically. You must set the following environment variables if you haven't added them to your buildspec.yml:  
+ AWS\$1ACCOUNT\$1ID
+ IMAGE\$1REPO\$1NAME
+ IMAGE\$1TAG
Console and AWS CLI users can see environment variables. If you have no concerns about the visibility of your environment variable, set the **Name** and **Value** fields, and then set **Type** to **Plaintext**.  
We recommend that you store an environment variable with a sensitive value, such as an AWS access key ID, an AWS secret access key, or a password as a parameter in Amazon EC2 Systems Manager Parameter Store or AWS Secrets Manager.   
If you use Amazon EC2 Systems Manager Parameter Store, then for **Type**, choose **Parameter**. For **Name**, enter an identifier for CodeBuild to reference. For **Value**, enter the parameter's name as stored in Amazon EC2 Systems Manager Parameter Store. Using a parameter named `/CodeBuild/dockerLoginPassword` as an example, for **Type**, choose **Parameter**. For **Name**, enter `LOGIN_PASSWORD`. For **Value**, enter `/CodeBuild/dockerLoginPassword`.   
If you use Amazon EC2 Systems Manager Parameter Store, we recommend that you store parameters with parameter names that start with `/CodeBuild/` (for example, `/CodeBuild/dockerLoginPassword`). You can use the CodeBuild console to create a parameter in Amazon EC2 Systems Manager. Choose **Create parameter**, and then follow the instructions in the dialog box. (In that dialog box, for **KMS key**, you can specify the ARN of an AWS KMS key in your account. Amazon EC2 Systems Manager uses this key to encrypt the parameter's value during storage and decrypt it during retrieval.) If you use the CodeBuild console to create a parameter, the console starts the parameter name with `/CodeBuild/` as it is being stored. For more information, see [Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) and [Systems Manager Parameter Store Console Walkthrough](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-walk.html#sysman-paramstore-console) in the *Amazon EC2 Systems Manager User Guide*.  
If your build project refers to parameters stored in Amazon EC2 Systems Manager Parameter Store, the build project's service role must allow the `ssm:GetParameters` action. If you chose **New service role** earlier, CodeBuild includes this action in the default service role for your build project. However, if you chose **Existing service role**, you must include this action to your service role separately.  
If your build project refers to parameters stored in Amazon EC2 Systems Manager Parameter Store with parameter names that do not start with `/CodeBuild/`, and you chose **New service role**, you must update that service role to allow access to parameter names that do not start with `/CodeBuild/`. This is because that service role allows access only to parameter names that start with `/CodeBuild/`.  
If you choose **New service role**, the service role includes permission to decrypt all parameters under the `/CodeBuild/` namespace in the Amazon EC2 Systems Manager Parameter Store.  
Environment variables you set replace existing environment variables. For example, if the Docker image already contains an environment variable named `MY_VAR` with a value of `my_value`, and you set an environment variable named `MY_VAR` with a value of `other_value`, then `my_value` is replaced by `other_value`. Similarly, if the Docker image already contains an environment variable named `PATH` with a value of `/usr/local/sbin:/usr/local/bin`, and you set an environment variable named `PATH` with a value of `$PATH:/usr/share/ant/bin`, then `/usr/local/sbin:/usr/local/bin` is replaced by the literal value `$PATH:/usr/share/ant/bin`.  
Do not set any environment variable with a name that begins with `CODEBUILD_`. This prefix is reserved for internal use.  
If an environment variable with the same name is defined in multiple places, the value is determined as follows:  
+ The value in the start build operation call takes highest precedence.
+ The value in the build project definition takes next precedence.
+ The value in the buildspec declaration takes lowest precedence.
If you use Secrets Manager, for **Type**, choose **Secrets Manager**. For **Name**, enter an identifier for CodeBuild to reference. For **Value**, enter a `reference-key` using the pattern `secret-id:json-key:version-stage:version-id`. For information, see [Secrets Manager reference-key in the buildspec file](build-spec-ref.md#secrets-manager-build-spec).  
If you use Secrets Manager, we recommend that you store secrets with names that start with `/CodeBuild/` (for example, `/CodeBuild/dockerLoginPassword`). For more information, see [What Is AWS Secrets Manager?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) in the *AWS Secrets Manager User Guide*.   
If your build project refers to secrets stored in Secrets Manager, the build project's service role must allow the `secretsmanager:GetSecretValue` action. If you chose **New service role** earlier, CodeBuild includes this action in the default service role for your build project. However, if you chose **Existing service role**, you must include this action to your service role separately.   
If your build project refers to secrets stored in Secrets Manager with secret names that do not start with `/CodeBuild/`, and you chose **New service role**, you must update the service role to allow access to secret names that do not start with `/CodeBuild/`. This is because the service role allows access only to secret names that start with `/CodeBuild/`.  
If you choose **New service role**, the service role includes permission to decrypt all secrets under the `/CodeBuild/` namespace in the Secrets Manager.

### Buildspec
<a name="create-project-console-buildspec"></a>

**Build specifications**  
Do one of the following:  
+ If your source code includes a buildspec file, choose **Use a buildspec file**. By default, CodeBuild looks for a file named `buildspec.yml` in the source code root directory. If your buildspec file uses a different name or location, enter its path from the source root in **Buildspec name** (for example, `buildspec-two.yml` or `configuration/buildspec.yml`. If the buildspec file is in an S3 bucket, it must be in the same AWS Region as your build project. Specify the buildspec file using its ARN (for example, `arn:aws:s3:::<my-codebuild-sample2>/buildspec.yml`).
+ If your source code does not include a buildspec file, or if you want to run build commands different from the ones specified for the `build` phase in the `buildspec.yml` file in the source code's root directory, choose **Insert build commands**. For **Build commands**, enter the commands you want to run in the `build` phase. For multiple commands, separate each command by `&&` (for example, `mvn test && mvn package`). To run commands in other phases, or if you have a long list of commands for the `build` phase, add a `buildspec.yml` file to the source code root directory, add the commands to the file, and then choose **Use the buildspec.yml in the source code root directory**.
For more information, see the [Buildspec reference](build-spec-ref.md).

### Batch configuration
<a name="create-project-console-batch-config"></a>

You can run a group of builds as a single operation. For more information, see [Run builds in batches](batch-build.md).

**Define batch configuration**  
Select to allow batch builds in this project.

**Batch service role**  
Provides the service role for batch builds.   
Choose one of the following:  
+ If you do not have a batch service role, choose **New service role**. In **Service role**, enter a name for the new role.
+ If you have a batch service role, choose **Existing service role**. In **Service role**, choose the service role.
Batch builds introduce a new security role in the batch configuration. This new role is required as CodeBuild must be able to call the `StartBuild`, `StopBuild`, and `RetryBuild` actions on your behalf to run builds as part of a batch. Customers should use a new role, and not the same role they use in their build, for two reasons:  
+ Giving the build role `StartBuild`, `StopBuild`, and `RetryBuild` permissions would allow a single build to start more builds via the buildspec.
+ CodeBuild batch builds provide restrictions that restrict the number of builds and compute types that can be used for the builds in the batch. If the build role has these permissions, it is possible the builds themselves could bypass these restrictions.

**Allowed compute types for batch**  
Select the compute types allowed for the batch. Select all that apply.

**Allowed fleets for batch**  
Select the fleets allowed for the batch. Select all that apply.

**Maximum builds allowed in batch**  
Enter the maximum number of builds allowed in the batch. If a batch exceeds this limit, the batch will fail.

**Batch timeout**  
Enter the maximum amount of time for the batch build to complete.

**Combine artifacts**  
Select **Combine all artifacts from batch into a single location** to have all of the artifacts from the batch combined into a single location.

 **Batch report mode**   
Select the desired build status report mode for batch builds.  
This field is only available when the project source is Bitbucket, GitHub, or GitHub Enterprise, and **Report build statuses to source provider when your builds start and finish** is selected under **Source**.   
 **Aggregated builds**   
Select to have the statuses for all builds in the batch combined into a single status report.  
 **Individual builds**   
Select to have the build statuses for all builds in the batch reported separately.

### Artifacts
<a name="create-project-console-artifacts"></a>

**Type**  
Do one of the following:  
+ If you do not want to create any build output artifacts, choose **No artifacts**. You might want to do this if you're only running build tests or you want to push a Docker image to an Amazon ECR repository.
+ To store the build output in an S3 bucket, choose **Amazon S3**, and then do the following:
  + If you want to use your project name for the build output ZIP file or folder, leave **Name** blank. Otherwise, enter the name. (If you want to output a ZIP file, and you want the ZIP file to have a file extension, be sure to include it after the ZIP file name.)
  + Select **Enable semantic versioning** if you want a name specified in the buildspec file to override any name that is specified in the console. The name in a buildspec file is calculated at build time and uses the Shell command language. For example, you can append a date and time to your artifact name so that it is always unique. Unique artifact names prevent artifacts from being overwritten. For more information, see [Buildspec syntax](build-spec-ref.md#build-spec-ref-syntax).
  + For **Bucket name**, choose the name of the output bucket.
  + If you chose **Insert build commands** earlier in this procedure, then for **Output files**, enter the locations of the files from the build that you want to put into the build output ZIP file or folder. For multiple locations, separate each location with a comma (for example, `appspec.yml, target/my-app.jar`). For more information, see the description of `files` in [Buildspec syntax](build-spec-ref.md#build-spec-ref-syntax).
  + If you do not want your build artifacts encrypted, select **Remove artifacts encryption**.
For each secondary set of artifacts you want:  

1. For **Artifact identifier**, enter a value that is fewer than 128 characters and contains only alphanumeric characters and underscores.

1. Choose **Add artifact**.

1. Follow the previous steps to configure your secondary artifacts.

1. Choose **Save artifact**.

**Additional configuration**    
**Encryption key**  
(Optional) Do one of the following:  
+ To use the AWS managed key for Amazon S3 in your account to encrypt the build output artifacts, leave **Encryption key** blank. This is the default.
+ To use a customer managed key to encrypt the build output artifacts, in **Encryption key**, enter the ARN of the KMS key. Use the format `arn:aws:kms:region-ID:account-ID:key/key-ID`.  
**Cache type**  
For **Cache type**, choose one of the following:  
+ If you do not want to use a cache, choose **No cache**.
+ If you want to use an Amazon S3 cache, choose **Amazon S3**, and then do the following:
  + For **Bucket**, choose the name of the S3 bucket where the cache is stored.
  + (Optional) For **Cache path prefix**, enter an Amazon S3 path prefix. The **Cache path prefix** value is similar to a directory name. It makes it possible for you to store the cache under the same directory in a bucket. 
**Important**  
Do not append a trailing slash (/) to the end of the path prefix.
+  If you want to use a local cache, choose **Local**, and then choose one or more local cache modes. 
**Note**  
Docker layer cache mode is available for Linux only. If you choose it, your project must run in privileged mode. 
Using a cache saves considerable build time because reusable pieces of the build environment are stored in the cache and used across builds. For information about specifying a cache in the buildspec file, see [Buildspec syntax](build-spec-ref.md#build-spec-ref-syntax). For more information about caching, see [Cache builds to improve performance](build-caching.md). 

### Logs
<a name="create-project-console-logs"></a>

Choose the logs you want to create. You can create Amazon CloudWatch Logs, Amazon S3 logs, or both. 

**CloudWatch**  
If you want Amazon CloudWatch Logs logs:    
**CloudWatch logs**  
Select **CloudWatch logs**.  
**Group name**  
Enter the name of your Amazon CloudWatch Logs log group.  
**Stream name**  
Enter your Amazon CloudWatch Logs log stream name. 

**S3**  
If you want Amazon S3 logs:    
**S3 logs**  
Select **S3 logs**.  
**Bucket**  
Choose the name of the S3 bucket for your logs.   
**Path prefix**  
Enter the prefix for your logs.   
**Disable S3 log encryption**  
Select if you do not want your S3 logs encrypted. 

## Create a build project (AWS CLI)
<a name="create-project-cli"></a>

For more information about using the AWS CLI with CodeBuild, see the [Command line reference](cmd-ref.md).

To create a CodeBuild build project using the AWS CLI, you create a JSON-formatted [Project](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_Project.html) structure, fill in the structure, and call the [https://docs.aws.amazon.com/cli/latest/reference/codebuild/create-project.html](https://docs.aws.amazon.com/cli/latest/reference/codebuild/create-project.html) command to create the project.

### Create the JSON file
<a name="cp-cli-create-file"></a>

Create a skeleton JSON file with the [https://docs.aws.amazon.com/cli/latest/reference/codebuild/create-project.html](https://docs.aws.amazon.com/cli/latest/reference/codebuild/create-project.html) command, using the `--generate-cli-skeleton` option:

```
aws codebuild create-project --generate-cli-skeleton > <json-file>
```

This creates a JSON file with the path and file name specified by *<json-file>*.

### Fill in the JSON file
<a name="cp-cli-fill-in-file"></a>

Modify the JSON data as follows and save your results.

```
{
  "name": "<project-name>",
  "description": "<description>",
  "source": {
    "type": "CODECOMMIT" | "CODEPIPELINE" | "GITHUB" | "GITHUB_ENTERPRISE" | "GITLAB" | "GITLAB_SELF_MANAGED" | "BITBUCKET" | "S3" | "NO_SOURCE",
    "location": "<source-location>",
    "gitCloneDepth": "<git-clone-depth>",
    "buildspec": "<buildspec>",
    "InsecureSsl": "<insecure-ssl>",
    "reportBuildStatus": "<report-build-status>",
    "buildStatusConfig": {
      "context": "<context>",
      "targetUrl": "<target-url>"
    },
    "gitSubmodulesConfig": {
      "fetchSubmodules": "<fetch-submodules>"
    },
    "auth": {
      "type": "<auth-type>",
      "resource": "<auth-resource>"
    },
    "sourceIdentifier": "<source-identifier>"
  },
  "secondarySources": [
    {
        "type": "CODECOMMIT" | "CODEPIPELINE" | "GITHUB" | "GITHUB_ENTERPRISE" | "GITLAB" | "GITLAB_SELF_MANAGED" | "BITBUCKET" | "S3" | "NO_SOURCE",
        "location": "<source-location>",
        "gitCloneDepth": "<git-clone-depth>",
        "buildspec": "<buildspec>",
        "InsecureSsl": "<insecure-ssl>",
        "reportBuildStatus": "<report-build-status>",
        "auth": {
          "type": "<auth-type>",
          "resource": "<auth-resource>"
        },
        "sourceIdentifier": "<source-identifier>"
    }
  ],
  "secondarySourceVersions": [
    {
      "sourceIdentifier": "<secondary-source-identifier>",
      "sourceVersion": "<secondary-source-version>"
    }
  ],
  "sourceVersion": "<source-version>",
  "artifacts": {
    "type": "CODEPIPELINE" | "S3" | "NO_ARTIFACTS",
    "location": "<artifacts-location>",
    "path": "<artifacts-path>",
    "namespaceType": "<artifacts-namespacetype>",
    "name": "<artifacts-name>",
    "overrideArtifactName": "<override-artifact-name>",
    "packaging": "<artifacts-packaging>"
  },
  "secondaryArtifacts": [
    {
      "type": "CODEPIPELINE" | "S3" | "NO_ARTIFACTS",
      "location": "<secondary-artifact-location>",
      "path": "<secondary-artifact-path>",
      "namespaceType": "<secondary-artifact-namespaceType>",
      "name": "<secondary-artifact-name>",
      "packaging": "<secondary-artifact-packaging>",
      "artifactIdentifier": "<secondary-artifact-identifier>"
    }
  ],
  "cache": {
    "type": "<cache-type>",
    "location": "<cache-location>",
    "mode": [
      "<cache-mode>"
    ]
  },
  "environment": {
    "type": "LINUX_CONTAINER" | "LINUX_GPU_CONTAINER" | "ARM_CONTAINER" | "WINDOWS_SERVER_2019_CONTAINER" | "WINDOWS_SERVER_2022_CONTAINER",
    "image": "<image>",
    "computeType": "BUILD_GENERAL1_SMALL" | "BUILD_GENERAL1_MEDIUM" | "BUILD_GENERAL1_LARGE" | "BUILD_GENERAL1_2XLARGE",
    "certificate": "<certificate>",
    "environmentVariables": [
      {
        "name": "<environmentVariable-name>",
        "value": "<environmentVariable-value>",
        "type": "<environmentVariable-type>"
      }
    ],
    "registryCredential": [
      {
        "credential": "<credential-arn-or-name>",
        "credentialProvider": "<credential-provider>"
      }
    ],
    "imagePullCredentialsType": "CODEBUILD" | "SERVICE_ROLE",
    "privilegedMode": "<privileged-mode>"
  },
  "serviceRole": "<service-role>",
  "autoRetryLimit": <auto-retry-limit>,
  "timeoutInMinutes": <timeout>,
  "queuedTimeoutInMinutes": <queued-timeout>,
  "encryptionKey": "<encryption-key>",
  "tags": [
    {
      "key": "<tag-key>",
      "value": "<tag-value>"
    }
  ],
  "vpcConfig": {
    "securityGroupIds": [
         "<security-group-id>"
    ],
    "subnets": [
         "<subnet-id>"
    ],
    "vpcId": "<vpc-id>"
  },
  "badgeEnabled": "<badge-enabled>",
  "logsConfig": {
    "cloudWatchLogs": {
      "status": "<cloudwatch-logs-status>",
      "groupName": "<group-name>",
      "streamName": "<stream-name>"
    },
    "s3Logs": {
      "status": "<s3-logs-status>",
      "location": "<s3-logs-location>",
      "encryptionDisabled": "<s3-logs-encryption-disabled>"
    }
  },
  "fileSystemLocations": [
    {
      "type": "EFS",
      "location": "<EFS-DNS-name-1>:/<directory-path>",
      "mountPoint": "<mount-point>",
      "identifier": "<efs-identifier>",
      "mountOptions": "<efs-mount-options>"
    }
  ],
  "buildBatchConfig": {
    "serviceRole": "<batch-service-role>",
    "combineArtifacts": <combine-artifacts>,
    "restrictions": {
      "maximumBuildsAllowed": <max-builds>,
      "computeTypesAllowed": [
        "<compute-type>"
      ],
      "fleetsAllowed": [
        "<fleet-name>"
      ]
    },
    "timeoutInMins": <batch-timeout>,
    "batchReportMode": "REPORT_AGGREGATED_BATCH" | "REPORT_INDIVIDUAL_BUILDS"
  },
  "concurrentBuildLimit": <concurrent-build-limit>
}
```

Replace the following:

#### **name**
<a name="cli.project-name"></a>

Required. The name for this build project. This name must be unique across all of the build projects in your AWS account.

#### **description**
<a name="cli.description"></a>

Optional. The description for this build project.

#### **source**
<a name="cli.source"></a>

Required. A [ProjectSource](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectSource.html) object that contains information about this build project's source code settings. After you add a `source` object, you can add up to 12 more sources using the [**secondarySources**](#cli.secondarysources). These settings include the following:

source/**type**  <a name="cli.source.type"></a>
Required. The type of repository that contains the source code to build. Valid values include:  
+ `CODECOMMIT`
+ `CODEPIPELINE`
+ `GITHUB`
+ `GITHUB_ENTERPRISE`
+ `GITLAB`
+ `GITLAB_SELF_MANAGED`
+ `BITBUCKET`
+ `S3`
+ `NO_SOURCE`
If you use `NO_SOURCE`, the buildspec cannot be a file because the project does not have a source. Instead, you must use the `buildspec` attribute to specify a YAML-formatted string for your buildspec. For more information, see [Create a build project without a source](no-source.md).

source/**location**  <a name="cli.source.location"></a>
Required unless you set *<source-type>* to `CODEPIPELINE`. The location of the source code for the specified repository type.  
+ For CodeCommit, the HTTPS clone URL to the repository that contains the source code and the buildspec file (for example, `https://git-codecommit.<region-id>.amazonaws.com/v1/repos/<repo-name>`).
+ For Amazon S3, the build input bucket name, followed by the path and name of the ZIP file that contains the source code and the buildspec. For example:
  + For a ZIP file located at the root of the input bucket: `<bucket-name>/<object-name>.zip`.
  + For a ZIP file located in a subfolder in the input bucket: `<bucket-name>/<subfoler-path>/<object-name>.zip`.
+ For GitHub, the HTTPS clone URL to the repository that contains the source code and the buildspec file. The URL must contain github.com. You must connect your AWS account to your GitHub account. To do this, use the CodeBuild console to create a build project.
  + Choose **Authorize application**. (After you have connected to your GitHub account, you do not need to finish creating the build project. You can close the CodeBuild console.) 
+ For GitHub Enterprise Server, the HTTP or HTTPS clone URL to the repository that contains the source code and the buildspec file. You must also connect your AWS account to your GitHub Enterprise Server account. To do this, use the CodeBuild console to create a build project.

  1. Create a personal access token in GitHub Enterprise Server.

  1. Copy this token to your clipboard so you can use it when you create your CodeBuild project. For more information, see [Creating a personal access token for the command line](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/) on the GitHub Help website. 

  1. When you use the console to create your CodeBuild project, in **Source**, for **Source provider**, choose **GitHub Enterprise**.

  1. For **Personal Access Token**, paste the token that was copied to your clipboard. Choose **Save Token**. Your CodeBuild account is now connected to your GitHub Enterprise Server account.
+ For GitLab and GitLab self-managed, the HTTPS clone URL to the repository that contains the source code and the buildspec file. Note that if you use GitLab, the URL must contain gitlab.com. If you use GitLab self-managed, the URL does not need to contain gitlab.com. You must connect your AWS account to your GitLab or GitLab self-managed account. To do this, use the CodeBuild console to create a build project.
  + In the Developer Tools navigation pane, choose **Settings**, **Connections**, and then **Create connection**. On this page, create either a GitLab or GitLab self-managed connection, and then choose **Connect to GitLab**.
+ For Bitbucket, the HTTPS clone URL to the repository that contains the source code and the buildspec file. The URL must contain bitbucket.org. You must also connect your AWS account to your Bitbucket account. To do this, use the CodeBuild console to create a build project. 

  1. When you use the console to connect (or reconnect) with Bitbucket, on the Bitbucket **Confirm access to your account** page, choose **Grant access**. (After you have connected to your Bitbucket account, you do not need to finish creating the build project. You can close the CodeBuild console.) 
+ For AWS CodePipeline, do not specify a `location` value for `source`. CodePipeline ignores this value because when you create a pipeline in CodePipeline, you specify the source code location in the Source stage of the pipeline.

source/**gitCloneDepth**  <a name="cli.source.gitclonedepth"></a>
Optional. The depth of history to download. Minimum value is 0. If this value is 0, greater than 25, or not provided, then the full history is downloaded with each build project. If your source type is Amazon S3, this value is not supported.

source/**buildspec**  <a name="cli.source.buildspec"></a>
Optional. The build specification definition or file to use. If this value is not provided or is set to an empty string, the source code must contain a `buildspec.yml` file in its root directory. If this value is set, it can be either an inline buildspec definition, the path to an alternate buildspec file relative to the root directory of your primary source, or the path to an S3 bucket. The bucket must be in the same AWS Region as the build project. Specify the buildspec file using its ARN (for example, `arn:aws:s3:::<my-codebuild-sample2>/buildspec.yml`). For more information, see [Buildspec file name and storage location](build-spec-ref.md#build-spec-ref-name-storage).

source/**auth**  <a name="cli.source.auth"></a>
Contains information about the authorization settings for CodeBuild to access the source code to be built.

source/auth/**type**  <a name="cli.source.auth.type"></a>
Required. The authorization type to use. Valid values are:  
+ `OAUTH`
+ `CODECONNECTIONS`
+ `SECRETS_MANAGER`

source/auth/**resource**  <a name="cli.source.auth.resource"></a>
Optional. The resource value that applies to the specified authorization type. This can be the Secrets Manager ARN or the CodeConnections ARN.

source/**reportBuildStatus**  <a name="cli.source.reportbuildstatus"></a>
Specifies whether to send your source provider the status of a build's start and completion. If you set this with a source provider other than GitHub, GitHub Enterprise Server, or Bitbucket, an `invalidInputException` is thrown.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).

source/**buildStatusConfig**  <a name="cli.source.buildstatusconfig"></a>
Contains information that defines how the CodeBuild build project reports the build status to the source provider. This option is only used when the source type is `GITHUB`, `GITHUB_ENTERPRISE`, or `BITBUCKET`.    
source/buildStatusConfig/**context**  
For Bitbucket sources, this parameter is used for the `name` parameter in the Bitbucket commit status. For GitHub sources, this parameter is used for the `context` parameter in the GitHub commit status.   
For example, you can have the `context` contain the build number and the webhook trigger using the CodeBuild environment variables:  

```
AWS CodeBuild sample-project Build #$CODEBUILD_BUILD_NUMBER - $CODEBUILD_WEBHOOK_TRIGGER
```
This results in the context appearing like this for build \$124 triggered by a webhook pull request event:  

```
AWS CodeBuild sample-project Build #24 - pr/8
```  
source/buildStatusConfig/**targetUrl**  
For Bitbucket sources, this parameter is used for the `url` parameter in the Bitbucket commit status. For GitHub sources, this parameter is used for the `target_url` parameter in the GitHub commit status.  
For example, you can set the `targetUrl` to `https://aws.amazon.com/codebuild/<path to build>` and the commit status will link to this URL.  
You can also include CodeBuild environment variables in the `targetUrl` to add additional information to the URL. For example, to add the build region to the URL, set the `targetUrl` to:  

```
"targetUrl": "https://aws.amazon.com/codebuild/<path to build>?region=$AWS_REGION"
```
If the build region is `us-east-2`, this will expand to:   

```
https://aws.amazon.com/codebuild/<path to build>?region=us-east-2
```

source/**gitSubmodulesConfig**  <a name="cli.source.gitsubmodulesconfig"></a>
Optional. Information about the Git submodules configuration. Used with CodeCommit, GitHub, GitHub Enterprise Server, and Bitbucket only.     
source/gitSubmodulesConfig/**fetchSubmodules**  
Set `fetchSubmodules` to `true` if you want to include the Git submodules in your repository. Git submodules that are included must be configured as HTTPS.

source/**InsecureSsl**  <a name="cli.source.insecuressl"></a>
Optional. Used with GitHub Enterprise Server only. Set this value to `true` to ignore TLS warnings while connecting to your GitHub Enterprise Server project repository. The default value is `false`. `InsecureSsl` should be used for testing purposes only. It should not be used in a production environment.

source/**sourceIdentifier**  <a name="cli.source.sourceidentifier"></a>
A user-defined identifier for the project source. Optional for the primary source. Required for secondary sources.

#### **secondarySources**
<a name="cli.secondarysources"></a>

Optional. An array of [ProjectSource](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectSource.html) objects that contain information about the secondary sources for a build project. You can add up to 12 secondary sources. The `secondarySources` objects use the same properties used by the [**source**](#cli.source) object. In a secondary source object, the `sourceIdentifier` is required.

#### **secondarySourceVersions**
<a name="cli.secondarysourceversions"></a>

Optional. An array of [ProjectSourceVersion](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectSourceVersion.html) objects. If `secondarySourceVersions` is specified at the build level, then they take precedence over this. 

#### **sourceVersion**
<a name="cli.sourceversion"></a>

Optional. The version of the build input to be built for this project. If not specified, the latest version is used. If specified, it must be one of: 
+ For CodeCommit, the commit ID, branch, or Git tag to use.
+ For GitHub, the commit ID, pull request ID, branch name, or tag name that corresponds to the version of the source code you want to build. If a pull request ID is specified, it must use the format `pr/pull-request-ID` (for example `pr/25`). If a branch name is specified, the branch's HEAD commit ID is used. If not specified, the default branch's HEAD commit ID is used. 
+ For GitLab, the commit ID, pull request ID, branch name, tag name, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).
+ For Bitbucket, the commit ID, branch name, or tag name that corresponds to the version of the source code you want to build. If a branch name is specified, the branch's HEAD commit ID is used. If not specified, the default branch's HEAD commit ID is used. 
+ For Amazon S3, the version ID of the object that represents the build input ZIP file to use. 

If `sourceVersion` is specified at the build level, then that version takes precedence over this `sourceVersion` (at the project level). For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md). 

#### **artifacts**
<a name="cli.artifacts"></a>

Required. A [ProjectArtifacts](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectArtifacts.html) object that contains information about this build project's output artifact settings. After you add an `artifacts` object, you can add up to 12 more artifacts using the [secondaryArtifacts](#cli.secondaryartifacts). These settings include the following: 

artifacts/**type**  <a name="cli.artifacts.type"></a>
Required. The type of build output artifact. Valid values are:   
+ `CODEPIPELINE`
+ `NO_ARTIFACTS`
+ `S3`

artifacts/**location**  <a name="cli.artifacts.location"></a>
Only used with the `S3` artifact type. Not used for other artifact types.  
The name of the output bucket you created or identified in the prerequisites. 

artifacts/**path**  <a name="cli.artifacts.path"></a>
Only used with the `S3` artifact type. Not used for other artifact types.  
The path in of the output bucket to place ZIP file or folder. If you do not specify a value for `path`, CodeBuild uses `namespaceType` (if specified) and `name` to determine the path and name of the build output ZIP file or folder. For example, if you specify `MyPath` for `path` and `MyArtifact.zip` for `name`, the path and name would be `MyPath/MyArtifact.zip`. 

artifacts/**namespaceType**  <a name="cli.artifacts.namespacetype"></a>
Only used with the `S3` artifact type. Not used for other artifact types.  
The namespace of the build output ZIP file or folder. Valid values include `BUILD_ID` and `NONE`. Use `BUILD_ID` to insert the build ID into the path of the build output ZIP file or folder. Otherwise, use `NONE`. If you do not specify a value for `namespaceType`, CodeBuild uses `path` (if specified) and `name` to determine the path and name of the build output ZIP file or folder. For example, if you specify `MyPath` for `path`, `BUILD_ID` for `namespaceType`, and `MyArtifact.zip` for `name`, the path and name would be `MyPath/build-ID/MyArtifact.zip`. 

artifacts/**name**  <a name="cli.artifacts.name"></a>
Only used with the `S3` artifact type. Not used for other artifact types.  
The name of the build output ZIP file or folder inside of `location`. For example, if you specify `MyPath` for `path` and `MyArtifact.zip` for `name`, the path and name would be `MyPath/MyArtifact.zip`. 

artifacts/**overrideArtifactName**  <a name="cli.artifacts.overrideartifactname"></a>
Only used with the S3 artifact type. Not used for other artifact types.  
Optional. If set to `true`, the name specified in the `artifacts` block of the buildspec file overrides `name`. For more information, see [Build specification reference for CodeBuild](build-spec-ref.md). 

artifacts/**packaging**  <a name="cli.artifacts.packaging"></a>
Only used with the `S3` artifact type. Not used for other artifact types.   
Optional. Specifies how to package the artifacts. Allowed values are:    
NONE  
Create a folder that contains the build artifacts. This is the default value.   
ZIP  
Create a ZIP file that contains the build artifacts.

#### secondaryArtifacts
<a name="cli.secondaryartifacts"></a>

Optional. An array of [ProjectArtifacts](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectArtifacts.html) objects that contain information about the secondary artifacts settings for a build project. You can add up to 12 secondary artifacts. The `secondaryArtifacts` uses many of the same settings used by the [**artifacts**](#cli.artifacts) object. 

#### cache
<a name="cli.cache"></a>

Required. A [ProjectCache](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectCache.html) object that contains information about this build project's cache settings. For more information, see [Cache builds](build-caching.md). 

#### environment
<a name="cli.environment"></a>

Required. A [ProjectEnvironment](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectEnvironment.html) object that contains information about this project's build environment settings. These settings include:

environment/**type**  <a name="cli.environment.type"></a>
Required. The type of build environment. For more information, see [type](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectEnvironment.html#CodeBuild-Type-ProjectEnvironment-type) in the *CodeBuild API Reference*.

environment/**image**  <a name="cli.environment.image"></a>
Required. The Docker image identifier used by this build environment. Typically, this identifier is expressed as *image-name*:*tag*. For example, in the Docker repository that CodeBuild uses to manage its Docker images, this could be `aws/codebuild/standard:5.0`. In Docker Hub, `maven:3.3.9-jdk-8`. In Amazon ECR, `account-id.dkr.ecr.region-id.amazonaws.com/your-Amazon-ECR-repo-name:tag`. For more information, see [Docker images provided by CodeBuild](build-env-ref-available.md). 

environment/**computeType**  <a name="cli.environment.computetype"></a>
Required. Specifies the compute resources used by this build environment. For more information, see [computeType](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectEnvironment.html#CodeBuild-Type-ProjectEnvironment-computeType) in the *CodeBuild API Reference*.

environment/**certificate**  <a name="cli.environment.certificate"></a>
Optional. The ARN of the Amazon S3 bucket, path prefix, and object key that contains the PEM-encoded certificate. The object key can be either just the .pem file or a .zip file containing the PEM-encoded certificate. For example, if your Amazon S3 bucket name is `<my-bucket>`, your path prefix is `<cert>`, and your object key name is `<certificate.pem>`, then acceptable formats for `certificate` are `<my-bucket/cert/certificate.pem>` or `arn:aws:s3:::<my-bucket/cert/certificate.pem>`.

environment/**environmentVariables**  <a name="cli.environment.environmentvariables"></a>
Optional. An array of [EnvironmentVariable](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_EnvironmentVariable.html) objects that contains the environment variables you want to specify for this build environment. Each environment variable is expressed as an object that contains a `name`, `value`, and `type` of `name`, `value`, and `type`.   
Console and AWS CLI users can see all environment variables. If you have no concerns about the visibility of your environment variable, set `name` and `value`, and set `type` to `PLAINTEXT`.  
We recommend you store environment variables with sensitive values, such as an AWS access key ID, an AWS secret access key, or a password, as a parameter in Amazon EC2 Systems Manager Parameter Store or AWS Secrets Manager. For `name`, for that stored parameter, set an identifier for CodeBuild to reference.   
If you use Amazon EC2 Systems Manager Parameter Store, for `value`, set the parameter's name as stored in the Parameter Store. Set `type` to `PARAMETER_STORE`. Using a parameter named `/CodeBuild/dockerLoginPassword` as an example, set `name` to `LOGIN_PASSWORD`. Set `value` to `/CodeBuild/dockerLoginPassword`. Set `type` to `PARAMETER_STORE`.   
If you use Amazon EC2 Systems Manager Parameter Store, we recommend that you store parameters with parameter names that start with `/CodeBuild/` (for example, `/CodeBuild/dockerLoginPassword`). You can use the CodeBuild console to create a parameter in Amazon EC2 Systems Manager. Choose **Create parameter**, and then follow the instructions in the dialog box. (In that dialog box, for **KMS key**, you can specify the ARN of an AWS KMS key in your account. Amazon EC2 Systems Manager uses this key to encrypt the parameter's value during storage and decrypt it during retrieval.) If you use the CodeBuild console to create a parameter, the console starts the parameter name with `/CodeBuild/` as it is being stored. For more information, see [Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) and [Systems Manager Parameter Store Console Walkthrough](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-walk.html#sysman-paramstore-console) in the *Amazon EC2 Systems Manager User Guide*.  
If your build project refers to parameters stored in Amazon EC2 Systems Manager Parameter Store, the build project's service role must allow the `ssm:GetParameters` action. If you chose **New service role** earlier, CodeBuild includes this action in the default service role for your build project. However, if you chose **Existing service role**, you must include this action to your service role separately.  
If your build project refers to parameters stored in Amazon EC2 Systems Manager Parameter Store with parameter names that do not start with `/CodeBuild/`, and you chose **New service role**, you must update that service role to allow access to parameter names that do not start with `/CodeBuild/`. This is because that service role allows access only to parameter names that start with `/CodeBuild/`.  
If you choose **New service role**, the service role includes permission to decrypt all parameters under the `/CodeBuild/` namespace in the Amazon EC2 Systems Manager Parameter Store.  
Environment variables you set replace existing environment variables. For example, if the Docker image already contains an environment variable named `MY_VAR` with a value of `my_value`, and you set an environment variable named `MY_VAR` with a value of `other_value`, then `my_value` is replaced by `other_value`. Similarly, if the Docker image already contains an environment variable named `PATH` with a value of `/usr/local/sbin:/usr/local/bin`, and you set an environment variable named `PATH` with a value of `$PATH:/usr/share/ant/bin`, then `/usr/local/sbin:/usr/local/bin` is replaced by the literal value `$PATH:/usr/share/ant/bin`.  
Do not set any environment variable with a name that begins with `CODEBUILD_`. This prefix is reserved for internal use.  
If an environment variable with the same name is defined in multiple places, the value is determined as follows:  
+ The value in the start build operation call takes highest precedence.
+ The value in the build project definition takes next precedence.
+ The value in the buildspec declaration takes lowest precedence.
If you use Secrets Manager, for `value`, set the parameter's name as stored in Secrets Manager. Set `type` to `SECRETS_MANAGER`. Using a secret named `/CodeBuild/dockerLoginPassword` as an example, set `name` to `LOGIN_PASSWORD`. Set `value` to `/CodeBuild/dockerLoginPassword`. Set `type` to `SECRETS_MANAGER`.  
If you use Secrets Manager, we recommend that you store secrets with names that start with `/CodeBuild/` (for example, `/CodeBuild/dockerLoginPassword`). For more information, see [What Is AWS Secrets Manager?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) in the *AWS Secrets Manager User Guide*.   
If your build project refers to secrets stored in Secrets Manager, the build project's service role must allow the `secretsmanager:GetSecretValue` action. If you chose **New service role** earlier, CodeBuild includes this action in the default service role for your build project. However, if you chose **Existing service role**, you must include this action to your service role separately.   
If your build project refers to secrets stored in Secrets Manager with secret names that do not start with `/CodeBuild/`, and you chose **New service role**, you must update the service role to allow access to secret names that do not start with `/CodeBuild/`. This is because the service role allows access only to secret names that start with `/CodeBuild/`.  
If you choose **New service role**, the service role includes permission to decrypt all secrets under the `/CodeBuild/` namespace in the Secrets Manager.

environment/**registryCredential**  <a name="cli.environment.registrycredential"></a>
Optional. A [RegistryCredential](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_RegistryCredential.html) object that specifies the credentials that provide access to a private Docker registry.     
environment/registryCredential/**credential**  
Specifies the ARN or name of credentials created using AWS Managed Services. You can use the name of the credentials only if they exist in your current Region.  
environment/registryCredential/**credentialProvider**  
The only valid value is `SECRETS_MANAGER`.
When this is set:   
+ `imagePullCredentials` must be set to `SERVICE_ROLE`.
+ The image cannot be a curated image or an Amazon ECR image.

environment/**imagePullCredentialsType**  <a name="cli.environment.imagepullcredentialstype"></a>
Optional. The type of credentials CodeBuild uses to pull images in your build. There are two valid values:    
CODEBUILD  
`CODEBUILD` specifies that CodeBuild uses its own credentials. You must edit your Amazon ECR repository policy to trust the CodeBuild service principal.   
SERVICE\$1ROLE  
Specifies that CodeBuild uses your build project's service role. 
When you use a cross-account or private registry image, you must use `SERVICE_ROLE` credentials. When you use a CodeBuild curated image, you must use `CODEBUILD` credentials. 

environment/**privilegedMode**  <a name="cli.environment.privilegedmode"></a>
Set to `true` only if you plan to use this build project to build Docker images. Otherwise, all associated builds that attempt to interact with the Docker daemon fail. You must also start the Docker daemon so that your builds can interact with it. One way to do this is to initialize the Docker daemon in the `install` phase of your buildspec file by running the following build commands. Do not run these commands if you specified a build environment image provided by CodeBuild with Docker support.  
By default, Docker daemon is enabled for non-VPC builds. If you would like to use Docker containers for VPC builds, see [Runtime Privilege and Linux Capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) on the Docker Docs website and enable privileged mode. Also, Windows does not support privileged mode.

```
- nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2 &
- timeout 15 sh -c "until docker info; do echo .; sleep 1; done"
```

#### serviceRole
<a name="cli.servicerole"></a>

Required. The ARN of the service role CodeBuild uses to interact with services on behalf of the user (for example, `arn:aws:iam::account-id:role/role-name`).

#### autoRetryLimit
<a name="cli.autoretrylimit"></a>

Optional. The number of additional automatic retries after a failed build. For example, if the auto-retry limit is set to 2, CodeBuild will call the `RetryBuild` API to automatically retry your build for up to 2 additional times.

#### timeoutInMinutes
<a name="cli.timeoutinminutes"></a>

Optional. The number of minutes, between 5 to 2160 (36 hours), after which CodeBuild stops the build if it is not complete. If not specified, the default of 60 is used. To determine if and when CodeBuild stopped a build due to a timeout, run the `batch-get-builds` command. To determine if the build has stopped, look in the output for a `buildStatus` value of `FAILED`. To determine when the build timed out, look in the output for the `endTime` value associated with a `phaseStatus` value of `TIMED_OUT`. 

#### queuedTimeoutInMinutes
<a name="cli.queuedtimeoutinminutes"></a>

Optional. The number of minutes, between 5 to 480 (8 hours), after which CodeBuild stops the build if it is is still queued. If not specified, the default of 60 is used. 

#### encryptionKey
<a name="cli.encryptionkey"></a>

Optional. The alias or ARN of the AWS KMS key used by CodeBuild to encrypt the build output. If you specify an alias, use the format `arn:aws:kms:region-ID:account-ID:key/key-ID` or, if an alias exists, use the format `alias/key-alias`. If not specified, the AWS-managed KMS key for Amazon S3 is used.

#### tags
<a name="cli.tags"></a>

Optional. An array of [Tag](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_Tag.html) objects that provide the tags you want to associate with this build project. You can specify up to 50 tags. These tags can be used by any AWS service that supports CodeBuild build project tags. Each tag is expressed as an object with a `key` and a `value`.

#### vpcConfig
<a name="cli.vpcconfig"></a>

Optional. A [VpcConfig](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_VpcConfig.html) object that contains information information about the VPC configuration for your project. For more information, see [Use AWS CodeBuild with Amazon Virtual Private Cloud](vpc-support.md).

These properties include: 

vpcId  
Required. The VPC ID that CodeBuild uses. Run this command to get a list of all VPC IDs in your Region:  

```
aws ec2 describe-vpcs --region <region-ID>
```

subnets  
Required. An array of subnet IDs that include resources used by CodeBuild. Run this command to get these IDs:  

```
aws ec2 describe-subnets --filters "Name=vpc-id,Values=<vpc-id>" --region <region-ID>
```

securityGroupIds  
Required. An array of security group IDs used by CodeBuild to allow access to resources in the VPC. Run this command to get these IDs:  

```
aws ec2 describe-security-groups --filters "Name=vpc-id,Values=<vpc-id>" --<region-ID>
```

#### badgeEnabled
<a name="cli.badgeenabled"></a>

Optional. Specifies whether to include build badges with your CodeBuild project. Set to `true` to enable build badges, or `false` otherwise. For more information, see [Build badges sample with CodeBuild](sample-build-badges.md).

#### logsConfig
<a name="cli.logsconfig"></a>

A [LogsConfig](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_LogsConfig.html) object that contains information about where this build's logs are located.

logsConfig/**cloudWatchLogs**  <a name="cli.logsconfig.cloudwatchlogs"></a>
A [CloudWatchLogsConfig](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_CloudWatchLogsConfig.html) object that contains information about pushing logs to CloudWatch Logs.

logsConfig/**s3Logs**  <a name="cli.logsconfig.s3logs"></a>
An [S3LogsConfig](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_S3LogsConfig.html) object that contains information about pushing logs to Amazon S3.

#### fileSystemLocations
<a name="cli.filesystemlocations"></a>

Optional. An array of [ProjectFileSystemsLocation](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectFileSystemLocation.html) objects that contains informationabout your Amazon EFS configuration. 

#### buildBatchConfig
<a name="cli.buildbatchconfig"></a>

Optional. The `buildBatchConfig` object is a [ProjectBuildBatchConfig](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectBuildBatchConfig.html) structure that contains the batch build configuration information for the project.

buildBatchConfig/**serviceRole**  
The service role ARN for the batch build project.

buildBatchConfig/**combineArtifacts**  
A Boolean value that specifies whether to combine the build artifacts for the batch build into a single artifact location.

buildBatchConfig/restrictions/**maximumBuildsAllowed**  
The maximum number of builds allowed.

buildBatchConfig/restrictions/**computeTypesAllowed**  
An array of strings that specify the compute types that are allowed for the batch build. See [Build environment compute types](https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-compute-types.html) for these values. 

buildBatchConfig/restrictions/**fleetsAllowed**  
An array of strings that specify the fleets that are allowed for the batch build. See [Run builds on reserved capacity fleets](https://docs.aws.amazon.com/codebuild/latest/userguide/fleets.html) for more information. 

buildBatchConfig/**timeoutInMinutes**  
The maximum amount of time, in minutes, that the batch build must be completed in.

buildBatchConfig/**batchReportMode**   
Specifies how build status reports are sent to the source provider for the batch build. Valid values include:    
`REPORT_AGGREGATED_BATCH`  
(Default) Aggregate all of the build statuses into a single status report.  
`REPORT_INDIVIDUAL_BUILDS`  
Send a separate status report for each individual build.

#### concurrentBuildLimit
<a name="cli.concurrentbuildlimit"></a>

The maximum number of concurrent builds that are allowed for this project.

New builds are only started if the current number of builds is less than or equal to this limit. If the current build count meets this limit, new builds are throttled and are not run.

### Create the project
<a name="cp-cli-create-project"></a>

To create the project, run the **[https://docs.aws.amazon.com/cli/latest/reference/codebuild/create-project.html](https://docs.aws.amazon.com/cli/latest/reference/codebuild/create-project.html)** command again, passing your JSON file:

```
aws codebuild create-project --cli-input-json file://<json-file>
```

If successful, the JSON representation of a [Project](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_Project.html) object appears in the console output. See the [CreateProject Response Syntax](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_CreateProject.html#API_CreateProject_ResponseSyntax) for an example of this data.

Except for the build project name, you can change any of the build project's settings later. For more information, see [Change a build project's settings (AWS CLI)](change-project.md#change-project-cli).

To start running a build, see [Run a build (AWS CLI)](run-build-cli.md).

If your source code is stored in a GitHub repository, and you want CodeBuild to rebuild the source code every time a code change is pushed to the repository, see [Start running builds automatically (AWS CLI)](run-build-cli-auto-start.md).

## Create a build project (AWS SDKs)
<a name="create-project-sdks"></a>

For information about using AWS CodeBuild with the AWS SDKs, see the [AWS SDKs and tools reference](sdk-ref.md).

## Create a build project (CloudFormation)
<a name="create-project-cloud-formation"></a>

For information about using AWS CodeBuild with CloudFormation, see [the CloudFormation template for CodeBuild](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-project.html) in the *AWS CloudFormation User Guide*.

# Create a notification rule
<a name="notification-rule-create"></a>

You can use notification rules to notify users when important changes, such as build successes and failures, occur. Notification rules specify both the events and the Amazon SNS topic that is used to send notifications. For more information, see [What are notifications?](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/welcome.html)



You can use the console or the AWS CLI to create notification rules for AWS CodeBuild. <a name="notification-rule-create-console"></a>

# To create a notification rule (console)
<a name="notification-rule-create-console"></a>

1. Sign in to the AWS Management Console and open the CodeBuild console at [https://console.aws.amazon.com/codebuild/](https://console.aws.amazon.com/codebuild/).

1. Choose **Build**, choose **Build projects**, and then choose a build project where you want to add notifications.

1. On the build project page, choose **Notify**, and then choose **Create notification rule**. You can also go to the **Settings** page for the build project and choose **Create notification rule**.

1. In **Notification name**, enter a name for the rule.

1. In **Detail type**, choose **Basic** if you want only the information provided to Amazon EventBridge included in the notification. Choose **Full** if you want to include information provided to Amazon EventBridge and information that might be supplied by the CodeBuild or the notification manager.

   For more information, see [Understanding Notification Contents and Security](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/security.html#security-notifications).

1.  In **Events that trigger notifications**, select the events for which you want to send notifications. For more information, see [ Events for Notification Rules on Build Projects](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/concepts.html#events-ref-buildproject).

1. In **Targets**, do one of the following:
   + If you have already configured a resource to use with notifications, in **Choose target type**, choose either **Amazon Q Developer in chat applications (Slack)** or **SNS topic**. In **Choose target**, choose the name of the client (for a Slack client configured in Amazon Q Developer in chat applications) or the Amazon Resource Name (ARN) of the Amazon SNS topic (for Amazon SNS topics already configured with the policy required for notifications).
   + If you have not configured a resource to use with notifications, choose **Create target**, and then choose **SNS topic**. Provide a name for the topic after **codestar-notifications-**, and then choose **Create**.
**Note**  
If you create the Amazon SNS topic as part of creating the notification rule, the policy that allows the notifications feature to publish events to the topic is applied for you. Using a topic created for notification rules helps ensure that you subscribe only those users that you want to receive notifications about this resource.
You cannot create an Amazon Q Developer in chat applications client as part of creating a notification rule. If you choose Amazon Q Developer in chat applications (Slack), you will see a button directing you to configure a client in Amazon Q Developer in chat applications. Choosing that option opens the Amazon Q Developer in chat applications console. For more information, see [ Configure Integrations Between Notifications and Amazon Q Developer in chat applications](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notifications-chatbot.html).
If you want to use an existing Amazon SNS topic as a target, you must add the required policy for AWS CodeStar Notifications in addition to any other policies that might exist for that topic. For more information, see [Configure Amazon SNS Topics for Notifications ](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/set-up-sns.html) and [Understanding Notification Contents and Security](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/security.html#security-notifications). 

1. To finish creating the rule, choose **Submit**.

1. You must subscribe users to the Amazon SNS topic for the rule before they can receive notifications. For more information, see [Subscribe Users to Amazon SNS Topics That Are Targets](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/subscribe-users-sns.html). You can also set up integration between notifications and Amazon Q Developer in chat applications to send notifications to Amazon Chime chatrooms. For more information, see [Configure Integration Between Notifications and Amazon Q Developer in chat applications](https://docs.aws.amazon.com/codestar-notifications/latest/userguide/notifications-chatbot.html).<a name="notification-rule-create-cli"></a>

# To create a notification rule (AWS CLI)
<a name="notification-rule-create-cli"></a>

1. At a terminal or command prompt, run the **create-notification rule** command to generate the JSON skeleton:

   ```
   aws codestarnotifications create-notification-rule --generate-cli-skeleton > rule.json
   ```

   You can name the file anything you want. In this example, the file is named *rule.json*.

1. Open the JSON file in a plain-text editor and edit it to include the resource, event types, and target you want for the rule. The following example shows a notification rule named **MyNotificationRule** for a build project named *MyBuildProject* in an AWS acccount with the ID *123456789012*. Notifications are sent with the full detail type to an Amazon SNS topic named *codestar-notifications-MyNotificationTopic* when builds are successful:

   ```
   {
       "Name": "MyNotificationRule",
       "EventTypeIds": [
           "codebuild-project-build-state-succeeded"
       ],
       "Resource": "arn:aws:codebuild:us-east-2:123456789012:MyBuildProject",
       "Targets": [
           {
               "TargetType": "SNS",
               "TargetAddress": "arn:aws:sns:us-east-2:123456789012:codestar-notifications-MyNotificationTopic"
           }
       ],
       "Status": "ENABLED",
       "DetailType": "FULL"
   }
   ```

   Save the file.

1. Using the file you just edited, at the terminal or command line, run the **create-notification-rule** command again to create the notification rule:

   ```
   aws codestarnotifications create-notification-rule --cli-input-json  file://rule.json
   ```

1. If successful, the command returns the ARN of the notification rule, similar to the following:

   ```
   {
       "Arn": "arn:aws:codestar-notifications:us-east-1:123456789012:notificationrule/dc82df7a-EXAMPLE"
   }
   ```

# Change build project settings in AWS CodeBuild
<a name="change-project"></a>

You can use the AWS CodeBuild console, AWS CLI, or AWS SDKs to change a build project's settings.

If you add test reporting to a build project, make sure your IAM role has the permissions described in [Test report permissions](test-permissions.md).

**Topics**
+ [

## Change a build project's settings (console)
](#change-project-console)
+ [

## Change a build project's settings (AWS CLI)
](#change-project-cli)
+ [

## Change a build project's settings (AWS SDKs)
](#change-project-sdks)

## Change a build project's settings (console)
<a name="change-project-console"></a>

To change the settings for a build project, perform the following procedure:

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. In the navigation pane, choose **Build projects**.

1. Do one of the following:
   + Choose the link for the build project you want to change, and then choose **Build details**.
   + Choose the button next to the build project you want to change, choose **View details**, and then choose **Build details**.

You can modify the following sections:

**Topics**
+ [

### Project configuration
](#change-project-console-project-config)
+ [

### Source
](#change-project-console-source)
+ [

### Environment
](#change-project-console-environment)
+ [

### Buildspec
](#change-project-console-buildspec)
+ [

### Batch configuration
](#change-project-console-batch-config)
+ [

### Artifacts
](#change-project-console-artifacts)
+ [

### Logs
](#change-project-console-logs)

### Project configuration
<a name="change-project-console-project-config"></a>

In the **Project configuration** section, choose **Edit**. When your changes are complete, choose **Update configuration** to save the new configuration. 

You can modify the following properties. 

**Description**  
Enter an optional description of the build project to help other users understand what this project is used for.

**Build badge**  
Select **Enable build badge** to make your project's build status visible and embeddable. For more information, see [Build badges sample](sample-build-badges.md).  
Build badge does not apply if your source provider is Amazon S3. 

**Enable concurrent build limit**  
If you want to limit the number of concurrent builds for this project, perform the following steps:  

1. Select **Restrict number of concurrent builds this project can start**.

1. In **Concurrent build limit**, enter the maximum number of concurrent builds that are allowed for this project. This limit cannot be greater than the concurrent build limit set for the account. If you try to enter a number greater than the account limit, an error message is displayed.
New builds are only started if the current number of builds is less than or equal to this limit. If the current build count meets this limit, new builds are throttled and are not run.

**Enable public build access**  <a name="change-project-console.public-builds"></a>
To make your project's build results available to the public, including users without access to an AWS account, select **Enable public build access** and confirm that you want to make the build results public. The following properties are used for public build projects:    
**Public build service role**  
Select **New service role** if you want to have CodeBuild create a new service role for you, or **Existing service role** if you want to use an existing service role.  
The public build service role enables CodeBuild to read the CloudWatch Logs and download the Amazon S3 artifacts for the project's builds. This is required to make the project's build logs and artifacts available to the public.  
**Service role**  
Enter the name of the new service role or an existing service role.
To make your project's build results private, clear **Enable public build access**.   
For more information, see [Get public build project URLs](public-builds.md).  
The following should be kept in mind when making your project's build results public:  
+ All of a project's build results, logs, and artifacts, including builds that were run when the project was private, are available to the public.
+ All build logs and artifacts are available to the public. Environment variables, source code, and other sensitive information may have been output to the build logs and artifacts. You must be careful about what information is output to the build logs. Some best practices are:
  + Do not store sensitive values, especially AWS access key IDs and secret access keys, in environment variables. We recommend that you use an Amazon EC2 Systems Manager Parameter Store or AWS Secrets Manager to store sensitive values.
  + Follow [Best practices for using webhooks](webhooks.md#webhook-best-practices) to limit which entities can trigger a build, and do not store the buildspec in the project itself, to ensure that your webhooks are as secure as possible.
+ A malicious user can use public builds to distribute malicious artifacts. We recommend that project administrators review all pull requests to verify that the pull request is a legitimate change. We also recommend that you validate any artifacts with their checksums to make sure that the correct artifacts are being downloaded.

**Additional information**  
For **Tags**, enter the name and value of any tags that you want supporting AWS services to use. Use **Add row** to add a tag. You can add up to 50 tags. 

### Source
<a name="change-project-console-source"></a>

In the **Source** section, choose **Edit**. When your changes are complete, choose **Update configuration** to save the new configuration. 

You can modify the following properties:

**Source provider**  
Choose the source code provider type. Use the following lists to make selections appropriate for your source provider:  
CodeBuild does not support Bitbucket Server.

------
#### [ Amazon S3 ]

 **Bucket**   
Choose the name of the input bucket that contains the source code. 

 **S3 object key or S3 folder**   
Enter the name of the ZIP file or the path to the folder that contains the source code. Enter a forward slash (/) to download everything in the S3 bucket. 

 **Source version**   
Enter the version ID of the object that represents the build of your input file. For more information, see[Source version sample with AWS CodeBuild](sample-source-version.md). 

------
#### [ CodeCommit ]

 **Repository**   
Choose the repository you want to use.

**Reference type**  
Choose **Branch**, **Git tag**, or **Commit ID** to specify the version of your source code. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).  
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Git submodules**  
Select **Use Git submodules** if you want to include Git submodules in your repository. 

------
#### [ Bitbucket ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
Choose **CodeConnections**, **OAuth**, **App password**, or **Personal access token** to connect to CodeBuild.

 **Connection**   
Select a Bitbucket connection or a Secrets Manager secret to connect through your specified connection type.

 **Repository**   
Choose **Repository in my Bitbucket account** or **Public repository** and enter the repository URL.

 **Source version**   
Enter a branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md)   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Git submodules**  
Select **Use Git submodules** if you want to include Git submodules in your repository. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).  
For **Status context**, enter the value to be used for the `name` parameter in the Bitbucket commit status. For more information, see [build](https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build) in the Bitbucket API documentation.  
For **Target URL**, enter the value to be used for the `url` parameter in the Bitbucket commit status. For more information, see [build](https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/commit/%7Bnode%7D/statuses/build) in the Bitbucket API documentation.  
The status of a build triggered by a webhook is always reported to the source provider. To have the status of a build that is started from the console or an API call reported to the source provider, you must select this setting.  
If your project's builds are triggered by a webhook, you must push a new commit to the repo for a change to this setting to take effect.

In **Primary source webhook events**, select **Rebuild every time a code change is pushed to this repository ** if you want CodeBuild to build the source code every time a code change is pushed to this repository. For more information about webhooks and filter groups, see [Bitbucket webhook events](bitbucket-webhook.md).

------
#### [ GitHub ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
Choose **GitHub App**, **OAuth**, or **Personal access token** to connect to CodeBuild.

 **Connection**   
Select a GitHub connection or a Secrets Manager secret to connect through your specified connection type.

 **Repository**   
Choose **Repository in my GitHub account**, **Public repository**, or **GitHub scoped webhook** and enter the repository URL.

 **Source version**   
Enter a branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md)   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Git submodules**  
Select **Use Git submodules** if you want to include Git submodules in your repository. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).  
For **Status context**, enter the value to be used for the `context` parameter in the GitHub commit status. For more information, see [Create a commit status](https://developer.github.com/v3/repos/statuses/#create-a-commit-status) in the GitHub developer guide.  
For **Target URL**, enter the value to be used for the `target_url` parameter in the GitHub commit status. For more information, see [Create a commit status](https://developer.github.com/v3/repos/statuses/#create-a-commit-status) in the GitHub developer guide.  
The status of a build triggered by a webhook is always reported to the source provider. To have the status of a build that is started from the console or an API call reported to the source provider, you must select this setting.  
If your project's builds are triggered by a webhook, you must push a new commit to the repo for a change to this setting to take effect.

In **Primary source webhook events**, select **Rebuild every time a code change is pushed to this repository ** if you want CodeBuild to build the source code every time a code change is pushed to this repository. For more information about webhooks and filter groups, see [GitHub webhook events](github-webhook.md).

------
#### [ GitHub Enterprise Server ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
Choose **CodeConnections** or **Personal access token** to connect to CodeBuild.

 **Connection**   
Select a GitHub Enterprise connection or a Secrets Manager secret to connect through your specified connection type.

 **Repository**   
Choose **Repository in my GitHub Enterprise account** or **GitHub Enterprise scoped webhook** and enter the repository URL.

**Source version**  
Enter a pull request, branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

**Git clone depth**  
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Git submodules**  
Select **Use Git submodules** if you want to include Git submodules in your repository. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).  
For **Status context**, enter the value to be used for the `context` parameter in the GitHub commit status. For more information, see [Create a commit status](https://developer.github.com/v3/repos/statuses/#create-a-commit-status) in the GitHub developer guide.  
For **Target URL**, enter the value to be used for the `target_url` parameter in the GitHub commit status. For more information, see [Create a commit status](https://developer.github.com/v3/repos/statuses/#create-a-commit-status) in the GitHub developer guide.  
The status of a build triggered by a webhook is always reported to the source provider. To have the status of a build that is started from the console or an API call reported to the source provider, you must select this setting.  
If your project's builds are triggered by a webhook, you must push a new commit to the repo for a change to this setting to take effect.

**Insecure SSL**  
Select **Enable insecure SSL** to ignore SSL warnings while connecting to your GitHub Enterprise project repository. 

In **Primary source webhook events**, select **Rebuild every time a code change is pushed to this repository ** if you want CodeBuild to build the source code every time a code change is pushed to this repository. For more information about webhooks and filter groups, see [GitHub webhook events](github-webhook.md).

------
#### [ GitLab ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
**CodeConnections** is used to connect GitLab to CodeBuild.

 **Connection**   
Select a GitLab connection to connect through CodeConnections.

 **Repository**   
Choose the repository you want to use.

 **Source version**   
Enter a pull request ID, branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).

------
#### [ GitLab Self Managed ]

 **Credential**   
Choose **Default source credential** or **Custom source credential** and follow the instructions to manage the default source credential or customize the source credential.

 **Connection type**   
**CodeConnections** is used to connect GitLab Self Managed to CodeBuild.

 **Connection**   
Select a GitLab Self Managed connection to connect through CodeConnections.

 **Repository**   
Choose the repository you want to use.

 **Source version**   
Enter a pull request ID, branch, commit ID, tag, or reference and a commit ID. For more information, see [Source version sample with AWS CodeBuild](sample-source-version.md).   
We recommend that you choose Git branch names that don't look like commit IDs, such as `811dd1ba1aba14473856cee38308caed7190c0d` or `5392f7`. This helps you avoid Git checkout collisions with actual commits.

 **Git clone depth**   
Choose **Git clone depth** to create a shallow clone with a history truncated to the specified number of commits. If you want a full clone, choose **Full**. 

**Build status**  
Select **Report build statuses to source provider when your builds start and finish ** if you want the status of your build's start and completion reported to your source provider.   
To be able to report the build status to the source provider, the user associated with the source provider must have write access to the repo. If the user does not have write access, the build status cannot be updated. For more information, see [Source provider access](access-tokens.md).

------

### Environment
<a name="change-project-console-environment"></a>

In the **Environment** section, choose **Edit**. When your changes are complete, choose **Update configuration** to save the new configuration. 

You can modify the following properties:

**Provisioning model**  
To change the provisioning model, choose **Change provisioning model** and do one of the following:  
+ To use on-demand fleets managed by AWS CodeBuild, choose **On-demand**. With on-demand fleets, CodeBuild provides compute for your builds. The machines are destroyed when the build finishes. On-demand fleets are fully managed, and includes automatic scaling capabilities to handle spikes in demand.
+ To use reserved capacity fleets managed by AWS CodeBuild, choose **Reserved capacity**, and then select a **Fleet name**. With reserved capacity fleets, you configure a set of dedicated instances for your build environment. These machines remain idle, ready to process builds or tests immediately and reduces build durations. With reserved capacity fleets, your machines are always running and will continue to incur costs as long they're provisioned.
For information, see [Run builds on reserved capacity fleets](fleets.md).

**Environment image**  
To change the build image, choose **Override image** and do one of the following:  
+ To use a Docker image managed by AWS CodeBuild, choose **Managed image**, and then make selections from **Operating system**, **Runtime(s)**, **Image**, and **Image version**. Make a selection from **Environment type** if it is available.
+ To use another Docker image, choose **Custom image**. For **Environment type**, choose **ARM**, **Linux**, **Linux GPU**, or **Windows**. If you choose **Other registry**, for **External registry URL**, enter the name and tag of the Docker image in Docker Hub, using the format `docker repository/docker image name`. If you choose **Amazon ECR**, use **Amazon ECR repository** and **Amazon ECR image** to choose the Docker image in your AWS account.
+ To use a private Docker image, choose **Custom image**. For **Environment type**, choose **ARM**, **Linux**, **Linux GPU**, or **Windows**. For **Image registry**, choose **Other registry**, and then enter the ARN of the credentials for your private Docker image. The credentials must be created by Secrets Manager. For more information, see [What Is AWS Secrets Manager?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/) in the *AWS Secrets Manager User Guide*.
CodeBuild overrides the `ENTRYPOINT` for custom Docker images.

**Service role**  
Do one of the following:  
+ If you do not have a CodeBuild service role, choose **New service role**. In **Role name**, enter a name for the new role.
+ If you have a CodeBuild service role, choose **Existing service role**. In **Role ARN**, choose the service role.
When you use the console to create a build project, you can create a CodeBuild service role at the same time. By default, the role works with that build project only. If you use the console to associate this service role with another build project, the role is updated to work with the other build project. A service role can work with up to 10 build projects.

**Additional configuration**    
**Timeout**  
Specify a value, between 5 minutes and 36 hours, after which CodeBuild stops the build if it is not complete. If **hours** and **minutes** are left blank, the default value of 60 minutes is used.  
**Privileged**  
Select **Enable this flag if you want to build Docker images or want your builds to get elevated privileges.** only if you plan to use this build project to build Docker images. Otherwise, all associated builds that attempt to interact with the Docker daemon fail. You must also start the Docker daemon so that your builds can interact with it. One way to do this is to initialize the Docker daemon in the `install` phase of your build spec by running the following build commands. Do not run these commands if you chose a build environment image provided by CodeBuild with Docker support.  
By default, Docker daemon is enabled for non-VPC builds. If you would like to use Docker containers for VPC builds, see [Runtime Privilege and Linux Capabilities](https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities) on the Docker Docs website and enable privileged mode. Also, Windows does not support privileged mode.

```
- nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2 &
- timeout 15 sh -c "until docker info; do echo .; sleep 1; done"
```  
**VPC**  
If you want CodeBuild to work with your VPC:  
+ For **VPC**, choose the VPC ID that CodeBuild uses.
+ For **VPC Subnets**, choose the subnets that include resources that CodeBuild uses.
+ For **VPC Security groups**, choose the security groups that CodeBuild uses to allow access to resources in the VPCs.
For more information, see [Use AWS CodeBuild with Amazon Virtual Private Cloud](vpc-support.md).  
**Compute**  
Choose one of the available options.  
**Registry credential**  
Specify a registry credential when the project is configured with a non-private registry image.  
This credential will only be utilized if the images are overridden with those from private registries.  
**Environment variables**  
Enter the name and value, and then choose the type of each environment variable for builds to use.   
CodeBuild sets the environment variable for your AWS Region automatically. You must set the following environment variables if you haven't added them to your buildspec.yml:  
+ AWS\$1ACCOUNT\$1ID
+ IMAGE\$1REPO\$1NAME
+ IMAGE\$1TAG
Console and AWS CLI users can see environment variables. If you have no concerns about the visibility of your environment variable, set the **Name** and **Value** fields, and then set **Type** to **Plaintext**.  
We recommend that you store an environment variable with a sensitive value, such as an AWS access key ID, an AWS secret access key, or a password as a parameter in Amazon EC2 Systems Manager Parameter Store or AWS Secrets Manager.   
If you use Amazon EC2 Systems Manager Parameter Store, then for **Type**, choose **Parameter**. For **Name**, enter an identifier for CodeBuild to reference. For **Value**, enter the parameter's name as stored in Amazon EC2 Systems Manager Parameter Store. Using a parameter named `/CodeBuild/dockerLoginPassword` as an example, for **Type**, choose **Parameter**. For **Name**, enter `LOGIN_PASSWORD`. For **Value**, enter `/CodeBuild/dockerLoginPassword`.   
If you use Amazon EC2 Systems Manager Parameter Store, we recommend that you store parameters with parameter names that start with `/CodeBuild/` (for example, `/CodeBuild/dockerLoginPassword`). You can use the CodeBuild console to create a parameter in Amazon EC2 Systems Manager. Choose **Create parameter**, and then follow the instructions in the dialog box. (In that dialog box, for **KMS key**, you can specify the ARN of an AWS KMS key in your account. Amazon EC2 Systems Manager uses this key to encrypt the parameter's value during storage and decrypt it during retrieval.) If you use the CodeBuild console to create a parameter, the console starts the parameter name with `/CodeBuild/` as it is being stored. For more information, see [Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-paramstore.html) and [Systems Manager Parameter Store Console Walkthrough](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-paramstore-walk.html#sysman-paramstore-console) in the *Amazon EC2 Systems Manager User Guide*.  
If your build project refers to parameters stored in Amazon EC2 Systems Manager Parameter Store, the build project's service role must allow the `ssm:GetParameters` action. If you chose **New service role** earlier, CodeBuild includes this action in the default service role for your build project. However, if you chose **Existing service role**, you must include this action to your service role separately.  
If your build project refers to parameters stored in Amazon EC2 Systems Manager Parameter Store with parameter names that do not start with `/CodeBuild/`, and you chose **New service role**, you must update that service role to allow access to parameter names that do not start with `/CodeBuild/`. This is because that service role allows access only to parameter names that start with `/CodeBuild/`.  
If you choose **New service role**, the service role includes permission to decrypt all parameters under the `/CodeBuild/` namespace in the Amazon EC2 Systems Manager Parameter Store.  
Environment variables you set replace existing environment variables. For example, if the Docker image already contains an environment variable named `MY_VAR` with a value of `my_value`, and you set an environment variable named `MY_VAR` with a value of `other_value`, then `my_value` is replaced by `other_value`. Similarly, if the Docker image already contains an environment variable named `PATH` with a value of `/usr/local/sbin:/usr/local/bin`, and you set an environment variable named `PATH` with a value of `$PATH:/usr/share/ant/bin`, then `/usr/local/sbin:/usr/local/bin` is replaced by the literal value `$PATH:/usr/share/ant/bin`.  
Do not set any environment variable with a name that begins with `CODEBUILD_`. This prefix is reserved for internal use.  
If an environment variable with the same name is defined in multiple places, the value is determined as follows:  
+ The value in the start build operation call takes highest precedence.
+ The value in the build project definition takes next precedence.
+ The value in the buildspec declaration takes lowest precedence.
If you use Secrets Manager, for **Type**, choose **Secrets Manager**. For **Name**, enter an identifier for CodeBuild to reference. For **Value**, enter a `reference-key` using the pattern `secret-id:json-key:version-stage:version-id`. For information, see [Secrets Manager reference-key in the buildspec file](build-spec-ref.md#secrets-manager-build-spec).  
If you use Secrets Manager, we recommend that you store secrets with names that start with `/CodeBuild/` (for example, `/CodeBuild/dockerLoginPassword`). For more information, see [What Is AWS Secrets Manager?](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) in the *AWS Secrets Manager User Guide*.   
If your build project refers to secrets stored in Secrets Manager, the build project's service role must allow the `secretsmanager:GetSecretValue` action. If you chose **New service role** earlier, CodeBuild includes this action in the default service role for your build project. However, if you chose **Existing service role**, you must include this action to your service role separately.   
If your build project refers to secrets stored in Secrets Manager with secret names that do not start with `/CodeBuild/`, and you chose **New service role**, you must update the service role to allow access to secret names that do not start with `/CodeBuild/`. This is because the service role allows access only to secret names that start with `/CodeBuild/`.  
If you choose **New service role**, the service role includes permission to decrypt all secrets under the `/CodeBuild/` namespace in the Secrets Manager.

### Buildspec
<a name="change-project-console-buildspec"></a>

In the **Buildspec** section, choose **Edit**. When your changes are complete, choose **Update configuration** to save the new configuration. 

You can modify the following properties:

**Build specifications**  
Do one of the following:  
+ If your source code includes a buildspec file, choose **Use a buildspec file**. By default, CodeBuild looks for a file named `buildspec.yml` in the source code root directory. If your buildspec file uses a different name or location, enter its path from the source root in **Buildspec name** (for example, `buildspec-two.yml` or `configuration/buildspec.yml`. If the buildspec file is in an S3 bucket, it must be in the same AWS Region as your build project. Specify the buildspec file using its ARN (for example, `arn:aws:s3:::<my-codebuild-sample2>/buildspec.yml`).
+ If your source code does not include a buildspec file, or if you want to run build commands different from the ones specified for the `build` phase in the `buildspec.yml` file in the source code's root directory, choose **Insert build commands**. For **Build commands**, enter the commands you want to run in the `build` phase. For multiple commands, separate each command by `&&` (for example, `mvn test && mvn package`). To run commands in other phases, or if you have a long list of commands for the `build` phase, add a `buildspec.yml` file to the source code root directory, add the commands to the file, and then choose **Use the buildspec.yml in the source code root directory**.
For more information, see the [Buildspec reference](build-spec-ref.md).

### Batch configuration
<a name="change-project-console-batch-config"></a>

In the **Batch configuration** section, choose **Edit**. When your changes are complete, choose **Update configuration** to save the new configuration. For more information, see [Run builds in batches](batch-build.md).

You can modify the following properties:

**Batch service role**  
Provides the service role for batch builds.   
Choose one of the following:  
+ If you do not have a batch service role, choose **New service role**. In **Service role**, enter a name for the new role.
+ If you have a batch service role, choose **Existing service role**. In **Service role**, choose the service role.
Batch builds introduce a new security role in the batch configuration. This new role is required as CodeBuild must be able to call the `StartBuild`, `StopBuild`, and `RetryBuild` actions on your behalf to run builds as part of a batch. Customers should use a new role, and not the same role they use in their build, for two reasons:  
+ Giving the build role `StartBuild`, `StopBuild`, and `RetryBuild` permissions would allow a single build to start more builds via the buildspec.
+ CodeBuild batch builds provide restrictions that restrict the number of builds and compute types that can be used for the builds in the batch. If the build role has these permissions, it is possible the builds themselves could bypass these restrictions.

**Allowed compute types for batch**  
Select the compute types allowed for the batch. Select all that apply.

**Allowed fleets for batch**  
Select the fleets allowed for the batch. Select all that apply.

**Maximum builds allowed in batch**  
Enter the maximum number of builds allowed in the batch. If a batch exceeds this limit, the batch will fail.

**Batch timeout**  
Enter the maximum amount of time for the batch build to complete.

**Combine artifacts**  
Select **Combine all artifacts from batch into a single location** to have all of the artifacts from the batch combined into a single location.

 **Batch report mode**   
Select the desired build status report mode for batch builds.  
This field is only available when the project source is Bitbucket, GitHub, or GitHub Enterprise, and **Report build statuses to source provider when your builds start and finish** is selected under **Source**.   
 **Aggregated builds**   
Select to have the statuses for all builds in the batch combined into a single status report.  
 **Individual builds**   
Select to have the build statuses for all builds in the batch reported separately.

### Artifacts
<a name="change-project-console-artifacts"></a>

In the **Artifacts** section, choose **Edit**. When your changes are complete, choose **Update configuration** to save the new configuration. 

You can modify the following properties:

**Type**  
Do one of the following:  
+ If you do not want to create any build output artifacts, choose **No artifacts**. You might want to do this if you're only running build tests or you want to push a Docker image to an Amazon ECR repository.
+ To store the build output in an S3 bucket, choose **Amazon S3**, and then do the following:
  + If you want to use your project name for the build output ZIP file or folder, leave **Name** blank. Otherwise, enter the name. (If you want to output a ZIP file, and you want the ZIP file to have a file extension, be sure to include it after the ZIP file name.)
  + Select **Enable semantic versioning** if you want a name specified in the buildspec file to override any name that is specified in the console. The name in a buildspec file is calculated at build time and uses the Shell command language. For example, you can append a date and time to your artifact name so that it is always unique. Unique artifact names prevent artifacts from being overwritten. For more information, see [Buildspec syntax](build-spec-ref.md#build-spec-ref-syntax).
  + For **Bucket name**, choose the name of the output bucket.
  + If you chose **Insert build commands** earlier in this procedure, then for **Output files**, enter the locations of the files from the build that you want to put into the build output ZIP file or folder. For multiple locations, separate each location with a comma (for example, `appspec.yml, target/my-app.jar`). For more information, see the description of `files` in [Buildspec syntax](build-spec-ref.md#build-spec-ref-syntax).
  + If you do not want your build artifacts encrypted, select **Remove artifacts encryption**.
For each secondary set of artifacts you want:  

1. For **Artifact identifier**, enter a value that is fewer than 128 characters and contains only alphanumeric characters and underscores.

1. Choose **Add artifact**.

1. Follow the previous steps to configure your secondary artifacts.

1. Choose **Save artifact**.

**Additional configuration**    
**Encryption key**  
Do one of the following:  
+ To use the AWS managed key Amazon S3 in your account to encrypt the build output artifacts, leave **Encryption key** blank. This is the default.
+ To use a customer managed key to encrypt the build output artifacts, in **Encryption key**, enter the ARN of the customer managed key. Use the format `arn:aws:kms:region-ID:account-ID:key/key-ID`.  
**Cache type**  
For **Cache type**, choose one of the following:  
+ If you do not want to use a cache, choose **No cache**.
+ If you want to use an Amazon S3 cache, choose **Amazon S3**, and then do the following:
  + For **Bucket**, choose the name of the S3 bucket where the cache is stored.
  + (Optional) For **Cache path prefix**, enter an Amazon S3 path prefix. The **Cache path prefix** value is similar to a directory name. It makes it possible for you to store the cache under the same directory in a bucket. 
**Important**  
Do not append a trailing slash (/) to the end of the path prefix.
+  If you want to use a local cache, choose **Local**, and then choose one or more local cache modes. 
**Note**  
Docker layer cache mode is available for Linux only. If you choose it, your project must run in privileged mode. 
Using a cache saves considerable build time because reusable pieces of the build environment are stored in the cache and used across builds. For information about specifying a cache in the buildspec file, see [Buildspec syntax](build-spec-ref.md#build-spec-ref-syntax). For more information about caching, see [Cache builds to improve performance](build-caching.md). 

### Logs
<a name="change-project-console-logs"></a>

In the **Logs** section, choose **Edit**. When your changes are complete, choose **Update configuration** to save the new configuration. 

You can modify the following properties:

Choose the logs you want to create. You can create Amazon CloudWatch Logs, Amazon S3 logs, or both. 

**CloudWatch**  
If you want Amazon CloudWatch Logs logs:    
**CloudWatch logs**  
Select **CloudWatch logs**.  
**Group name**  
Enter the name of your Amazon CloudWatch Logs log group.  
**Stream name**  
Enter your Amazon CloudWatch Logs log stream name. 

**S3**  
If you want Amazon S3 logs:    
**S3 logs**  
Select **S3 logs**.  
**Bucket**  
Choose the name of the S3 bucket for your logs.   
**Path prefix**  
Enter the prefix for your logs.   
**Disable S3 log encryption**  
Select if you do not want your S3 logs encrypted. 

## Change a build project's settings (AWS CLI)
<a name="change-project-cli"></a>

For information about using the AWS CLI with AWS CodeBuild, see the [Command line reference](cmd-ref.md).

To update a CodeBuild project with the AWS CLI, you create a JSON file with the updated properties and pass that file to the [https://docs.aws.amazon.com/cli/latest/reference/codebuild/update-project.html](https://docs.aws.amazon.com/cli/latest/reference/codebuild/update-project.html) command. Any properties not contained in the update file remain unchanged.

In the update JSON file, only the `name` property and the modified properties are required. The `name` property identifies the project to modify. For any modified structures, the required parameters for those structures must also be included. For example, to modify the environment for the project, the `environment/type` and `environment/computeType` properties are required. Here is an example that updates the environment image:

```
{
  "name": "<project-name>",
  "environment": {
    "type": "LINUX_CONTAINER",
    "computeType": "BUILD_GENERAL1_SMALL",
    "image": "aws/codebuild/amazonlinux-x86_64-standard:4.0"
  }
}
```

If you need to obtain the current property values for a project, use the [https://docs.aws.amazon.com/cli/latest/reference/codebuild/batch-get-projects.html](https://docs.aws.amazon.com/cli/latest/reference/codebuild/batch-get-projects.html) command to obtain the current properties of the project you are modifying, and write the output to a file.

```
aws codebuild batch-get-projects --names "<project-name>" > project-info.json
```

The *project-info.json* file contains an array of projects, so it cannot be used directly to update a project. You can, however, copy the properties that you want to modify from the *project-info.json* file and paste them into your update file as a baseline for the properties you want to modify. For more information, see [View a build project's details (AWS CLI)](view-project-details.md#view-project-details-cli).

Modify the update JSON file as described in [Create a build project (AWS CLI)](create-project.md#create-project-cli), and save your results. When you are finished modifying the update JSON file, run the [https://docs.aws.amazon.com/cli/latest/reference/codebuild/update-project.html](https://docs.aws.amazon.com/cli/latest/reference/codebuild/update-project.html) command, passing the update JSON file.

```
aws codebuild update-project --cli-input-json file://<update-project-file>
```

If successful, the updated project JSON appears in the output. If any required parameters are missing, an error message is displayed in the output that identifies the missing parameters. For example, this is the error message displayed if the `environment/type` parameter is missing:

```
aws codebuild update-project --cli-input-json file://update-project.json

Parameter validation failed:
Missing required parameter in environment: "type"
```

## Change a build project's settings (AWS SDKs)
<a name="change-project-sdks"></a>

For information about using AWS CodeBuild with the AWS SDKs, see the [AWS SDKs and tools reference](sdk-ref.md).

# Multiple access tokens in CodeBuild
<a name="multiple-access-tokens"></a>

CodeBuild supports sourcing access tokens to third party providers from your secrets in AWS Secrets Manager or through AWS CodeConnections connections. You can set your secret or connection as the default credential for interactions with a specified third party provider such as GitHub, GitHub Enterprise, or Bitbucket.

You can set your source credentials at three different levels:

1. **Account level credentials for all projects:** These are default credentials for all projects in an AWS account. They will be used on a project when no project or source level credentials are specified.

1. **Source level credentials for a specific repository:** This is when a Secrets Manager secret or CodeConnections connection is defined on a project source. These credentials will only be used for operations on the specified source repository. This allows you to set up multiple access tokens with different permission scopes in the same project, and not use the default account level credentials.

1. **Project level fallback credentials:** You can set a project level fallback credential by using `NO_SOURCE` as primary source type and define a secret or connection on it. This is can be used when you have multiple sources on a project, but want to use the same credentials for them, or when you don't want to use the default account level credentials for your project.

**Topics**
+ [

## Step 1: Create a Secrets Manager secret or a CodeConnections connection
](#create-secret-connection)
+ [

## Step 2: Grant CodeBuild project IAM role access to Secrets Manager secrets
](#asm-role-access)
+ [

## Step 3: Configure Secrets Manager or CodeConnections tokens
](#asm-account-credential)
+ [

## Additional setup options
](#asm-credential-cfn)

## Step 1: Create a Secrets Manager secret or a CodeConnections connection
<a name="create-secret-connection"></a>

Use the following instructions to create a Secrets Manager secret or a CodeConnections connection:
+ [Create and store a token in a Secrets Manager secret](asm-create-secret.md).
+ [Create a connection to GitHub](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-create-github.html)
+ [Create a connection to to GitHub Enterprise Server](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-create-gheserver.html)
+ [Create a connection to Bitbucket](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-create-bitbucket.html)

## Step 2: Grant CodeBuild project IAM role access to Secrets Manager secrets
<a name="asm-role-access"></a>

**Note**  
Before you continue, you must have access to the token created in Secrets Manager or CodeConnections.

To grant CodeBuild project IAM role access to Secrets Manager or CodeConnections, you must add the following IAM policy.

**To grant CodeBuild project IAM role access**

1. Create an IAM role for your CodeBuild project by following the instructions to [Allow CodeBuild to interact with other AWS services](setting-up-service-role.md) for your CodeBuild project.

1. Do one of the following:
   + Add the following IAM policy to your CodeBuild project role to grant access to your secret.

------
#### [ JSON ]

****  

     ```
     {
         "Version":"2012-10-17",		 	 	 
         "Statement": [
             {
                 "Effect": "Allow",
                 "Action": [
                     "secretsmanager:GetSecretValue"
                 ],
                 "Resource": [
                     "arn:aws:iam::*:role/Service*"
                 ]
             }
         ]
     }
     ```

------

     (Optional) If you're using AWS KMS customer managed keys to encrypt a Secrets Manager secret, you can add the following policy statement to grant access.

------
#### [ JSON ]

****  

     ```
     {
         "Version":"2012-10-17",		 	 	 
         "Statement": [
             {
                 "Effect": "Allow",
                 "Action": [
                     "kms:Decrypt"
                 ],
                 "Resource": "arn:aws:iam::*:role/Service*",
                 "Condition": {
                     "StringEquals": {
                         "kms:EncryptionContext:SecretARN": "arn:aws:iam::*:role/Service*"
                     }
                 }
             }
         ]
     }
     ```

------
   + Add the following IAM policy to your CodeBuild project role to grant access to your connection.

------
#### [ JSON ]

****  

     ```
     {
         "Version":"2012-10-17",		 	 	 
         "Statement": [
             {
                 "Effect": "Allow",
                 "Action": [
                     "codeconnections:GetConnectionToken",
                     "codeconnections:GetConnection"
                 ],
                 "Resource": [
                     "arn:aws:iam::*:role/Service*"
                 ]
             }
         ]
     }
     ```

------

## Step 3: Configure Secrets Manager or CodeConnections tokens
<a name="asm-account-credential"></a>

You can set your source credentials at three different levels with either Secrets Manager or CodeConnections tokens.

### Configure Secrets Manager or CodeConnections tokens as account level credentials
<a name="asm-account-credential"></a>

You can configure a Secrets Manager secret or CodeConnections connection as an account level credential and use it in a project.

------
#### [ AWS Management Console ]

**To configure a connection as an account level credential in the AWS Management Console**

1. For **Source provider**, choose **Bitbucket**, **GitHub**, or **GitHub Enterprise**. 

1. For **Credential**, do one of the following:
   + Choose **Default source credential** to use your account's default source credential to apply to all projects.

     1. If you aren't connected to your source provider, choose **Manage default source credential**.

     1. For **Credential type**, choose a credential type.

     1. If you chose **CodeConnections**, choose to use an existing connection or create a new connection.

        If you chose a different credential type, for **Service** choose which service you'd like to use to store your token and do the following:
        + If you chose to use **Secrets Manager**, you can choose to use an existing secret connection or create a new secret and choose **Save**. For more information how to create a new secret, see [Create and store a token in a Secrets Manager secret](asm-create-secret.md).
        + If you chose to use **CodeBuild**, enter your token or your username and app password, and choose **Save**.
   + Choose **Custom source credential** to use a custom source credential to override your account's default settings.

     1. For **Credential type**, choose a credential type.

     1. In **Connection**, choose to use an existing connection or create a new connection.

------
#### [ AWS CLI ]

**To configure a connection as an account level credential in the AWS CLI**
+ Open a terminal (Linux, macOS, or Unix) or command prompt (Windows). Use the AWS CLI to run the **import-source-credentials** command.

  Use the following command to configure a Secrets Manager secret:

  ```
  aws codebuild import-source-credentials \
      --token "<secret-arn>" \
      --server-type <source-provider> \
      --auth-type SECRETS_MANAGER \
      --region <aws-region>
  ```

  Use the following command to configure a CodeConnections connection:

  ```
  aws codebuild import-source-credentials \
      --token "<connection-arn>" \
      --server-type <source-provider> \
      --auth-type CODECONNECTIONS \
      --region <aws-region>
  ```

  This command allows you to import a token as the account level default source credentials. When you import a credential using the [ImportSourceCredentials](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ImportSourceCredentials.html) API, CodeBuild will use the token for all interactions with the source provider, such as webhooks, build status reporting and git clone operations unless a more specific set of credentials has been configured in the project.

------

You can now use the token in your build project and run it. For more information, see [Create a build project in AWS CodeBuild](create-project.md) and [Run AWS CodeBuild builds manually](run-build.md).

### Configure multiple tokens as source level credentials
<a name="asm-source-credential"></a>

To use Secrets Manager secrets or CodeConnections connections as source level credentials, directly reference the token in CodeBuild project, and start a build.

------
#### [ AWS Management Console ]

**To configure multiple tokens as source level credentials in the AWS Management Console**

1. For **Source provider**, choose **GitHub**. 

1. For **Credential**, do one of the following:
   + Choose **Default source credential** to use your account's default source credential to apply to all projects.

     1. If you aren't connected to GitHub, choose **Manage default source credential**.

     1. For **Credential type**, choose **GitHub App**.

     1. In **Connection**, choose to use an existing connection or create a new connection.
   + Choose **Custom source credential** to use a custom source credential to override your account's default settings.

     1. For **Credential type**, choose **GitHub App**.

     1. In **Connection**, choose to use an existing connection or create a new connection.

1. Choose **Add source** and repeat the process of choosing your source provider and credentials.

------
#### [ AWS CLI ]

**To configure multiple tokens as source level credentials in the AWS CLI**
+ Open a terminal (Linux, macOS, or Unix) or command prompt (Windows). Use the AWS CLI to run the **create-project** command.

  Use the following command:

  ```
  aws codebuild create-project --region <aws-region> \
      --name <project-name> \
      --artifacts type=NO_ARTIFACTS \
      --environment "type=LINUX_CONTAINER,
                     computeType=BUILD_GENERAL1_SMALL,
                     image=aws/codebuild/amazonlinux-x86_64-standard:5.0" \
      --service-role <service-role-name> \
      --source "type=GITHUB,
                location=<github-repository-1>,
                auth={type=SECRETS_MANAGER,resource=<secret-or-connection-arn-1>}" \
      --secondary-sources "type=GITHUB,
                location=<github-repository-2>,
                auth={type=SECRETS_MANAGER,resource=<secret-or-connection-arn-2>},
                sourceIdentifier=secondary"
  
  aws codebuild start-build --region <aws-region> --project-name <project-name>
  ```

------

### Set a project level source credential fallback
<a name="asm-project-credential"></a>

To set up project level source credential fallback, use `NO_SOURCE` for your project's primary source and reference the token.

```
aws codebuild create-project \
    --name <project-name> \
    --service-role <service-role-name> \
    --artifacts type=NO_ARTIFACTS \
    --environment "type=LINUX_CONTAINER,
                   computeType=BUILD_GENERAL1_SMALL,
                   image=aws/codebuild/amazonlinux-x86_64-standard:5.0" \
    --service-role <service-role-name> \
    --source "type=NO_SOURCE,
              auth={type=SECRETS_MANAGER,resource=<secret-or-connection-arn>},
              buildspec=<buildspec>"
    --secondary-sources "type=GITHUB,
                         location=<github-repository>,
                         sourceIdentifier=secondary"

aws codebuild start-build --region <aws-region> --project-name <project_name>
```

When using `NO_SOURCE`, a buildspec typically is provided within the source model as it is not directly configured to use an external source to fetch the [buildspec](build-spec-ref.md). Commonly, a `NO_SOURCE` source will handle cloning all relevant repositories from within the buildspec. To ensure the configured credentials are available for those operations, you can enable the `git-credential-helper` option in the buildspec.

```
env:
  git-credential-helper: yes
```

During the build, CodeBuild will then read the `AuthServer` field from the configured token and use the token credentials for all git requests to that particular third party source provider.

## Additional setup options
<a name="asm-credential-cfn"></a>

You can configure Secrets Manager account level credentials by using CloudFormation templates. You can use the following CloudFormation template to set an account level credential:

```
Parameters:
  GitHubToken:
    Type: String
    NoEcho: true
    Default: placeholder
Resources:
  CodeBuildAuthTokenSecret:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: CodeBuild auth token
      Name: codebuild-auth-token
      SecretString:
        !Join
          - ''
          - - '{"ServerType":"GITHUB","AuthType":"PERSONAL_ACCESS_TOKEN","Token":"'
            - !Ref GitHubToken
            - '"}'
      Tags:
        - Key: codebuild:source:provider
          Value: github
        - Key: codebuild:source:type
          Value: personal_access_token
  CodeBuildSecretsManagerAccountCredential:
    Type: AWS::CodeBuild::SourceCredential
    Properties:
      ServerType: GITHUB
      AuthType: SECRETS_MANAGER
      Token: !Ref CodeBuildAuthTokenSecret
```

**Note**  
If you're also creating a project in the same stack, use the CloudFormation attribute [DependsOn](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-attribute-dependson.html) to ensure the `AccountCredential` is created before the project.

You can also configure Secrets Manager multiple source level credentials by using CloudFormation templates. You can use the following CloudFormation template to use multiple tokens to pull in multiple sources:

```
Parameters:
  GitHubTokenOne:
    Type: String
    NoEcho: true
    Default: placeholder
  GitHubTokenTwo:
    Type: String
    NoEcho: true
    Default: placeholder

Resources:
  CodeBuildSecretsManagerProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Name: codebuild-multitoken-example
      ServiceRole: <service-role>
      Environment:
        Type: LINUX_CONTAINER
        ComputeType: BUILD_GENERAL1_SMALL
        Image: aws/codebuild/amazonlinux-x86_64-standard:5.0
      Source:
        Type: GITHUB
        Location: <github-repository-one>
        Auth:
          Type: SECRETS_MANAGER
          Resource: !Ref CodeBuildAuthTokenSecretOne
      SecondarySources:
        - Type: GITHUB
          Location: <github-repository-two>
          Auth:
            Type: SECRETS_MANAGER
            Resource: !Ref CodeBuildAuthTokenSecretTwo
          SourceIdentifier: secondary
      Artifacts:
        Type: NO_ARTIFACTS
      LogsConfig:
        CloudWatchLogs:
          Status: ENABLED
  CodeBuildProjectIAMRoleSecretAccess:
    Type: AWS::IAM::RolePolicy
    Properties:
      RoleName: <role-name>
      PolicyName: CodeBuildProjectIAMRoleSecretAccessPolicy
      PolicyDocument:
        Version: '2012-10-17		 	 	 '
        Statement:
          - Effect: Allow
            Action:
              - secretsmanager:GetSecretValue
            Resource:
              - !Ref CodeBuildAuthTokenSecretOne
              - !Ref CodeBuildAuthTokenSecretTwo
  CodeBuildAuthTokenSecretOne:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: CodeBuild auth token one
      Name: codebuild-auth-token-one
      SecretString:
        !Join
          - ''
          - - '{"ServerType":"GITHUB","AuthType":"PERSONAL_ACCESS_TOKEN","Token":"'
            - !Ref GitHubTokenOne
            - '"}'
      Tags:
        - Key: codebuild:source:provider
          Value: github
        - Key: codebuild:source:type
          Value: personal_access_token
  CodeBuildAuthTokenSecretTwo:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: CodeBuild auth token two
      Name: codebuild-auth-token-two
      SecretString:
        !Join
          - ''
          - - '{"ServerType":"GITHUB","AuthType":"PERSONAL_ACCESS_TOKEN","Token":"'
            - !Ref GitHubTokenTwo
            - '"}'
      Tags:
        - Key: codebuild:source:provider
          Value: github
        - Key: codebuild:source:type
          Value: personal_access_token
```

# Delete build projects in AWS CodeBuild
<a name="delete-project"></a>

You can use the CodeBuild console, AWS CLI, or AWS SDKs to delete a build project in CodeBuild. If you delete a project, its builds are not deleted.

**Warning**  
You cannot delete a project that has builds and a resource policy. To delete a project with a resource policy and builds, you must first remove the resource policy and delete its builds. 

**Topics**
+ [

## Delete a build project (console)
](#delete-project-console)
+ [

## Delete a build project (AWS CLI)
](#delete-project-cli)
+ [

## Delete a build project (AWS SDKs)
](#delete-project-sdks)

## Delete a build project (console)
<a name="delete-project-console"></a>

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. In the navigation pane, choose **Build projects**.

1. Do one of the following:
   + Choose the radio button next to the build project you want to delete, and then choose **Delete**.
   + Choose the link for the build project you want to delete, and then choose **Delete**.
**Note**  
By default, only the most recent 10 build projects are displayed. To view more build projects, choose a different value for **Projects per page** or use the back and forward arrows for viewing projects.

## Delete a build project (AWS CLI)
<a name="delete-project-cli"></a>

1. Run the `delete-project` command:

   ```
   aws codebuild delete-project --name name
   ```

   Replace the following placeholder:
   + *name*: Required string. The name of the build project to delete. To get a list of available build projects, run the `list-projects` command. For more information, see [View a list of build project names (AWS CLI)](view-project-list.md#view-project-list-cli).

1. If successful, no data and no errors appear in the output.

For more information about using the AWS CLI with AWS CodeBuild, see the [Command line reference](cmd-ref.md).

## Delete a build project (AWS SDKs)
<a name="delete-project-sdks"></a>

For more information about using AWS CodeBuild with the AWS SDKs, see the [AWS SDKs and tools reference](sdk-ref.md).

# Get public build project URLs
<a name="public-builds"></a>

AWS CodeBuild allows you to make the build results, logs, and artifacts for your build projects available to the general public. This allows contributors to your source repositories to view the results and download the artifacts of a build, without requiring them to have access to an AWS account.<a name="public-builds.warning"></a>

When you make your project's builds available to the public, all of a project's build results, logs, and artifacts, including builds that were run when the project was private, are made available to the public. Likewise, when you make a public build project private, the build results for that project are no longer available to the public.

For information about how to change the public visibility of your project's build results, see [Enable public build access](change-project.md#change-project-console.public-builds).

CodeBuild provides a URL for the public builds for your project that is unique to your project.

To obtain the public URL for your build project, use the following procedure.

**To obtain the URL of a public build project**

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. In the navigation pane, choose **Build projects**.

1. Choose the link for the build project you want to obtain the public URL for. 

1. The public URL is displayed in the **Public project URL** field in the **Configuration** section. You can choose the link to open the URL, or copy the URL with the copy button.<a name="public-build-warning"></a>

**Warning**  
The following should be kept in mind when making your project's build results public:  
All of a project's build results, logs, and artifacts, including builds that were run when the project was private, are available to the public.
All build logs and artifacts are available to the public. Environment variables, source code, and other sensitive information may have been output to the build logs and artifacts. You must be careful about what information is output to the build logs. Some best practices are:  
Do not store sensitive values, especially AWS access key IDs and secret access keys, in environment variables. We recommend that you use an Amazon EC2 Systems Manager Parameter Store or AWS Secrets Manager to store sensitive values.
Follow [Best practices for using webhooks](webhooks.md#webhook-best-practices) to limit which entities can trigger a build, and do not store the buildspec in the project itself, to ensure that your webhooks are as secure as possible.
A malicious user can use public builds to distribute malicious artifacts. We recommend that project administrators review all pull requests to verify that the pull request is a legitimate change. We also recommend that you validate any artifacts with their checksums to make sure that the correct artifacts are being downloaded.

# Share build projects
<a name="project-sharing"></a>

Project sharing allows project owners to share their AWS CodeBuild projects with other AWS accounts or users. In this model, the account that owns the project (owner) shares a project with other accounts (consumers). A consumer cannot edit or run a project.

**Topics**
+ [

## Share a project
](#project-sharing-share)
+ [

## Related services
](#project-sharing-related)
+ [

# Access CodeBuild projects shared with you
](project-sharing-access-prereqs.md)
+ [

# Unshare a shared project
](project-sharing-unshare.md)
+ [

# Identify a shared project
](project-sharing-identify.md)
+ [

# Shared project permissions
](project-sharing-perms.md)

## Share a project
<a name="project-sharing-share"></a>

The consumer can use both the AWS CLI and AWS CodeBuild console to view the project and builds you've shared. The consumer cannot edit or run the project.

You can add a project to an existing resource share or you can create one in the [AWS RAM console](https://console.aws.amazon.com/ram).

**Note**  
You cannot delete a project with builds that has been added to a resource share. 

To share a project with organizational units or an entire organization, you must enable sharing with AWS Organizations. For more information, see [Enable sharing with AWS Organizations](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-sharing.html) in the *AWS RAM User Guide*.

You can use the AWS CodeBuild console, AWS RAM console, or the AWS CLI to share a project that you own.

**Prerequisites for sharing projects**  
Before you start sharing a project, make sure your AWS account owns it. You cannot share a project that has been shared with you. 

**To share a project that you own (CodeBuild console)**

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. In the navigation pane, choose **Build projects**.
**Note**  
By default, only the 10 most recent build projects are displayed. To view more build projects, choose the gear icon, and then choose a different value for **Projects per page** or use the back and forward arrows.

1. Choose the project you want to share, and then choose **Share**. For more information, see [Create a resource share](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-sharing.html#getting-started-sharing-create) in the *AWS RAM User Guide*. 

**To share a project that you own (AWS RAM console)**  
See [Creating a resource share](https://docs.aws.amazon.com/ram/latest/userguide/working-with-sharing.html#working-with-sharing-create) in the *AWS RAM User Guide*.

**To share a project that you own (AWS RAM command)**  
Use the [create-resource-share](https://docs.aws.amazon.com/cli/latest/reference/ram/create-resource-share.html) command.

**To share a project that you own (CodeBuild command)**<a name="codebuild-command"></a>

Use the [put-resource-policy](https://docs.aws.amazon.com/cli/latest/reference/codebuild/put-resource-policy.html) command:

1. Create a file named `policy.json` and copy the following into it. 

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement":[{
       "Effect":"Allow",
       "Action":[
         "codebuild:BatchGetProjects",
         "codebuild:BatchGetBuilds",
         "codebuild:ListBuildsForProject"],
       "Resource":"arn:aws:iam::*:role/Service*"
     }]
   }
   ```

------

1. Update `policy.json` with the project ARN and identifiers to share it with. The following example grants read-only access to the root user for the AWS account identified by 123456789012. 

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement":[{
       "Effect":"Allow",
       "Principal":{
         "AWS": [
           "123456789012"
         ]
       },
       "Action":[
         "codebuild:BatchGetProjects",
         "codebuild:BatchGetBuilds",
         "codebuild:ListBuildsForProject"],
       "Resource":"arn:aws:codebuild:us-west-2:123456789012:project/my-project"
     }]
   }
   ```

------

1. Run the [put-resource-policy](https://docs.aws.amazon.com/cli/latest/reference/codebuild/put-resource-policy.html) command.

   ```
   aws codebuild put-resource-policy --resource-arn <project-arn> --policy file://policy.json
   ```

1. Get the AWS RAM resource share ARN.

   ```
   aws ram list-resources --resource-owner SELF --resource-arns <project-arn>
   ```

   This will return a response similar to this:

   ```
   {
     "resources": [
       {
         "arn": "<project-arn>",
         "type": "<type>",
         "resourceShareArn": "<resource-share-arn>",
         "creationTime": "<creation-time>",
         "lastUpdatedTime": "<last-update-time>"
       }
     ]
   }
   ```

   From the response, copy the *<resource-share-arn>* value to use in the next step.

1. Run the AWS RAM [promote-resource-share-created-from-policy](https://docs.aws.amazon.com/cli/latest/reference/ram/promote-resource-share-created-from-policy.html) command.

   ```
   aws ram promote-resource-share-created-from-policy --resource-share-arn <resource-share-arn>
   ```

## Related services
<a name="project-sharing-related"></a>

Project sharing integrates with AWS Resource Access Manager (AWS RAM), a service that makes it possible for you to share your AWS resources with any AWS account or through AWS Organizations. With AWS RAM, you share resources by creating a *resource share* that specifies the resources and the consumers to share them with. Consumers can be individual AWS accounts, organizational units in AWS Organizations, or an entire organization in AWS Organizations.

For more information, see the *[AWS RAM User Guide](https://docs.aws.amazon.com/ram/latest/userguide/)*.

# Access CodeBuild projects shared with you
<a name="project-sharing-access-prereqs"></a>

To access a shared project, a consumer's IAM role requires the `BatchGetProjects` permission. You can attach the following policy to their IAM role: 

```
{
    "Effect": "Allow",
    "Resource": [
        "*"
    ],
    "Action": [
        "codebuild:BatchGetProjects"
    ]
}
```

 For more information, see [Using identity-based policies for AWS CodeBuild](auth-and-access-control-iam-identity-based-access-control.md). 

# Unshare a shared project
<a name="project-sharing-unshare"></a>

An unshared project, including its builds, can be accessed only by its owner. If you unshare a project, any AWS account or user you previously shared it with cannot access the project or its builds.

To unshare a shared project that you own, you must remove it from the resource share. You can use the AWS CodeBuild console, AWS RAM console, or AWS CLI to do this.

**To unshare a shared project that you own (AWS RAM console)**  
See [Updating a resource share](https://docs.aws.amazon.com/ram/latest/userguide/working-with-sharing.html#working-with-sharing-update) in the *AWS RAM User Guide*.

**To unshare a shared project that you own (AWS CLI)**  
Use the [disassociate-resource-share](https://docs.aws.amazon.com/cli/latest/reference/ram/disassociate-resource-share.html) command.

 ** To unshare project that you own (CodeBuild command)** 

Run the [delete-resource-policy](https://docs.aws.amazon.com/cli/latest/reference/codebuild/delete-resource-policy.html) command and specify the ARN of the project you want to unshare:

```
aws codebuild delete-resource-policy --resource-arn project-arn
```

# Identify a shared project
<a name="project-sharing-identify"></a>

Owners and consumers can use the AWS CLI to identify shared projects.

**To identify projects shared with your AWS account or user (AWS CLI)**  
Use the [list-shared-projects](https://docs.aws.amazon.com/cli/latest/reference/codebuild/list-shared-projects.html) command to return the projects that are shared with you.

# Shared project permissions
<a name="project-sharing-perms"></a>

## Permissions for owners
<a name="project-perms-owner"></a>

A project owner can edit the project and use it to run builds.

## Permissions for consumers
<a name="project-perms-consumer"></a>

A project consumer can view a project and its builds, but cannot edit a project or use it to run builds.

# Tag build projects
<a name="how-to-tag-project"></a>

A *tag* is a custom attribute label that you or AWS assigns to an AWS resource. Each AWS tag has two parts:
+ A *tag key* (for example, `CostCenter`, `Environment`, `Project`, or `Secret`). Tag keys are case sensitive.
+ An optional field known as a *tag value* (for example, `111122223333`, `Production`, or a team name). Omitting the tag value is the same as using an empty string. Like tag keys, tag values are case sensitive.

Together these are known as key-value pairs. For information about the number of tags you can have on a project and restrictions on tag keys and values, see [Tags](limits.md#tag-limits).

Tags help you identify and organize your AWS resources. Many AWS services support tagging, so you can assign the same tag to resources from different services to indicate that the resources are related. For example, you can assign the same tag to a CodeBuild project that you assign to an S3 bucket. For more information about using tags, see [Tagging Best Practices](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/tagging-best-practices.html).

In CodeBuild, the primary resources are the project and the report group. You can use the CodeBuild console, the AWS CLI, CodeBuild APIs, or AWS SDKs to add, manage, and remove tags for a project. In addition to identifying, organizing, and tracking your project with tags, you can use tags in IAM policies to help control who can view and interact with your project. For examples of tag-based access policies, see [Using tags to control access to AWS CodeBuild resources](auth-and-access-control-using-tags.md).

**Important**  
When using the reserved capacity feature, data cached on fleet instances, including source files, Docker layers, and cached directories specified in the buildspec, can be accessible to other projects within the same account. This is by design and allows projects within the same account to share fleet instances.

**Topics**
+ [

# Add a tag to a project
](how-to-tag-project-add.md)
+ [

# View tags for a project
](how-to-tag-project-list.md)
+ [

# Edit tags for a project
](how-to-tag-project-update.md)
+ [

# Remove a tag from a project
](how-to-tag-project-delete.md)

# Add a tag to a project
<a name="how-to-tag-project-add"></a>

Adding tags to a project can help you identify and organize your AWS resources and manage access to them. First, you add one or more tags (key-value pairs) to a project. Keep in mind that there are limits on the number of tags you can have on a project. There are restrictions on the characters you can use in the key and value fields. For more information, see [Tags](limits.md#tag-limits). After you have tags, you can create IAM policies to manage access to the project based on these tags. You can use the CodeBuild console or the AWS CLI to add tags to a project. 

**Important**  
When using the reserved capacity feature, data cached on fleet instances, including source files, Docker layers, and cached directories specified in the buildspec, can be accessible to other projects within the same account. This is by design and allows projects within the same account to share fleet instances.

For more information about adding tags to a project when you create it, see [Add a tag to a project (console)](#how-to-tag-project-add-console).

**Important**  
Before you add a tag to a project, make sure to review any IAM policies that might use tags to control access to resources such as build projects. For examples of tag-based access policies, see [Using tags to control access to AWS CodeBuild resources](auth-and-access-control-using-tags.md).

**Topics**
+ [

## Add a tag to a project (console)
](#how-to-tag-project-add-console)
+ [

## Add a tag to a project (AWS CLI)
](#how-to-tag-project-add-cli)

## Add a tag to a project (console)
<a name="how-to-tag-project-add-console"></a>

You can use the CodeBuild console to add one or more tags to a CodeBuild project. 

1. Open the CodeBuild console at [https://console.aws.amazon.com/codebuild/](https://console.aws.amazon.com/codebuild/).

1. In **Build projects**, choose the name of the project where you want to add tags.

1. In the navigation pane, choose **Settings**. Choose **Build project tags**.

1. If no tags have been added to the project, choose **Add tag**. Otherwise, choose **Edit**, and then choose **Add tag**.

1. In **Key**, enter a name for the tag. You can add an optional value for the tag in **Value**. 

1. (Optional) To add another tag, choose **Add tag** again.

1. When you have finished adding tags, choose **Submit**.

## Add a tag to a project (AWS CLI)
<a name="how-to-tag-project-add-cli"></a>

To add a tag to a project when you create it, see [Create a build project (AWS CLI)](create-project.md#create-project-cli). In `create-project.json`, add your tags.

In these steps, we assume that you have already installed a recent version of the AWS CLI or updated to the current version. For more information, see [Installing the AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/installing.html).

If successful, this command returns nothing.

# View tags for a project
<a name="how-to-tag-project-list"></a>

Tags can help you identify and organize your AWS resources and manage access to them. For more information about using tags, see the [Tagging best practices](https://d1.awsstatic.com/whitepapers/aws-tagging-best-practices.pdf) whitepaper. For examples of tag-based access policies, see [Using tags to control access to AWS CodeBuild resources](auth-and-access-control-using-tags.md).

## View tags for a project (console)
<a name="how-to-tag-project-list-console"></a>

You can use the CodeBuild console to view the tags associated with a CodeBuild project. 

1. Open the CodeBuild console at [https://console.aws.amazon.com/codebuild/](https://console.aws.amazon.com/codebuild/).

1. In **Build projects**, choose the name of the project where you want to view tags.

1. In the navigation pane, choose **Settings**. Choose **Build project tags**. 

## View tags for a project (AWS CLI)
<a name="how-to-tag-project-list-cli"></a>

To view tags for a build project, run the following command. Use the name of your project for the `--names` parameter.

```
aws codebuild batch-get-projects --names your-project-name
```

If successful, this command returns JSON-formatted information about your build project that includes something like the following:

```
{
    "tags": {
        "Status": "Secret",
        "Team": "JanesProject"
    }
}
```

If the project does not have tags, the `tags` section is empty:

```
"tags": []
```

# Edit tags for a project
<a name="how-to-tag-project-update"></a>

You can change the value for a tag associated with a project. You can also change the name of the key, which is equivalent to removing the current tag and adding a different one with the new name and the same value as the other key. Keep in mind that there are limits on the characters you can use in the key and value fields. For more information, see [Tags](limits.md#tag-limits).

**Important**  
Editing tags for a project can impact access to that project. Before you edit the name (key) or value of a tag for a project, make sure to review any IAM policies that might use the key or value for a tag to control access to resources such as build projects. For examples of tag-based access policies, see [Using tags to control access to AWS CodeBuild resources](auth-and-access-control-using-tags.md).

## Edit a tag for a project (console)
<a name="how-to-tag-project-update-console"></a>

You can use the CodeBuild console to edit the tags associated with a CodeBuild project. 

1. Open the CodeBuild console at [https://console.aws.amazon.com/codebuild/](https://console.aws.amazon.com/codebuild/).

1. In **Build projects**, choose the name of the project where you want to edit tags.

1. In the navigation pane, choose **Settings**. Choose **Build project tags**. 

1. Choose **Edit**.

1. Do one of the following:
   + To change the tag, enter a new name in **Key**. Changing the name of the tag is the equivalent of removing a tag and adding a new tag with the new key name.
   + To change the value of a tag, enter a new value. If you want to change the value to nothing, delete the current value and leave the field blank.

1. When you have finished editing tags, choose **Submit**.

## Edit tags for a project (AWS CLI)
<a name="how-to-tag-project-update-cli"></a>

 To add, change, or delete tags from a build project, see [Change a build project's settings (AWS CLI)](change-project.md#change-project-cli). Update the `tags` section in the JSON-formatted data you use to update the project. 

# Remove a tag from a project
<a name="how-to-tag-project-delete"></a>

You can remove one or more tags associated with a project. Removing a tag does not delete the tag from other AWS resources that are associated with that tag.

**Important**  
Removing tags for a project can impact access to that project. Before you remove a tag from a project, make sure to review any IAM policies that might use the key or value for a tag to control access to resources such as build projects. For examples of tag-based access policies, see [Using tags to control access to AWS CodeBuild resources](auth-and-access-control-using-tags.md).

## Remove a tag from a project (console)
<a name="how-to-tag-project-delete-console"></a>

You can use the CodeBuild console to remove the association between a tag and a CodeBuild project. 

1. Open the CodeBuild console at [https://console.aws.amazon.com/codebuild/](https://console.aws.amazon.com/codebuild/).

1. In **Build projects**, choose the name of the project where you want to remove tags.

1. In the navigation pane, choose **Settings**. Choose **Build project tags**. 

1. Choose **Edit**.

1. Find the tag you want to remove, and then choose **Remove tag**.

1. When you have finished removing tags, choose **Submit**.

## Remove a tag from a project (AWS CLI)
<a name="how-to-tag-project-delete-cli"></a>

 To delete one or more tags from a build project, see [Change a build project's settings (AWS CLI)](change-project.md#change-project-cli). Update the `tags` section in the JSON-formatted data with an updated list of tags that does not contain the ones you want to delete. If you want to delete all tags, update the `tags` section to:

```
"tags: []"
```

**Note**  
If you delete a CodeBuild build project, all tag associations are removed from the deleted build project. You do not have to remove tags before you delete a build project.

# Use runners with AWS CodeBuild
<a name="runners"></a>

AWS CodeBuild supports integration with GitHub Actions runners, self-managed GitLab runners, and the Buildkite runner. 

**Topics**
+ [

# Self-hosted GitHub Actions runners in AWS CodeBuild
](action-runner-overview.md)
+ [

# Self-managed GitLab runners in AWS CodeBuild
](gitlab-runner.md)
+ [

# Self-managed Buildkite runner in AWS CodeBuild
](buildkite-runner.md)

# Self-hosted GitHub Actions runners in AWS CodeBuild
<a name="action-runner-overview"></a>

You can configure your project to set up self-hosted GitHub Actions runners in CodeBuild containers to process your GitHub Actions workflow jobs. This can be done by setting up a webhook using your CodeBuild project, and updating your GitHub Actions workflow YAML to use self-hosted runners hosted on CodeBuild machines.

The high-level steps to configure a CodeBuild project to run GitHub Actions jobs are as follows:

1. If you haven't done so already, create a personal access token or connect with an OAuth app to connect your project to GitHub.

1. Navigate to the CodeBuild console and create a CodeBuild project with a webhook and set up your webhook filters.

1. Update your GitHub Actions workflow YAML in GitHub to configure your build environment.

For a more detailed procedure, see [Tutorial: Configure a CodeBuild-hosted GitHub Actions runner](action-runner.md).

This feature allows your GitHub Actions workflow jobs to get native integration with AWS, which provides security and convenience through features like IAM, AWS Secrets Manager integration, AWS CloudTrail, and Amazon VPC. You can access latest instance types, including ARM-based instances.

**Topics**
+ [

# About the CodeBuild-hosted GitHub Actions runner
](action-runner-questions.md)
+ [

# Tutorial: Configure a CodeBuild-hosted GitHub Actions runner
](action-runner.md)
+ [

# Troubleshoot the webhook
](action-runner-troubleshoot-webhook.md)
+ [

# Label overrides supported with the CodeBuild-hosted GitHub Actions runner
](sample-github-action-runners-update-labels.md)
+ [

# Compute images supported with the CodeBuild-hosted GitHub Actions runner
](sample-github-action-runners-update-yaml.images.md)

# About the CodeBuild-hosted GitHub Actions runner
<a name="action-runner-questions"></a>

The following are some common questions about the CodeBuild-hosted GitHub Actions runner.

## When should I include the image and instance overrides in the label?
<a name="action-runner-image-label"></a>

You can include the image and instance overrides in the label in order to specify different build environment for each of your GitHub Actions workflow jobs. This can be done without the need to create multiple CodeBuild projects or webhooks. For example, this is useful when you need to use a [matrix for your workflow jobs](https://docs.github.com/en/actions/using-jobs/using-a-matrix-for-your-jobs).

```
name: Hello World
on: [push]
jobs:
  Hello-World-Job:
    runs-on:
      - codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
        image:${{ matrix.os }}
        instance-size:${{ matrix.size }}
    strategy:
      matrix:
        include:
          - os: arm-3.0
            size: small
          - os: linux-5.0
            size: large
    steps:
      - run: echo "Hello World!"
```

**Note**  
Quotation marks might be required if `runs-on` has multiple labels containing GitHub Actions context.

## Can I use CloudFormation for this feature?
<a name="action-runner-cfn"></a>

Yes, you can include a filter group in your CloudFormation template that specifies a GitHub Actions workflow job event filter in your project webhook.

```
Triggers:
  Webhook: true
  FilterGroups:
    - - Type: EVENT
        Pattern: WORKFLOW_JOB_QUEUED
```

For more information, see [Filter GitHub webhook events (CloudFormation)](github-webhook-events-cfn.md).

If you need help setting up project credentials in your CloudFormation template, see [AWS::CodeBuild::SourceCredential](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-sourcecredential.html) in the *AWS CloudFormation User Guide* for more information.

## How can I mask secrets when using this feature?
<a name="action-runner-secrets"></a>

By default, secrets that are printed in the log is not masked. If you would like to mask your secrets, you can use the following syntax: `::add-mask::value`. The following is an example of how you can use this syntax in your YAML:

```
name: Secret Job
on: [push]
jobs:
  Secret-Job:
    runs-on: codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
    env:
      SECRET_NAME: "secret-name"
    steps:
      - run: echo "::add-mask::$SECRET_NAME"
```

For more information, see [Masking a value in a log](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#masking-a-value-in-a-log) on GitHub.

## Can I receive GitHub Actions webhook events from multiple repositories within a single project?
<a name="action-runner-webhooks"></a>

CodeBuild supports organization and global level webhooks, which receive events from a specified organization or enterprise. For more information, see [GitHub global and organization webhooks](github-global-organization-webhook.md).

## Which regions support using a CodeBuild-hosted GitHub Actions runner?
<a name="action-runner-hosted-regions"></a>

CodeBuild-hosted GitHub Actions runners are supported in all CodeBuild regions. For more information about AWS Regions where CodeBuild is available, see [AWS Services by Region](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/).

## Which platforms support using a CodeBuild-hosted GitHub Actions runner?
<a name="action-runner-platform"></a>

CodeBuild-hosted GitHub Actions runners are supported on both Amazon EC2 and [AWS Lambda](lambda.md) compute. You can use the following platforms: Amazon Linux 2, Amazon Linux 2023, Ubuntu, and Windows Server Core 2019. For more information, see [EC2 compute images](ec2-compute-images.md) and [Lambda compute images](lambda-compute-images.md).

# Tutorial: Configure a CodeBuild-hosted GitHub Actions runner
<a name="action-runner"></a>

This tutorial shows you how to configure your CodeBuild projects to run GitHub Actions jobs. For more information about using GitHub Actions with CodeBuild see [Tutorial: Configure a CodeBuild-hosted GitHub Actions runner](#action-runner).<a name="sample-github-action-runners-prerequisites"></a>

To complete this tutorial, you must first:
+ Connect with a personal access token, a Secrets Manager secret, OAuth app, or GitHub App. If you'd like to connect with an OAuth app, you must use the CodeBuild console to do so. If you'd like to create a personal access token, you can either use the CodeBuild console or use the [ImportSourceCredentials API](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ImportSourceCredentials.html). For more instructions, see [GitHub and GitHub Enterprise Server access in CodeBuild](access-tokens-github-overview.md).
+ Connect CodeBuild to your GitHub account. To do so, you can do one of the following:
  + You can add GitHub as a source provider in the console. You can connect with either a personal access token, a Secrets Manager secret, OAuth app, or GitHub App. For instructions, see [GitHub and GitHub Enterprise Server access in CodeBuild](access-tokens-github-overview.md).
  + You can import your GitHub credentials via the [ImportSourceCredentials API](https://docs.aws.amazon.com/cli/latest/reference/codebuild/import-source-credentials.html). This can only be done with a personal access token. If you connect using an OAuth app, you must connect using the console instead. For instructions, see [Connect GitHub with an access token (CLI)](access-tokens-github.md#access-tokens-github-cli).
**Note**  
This only needs to be done if you haven't connected to GitHub for your account.

## Step 1: Create a CodeBuild project with a webhook
<a name="sample-github-action-runners-create-project"></a>

In this step, you will create a CodeBuild project with a webhook and review it in the GitHub console. You can also choose GitHub Enterprise as your source provider. To learn more about creating a webhook within GitHub Enterprise, see [GitHub manual webhooks](github-manual-webhook.md).

**To create a CodeBuild project with a webhook**

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a build project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Run a build (console)](run-build-console.md).

1. In **Project type**, choose **Runner project**.

   In **Runner**:

   1. For **Runner provider**, choose **GitHub**.

   1. For **Runner location**, choose **Repository**.

   1. For Repository URL under **Repository**, choose **https://github.com/user-name/repository-name**.
**Note**  
By default, your project will only receive `WORKFLOW_JOB_QUEUED` events for a single repository. If you would like to receive events for all repositories within an organization or enterprise, see [GitHub global and organization webhooks](github-global-organization-webhook.md).

1. 
   +  In **Environment**: 
     + Choose a supported **Environment image** and **Compute**. Note that you have the option to override the image and instance settings by using a label in your GitHub Actions workflow YAML. For more information, see [Step 2: Update your GitHub Actions workflow YAML](#sample-github-action-runners-update-yaml)
   +  In **Buildspec**: 
     + Note that your buildspec will be ignored unless `buildspec-override:true` is added as a label. Instead, CodeBuild will override it to use commands that will setup the self-hosted runner.

1. Continue with the default values and then choose **Create build project**.

1. Open the GitHub console at `https://github.com/user-name/repository-name/settings/hooks` to verify that a webhook has been created and is enabled to deliver **Workflow jobs** events.

## Step 2: Update your GitHub Actions workflow YAML
<a name="sample-github-action-runners-update-yaml"></a>

In this step, you will update your GitHub Actions workflow YAML file in [https://github.com/](https://github.com/) to configure your build environment and use GitHub Actions self-hosted runners in CodeBuild. For more information, see [Using labels with self-hosted runners](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/using-labels-with-self-hosted-runners) and [Label overrides supported with the CodeBuild-hosted GitHub Actions runner](sample-github-action-runners-update-labels.md).

### Update your GitHub Actions workflow YAML
<a name="sample-github-action-runners-update-yaml.setup"></a>

Navigate to [https://github.com/](https://github.com/) and update the [https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/using-labels-with-self-hosted-runners](https://docs.github.com/en/actions/hosting-your-own-runners/managing-self-hosted-runners/using-labels-with-self-hosted-runners) setting in your GitHub Actions workflow YAML to configure your build environment. To do so, you can do one of the following:
+ You can specify the project name and run ID, in which case the build will use your existing project configuration for the compute, image, image version, and instance size. The project name is needed to link the AWS-related settings of your GitHub Actions job to a specific CodeBuild project. By including the project name in the YAML, CodeBuild is allowed to invoke jobs with the correct project settings. By providing the run ID, CodeBuild will map your build to specific workflow runs and stop the build when the workflow run is cancelled. For more information, see [`github` context](https://docs.github.com/en/actions/learn-github-actions/contexts#github-context).

  ```
  runs-on: codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}
  ```
**Note**  
Make sure that your *<project-name>* matches the name of the project that you created in the previous step. If it doesn't match, CodeBuild will not process the webhook and the GitHub Actions workflow might hang.

  The following is an example of a GitHub Actions workflow YAML:

  ```
  name: Hello World
  on: [push]
  jobs:
    Hello-World-Job:
      runs-on:
        - codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
      steps:
        - run: echo "Hello World!"
  ```
+ You can also override your image and compute type in the label. See [Compute images supported with the CodeBuild-hosted GitHub Actions runner](sample-github-action-runners-update-yaml.images.md) for a list of curated images. For using custom images, see [Label overrides supported with the CodeBuild-hosted GitHub Actions runner](sample-github-action-runners-update-labels.md). The compute type and image in the label will override the environment settings on your project. To override your environment settings for an CodeBuild EC2 or Lambda compute build, use the following syntax:

  ```
  runs-on:
    - codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}
      image:<environment-type>-<image-identifier>
      instance-size:<instance-size>
  ```

  The following is an example of a GitHub Actions workflow YAML:

  ```
  name: Hello World
  on: [push]
  jobs:
    Hello-World-Job:
      runs-on:
        - codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
          image:arm-3.0
          instance-size:small
      steps:
        - run: echo "Hello World!"
  ```
+ You can override the fleet used for your build in the label. This will override the fleet settings configured on your project to use the specified fleet. For more information, see [Run builds on reserved capacity fleets](fleets.md). To override your fleet settings for an Amazon EC2 compute build, use the following syntax:

  ```
  runs-on:
    - codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}
      fleet:<fleet-name>
  ```

  To override both the fleet and the image used for the build, use the following syntax:

  ```
  runs-on:
    - codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}
      fleet:<fleet-name>
      image:<environment-type>-<image-identifier>
  ```

  The following is an example of a GitHub Actions workflow YAML:

  ```
  name: Hello World
  on: [push]
  jobs:
    Hello-World-Job:
      runs-on:
        - codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
          fleet:myFleet
          image:arm-3.0
      steps:
        - run: echo "Hello World!"
  ```
+ In order to run your GitHub Actions jobs on a custom image, you can configure a custom image in your CodeBuild project and avoid providing an image override label. CodeBuild will use the image configured in the project if no image override label is provided.
+ Optionally, you can provide labels outside of those that CodeBuild supports. These labels will be ignored for the purpose of overriding attributes of the build, but will not fail the webhook request. For example, adding `testLabel` as a label will not prevent the build from running.

**Note**  
If a dependency provided by GitHub-hosted runners is unavailable in the CodeBuild environment, you can install the dependency using GitHub Actions in your workflow run. For example, you can use the [https://github.com/actions/setup-python](https://github.com/actions/setup-python) action to install Python for your build environment.

### Run buildspec commands the INSTALL, PRE\$1BUILD, and POST\$1BUILD phases
<a name="sample-github-action-runners-update-yaml.buildspec"></a>

By default, CodeBuild ignores any buildspec commands when running a self-hosted GitHub Actions build. To run buildspec commands during the build, `buildspec-override:true` can be added as a suffix to the label:

```
runs-on:
  - codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}
    buildspec-override:true
```

By using this command, CodeBuild will create a folder called `actions-runner` in the container's primary source folder. When the GitHub Actions runner starts during the `BUILD` phase, the runner will run in the `actions-runner` directory.

There are several limitations when using a buildspec override in a self-hosted GitHub Actions build:
+ CodeBuild will not run buildspec commands during the `BUILD` phase, as the self-hosted runner runs in the `BUILD` phase.
+ CodeBuild will not download any primary or secondary sources during the `DOWNLOAD_SOURCE` phase. If you have a buildspec file configured, only that file will be downloaded from the project's primary source.
+ If a build command fails in the `PRE_BUILD` or `INSTALL` phase, CodeBuild will not start the self-hosted runner and the GitHub Actions workflow job will need to be cancelled manually.
+ CodeBuild fetches the runner token during the `DOWNLOAD_SOURCE` phase, which has an expiration time of one hour. If your `PRE_BUILD` or `INSTALL` phases exceed an hour, the runner token may expire before the GitHub self-hosted runner starts.

## Step 3: Review your results
<a name="sample-github-action-runners-verify"></a>

Whenever a GitHub Actions workflow run occurs, CodeBuild would receive the workflow job events through the webhook. For each job in the workflow, CodeBuild starts a build to run an ephemeral GitHub Actions runner. The runner is responsible for executing a single workflow job. Once the job is completed, the runner and the associated build process will be immediately terminated.

To view your workflow job logs, navigate to your repository in GitHub, choose **Actions**, choose your desired workflow, and then choose the specific **Job** that you'd like to review the logs for.

You can review the requested labels in the log while the job is waiting to be picked up by a self-hosted runner in CodeBuild.

![\[Loading the log of the job.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/hello-world-loading.png)


Once the job is completed, you will be able to view the log of the job.

![\[The log of the job.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/hello-world-log.png)


## GitHub Actions runner configuration options
<a name="sample-github-action-runners-config"></a>

You can specify the following environment variables in your project configuration to modify the setup configuration of your self-hosted runners.

`CODEBUILD_CONFIG_GITHUB_ACTIONS_ORG_REGISTRATION_NAME`  
CodeBuild will register self-hosted runners to the organization name specified as the value of this environment variable. For more information about registering runners at the organization level and the necessary permissions, see [ Create configuration for a just-in-time runner for an organization](https://docs.github.com/en/rest/actions/self-hosted-runners?apiVersion=2022-11-28#create-configuration-for-a-just-in-time-runner-for-an-organization).

`CODEBUILD_CONFIG_GITHUB_ACTIONS_ENTERPRISE_REGISTRATION_NAME`  
CodeBuild will register self-hosted runners to the enterprise name specified as the value of this environment variable. For more information about registering runners at the enterprise level and the necessary permissions, see [ Create configuration for a just-in-time runner for an Enterprise](https://docs.github.com/en/enterprise-server/rest/actions/self-hosted-runners?apiVersion=2022-11-28#create-configuration-for-a-just-in-time-runner-for-an-enterprise).  
Enterprise runners are not available to organization repositories by default. For self-hosted runners to pick up workflow jobs, you might need to configure your runner group access settings. For more information, see [ Making enterprise runners available to repositories](https://docs.github.com/en/enterprise-server/actions/hosting-your-own-runners/managing-self-hosted-runners/adding-self-hosted-runners#making-enterprise-runners-available-to-repositories).

`CODEBUILD_CONFIG_GITHUB_ACTIONS_RUNNER_GROUP_ID`  
CodeBuild will register self-hosted runners to the integer runner group ID stored as the value of this environment variable. By default, this value is 1. For more information about self-hosted runner groups, see [ Managing access to self-hosted runners using groups](https://docs.github.com/en/rest/actions/self-hosted-runners?apiVersion=2022-11-28#create-configuration-for-a-just-in-time-runner-for-an-organization).

`CODEBUILD_CONFIG_GITHUB_ACTIONS_ORG_REGISTRATION_NAME`  
To configure organization level runner registration using your GitHub Actions workflow YAML file, you can use the following syntax:  

```
name: Hello World
on: [push]
jobs:
  Hello-World-Job:
    runs-on:
      - codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
        organization-registration-name:myOrganization
    steps:
      - run: echo "Hello World!"
```

`CODEBUILD_CONFIG_GITHUB_ACTIONS_ENTERPRISE_REGISTRATION_NAME`  
To configure enterprise level runner registration using your GitHub Actions workflow YAML file, you can use the following syntax:  

```
name: Hello World
on: [push]
jobs:
  Hello-World-Job:
    runs-on:
      - codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
        enterprise-registration-name:myEnterprise
    steps:
      - run: echo "Hello World!"
```

`CODEBUILD_CONFIG_GITHUB_ACTIONS_RUNNER_GROUP_ID`  
To configure registering runners to a specific runner group ID using your GitHub Actions workflow YAML file, you can use the following syntax:  

```
name: Hello World
on: [push]
jobs:
  Hello-World-Job:
    runs-on:
      - codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
        registration-group-id:3
    steps:
      - run: echo "Hello World!"
```

## Filter GitHub Actions webhook events (CloudFormation)
<a name="sample-github-action-runners-webhooks-cfn"></a>

The following YAML-formatted portion of an CloudFormation template creates a filter group that triggers a build when it evaluates to true. The following filter group specifies a GitHub Actions workflow job request with a workflow name matching the regular expression `\[CI-CodeBuild\]`.

```
CodeBuildProject:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: MyProject
    ServiceRole: service-role
    Artifacts:
      Type: NO_ARTIFACTS
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/standard:5.0
    Source:
      Type: GITHUB
      Location: CODEBUILD_DEFAULT_WEBHOOK_SOURCE_LOCATION
    Triggers:
      Webhook: true
      ScopeConfiguration:
        Name: organization-name
        Scope: GITHUB_ORGANIZATION
      FilterGroups:
        - - Type: EVENT
            Pattern: WORKFLOW_JOB_QUEUED
          - Type: WORKFLOW_NAME
            Pattern: \[CI-CodeBuild\]
```

## Filter GitHub Actions webhook events (AWS CDK)
<a name="sample-github-action-runners-webhooks-cdk"></a>

The following AWS CDK template creates a filter group that triggers a build when it evaluates to true. The following filter group specifies a GitHub Actions workflow job request.

```
import { aws_codebuild as codebuild } from 'aws-cdk-lib';
import {EventAction, FilterGroup} from "aws-cdk-lib/aws-codebuild";

const source = codebuild.Source.gitHub({
      owner: 'owner',
      repo: 'repo',
      webhook: true,
      webhookFilters: [FilterGroup.inEventOf(EventAction.WORKFLOW_JOB_QUEUED)],
    })
```

## Filter GitHub Actions webhook events (Terraform)
<a name="sample-github-action-runners-webhooks-terraform"></a>

The following Terraform template creates a filter group that triggers a build when it evaluates to true. The following filter group specifies a GitHub Actions workflow job request.

```
resource "aws_codebuild_webhook" "example" {
  project_name = aws_codebuild_project.example.name
  build_type   = "BUILD"
  filter_group {
    filter {
      type    = "EVENT"
      pattern = "WORKFLOW_JOB_QUEUED"
    }
  }
}
```

## Filter GitHub Actions webhook events (AWS CLI)
<a name="sample-github-action-runners-webhooks-cli"></a>

The following AWS CLI commands create a self-hosted GitHub Actions runner project with a GitHub Actions workflow job request filter group that triggers a build when it evaluates to true.

```
aws codebuild create-project \
--name <project name> \
--source "{\"type\":\"GITHUB\",\"location\":\"<repository location>\",\"buildspec\":\"\"}" \
--artifacts {"\"type\":\"NO_ARTIFACTS\""} \
--environment "{\"type\": \"LINUX_CONTAINER\",\"image\": \"aws/codebuild/amazonlinux-x86_64-standard:5.0\",\"computeType\": \"BUILD_GENERAL1_MEDIUM\"}" \
--service-role "<service role ARN>"
```

```
aws codebuild create-webhook \
--project-name <project name> \
--filter-groups "[[{\"type\":\"EVENT\",\"pattern\":\"WORKFLOW_JOB_QUEUED\"}]]"
```

# Troubleshoot the webhook
<a name="action-runner-troubleshoot-webhook"></a>

**Issue: **The webhook you set up in [Tutorial: Configure a CodeBuild-hosted GitHub Actions runner](action-runner.md) isn't working or your workflow job is hanging on GitHub.

**Possible causes: **
+ Your webhook **Workflow jobs** event might be failing to trigger a build. Review the **Response** logs to view the response or error message.
+ Your jobs are being assigned to the incorrect runner agent due to their label configuration. This issue can occur when one of your jobs within a single workflow run has fewer labels than another job. For example, if you have two jobs with the following labels in the same workflow run:
  + **Job 1**: `codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}`
  + **Job 2**: `codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}`, `instance-size:medium`

  When routing a self-hosted GitHub Actions job, GitHub will route the job to any runner with all the job's specified labels. This behavior means that **Job 1** can be picked up by either the runner created for **Job 1** or **Job 2**, but **Job 2** can only be picked up by the runner created for **Job 2** since it has an additional label. If **Job 1** is picked up by the runner created for **Job 2**, then **Job 2** will become stuck since the **Job 1** runner doesn't have the `instance-size:medium` label.

**Recommended solutions: **

When creating multiple jobs within the same workflow run, use the same number of label overrides for each job or assign each job a custom label, such as `job1` or `job2`.

If the error persists, use the following instructions to debug the issue.

1. Open the GitHub console at `https://github.com/user-name/repository-name/settings/hooks` to view your repository's webhook settings. On this page, you'll see a webhook that was created for your repository.

1. Choose **Edit** and conﬁrm that the webhook is enabled to deliver **Workﬂow jobs** events.  
![\[Workflow job events are enabled in your webhook.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-actions-workflow-jobs.png)

1.  Navigate to the **Recent Deliveries** tab, find the corresponding `workflow_job.queued` event, and expand the event. 

1.  Review the **labels** field in the **Payload** and make sure it’s as expected. 

1.  Finally, review the **Response** tab, as this contains the response or error message returned from CodeBuild.   
![\[The response or error message returned from CodeBuild.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-actions-workflow-jobs-response.png)

1.  Alternatively, you can debug webhook failures using GitHub's APIs. You can view recent deliveries for a webhook using the [ List deliveries for a repository webhook](https://docs.github.com/en/rest/repos/webhooks?apiVersion=2022-11-28#list-deliveries-for-a-repository-webhook) API: 

   ```
   gh api \
     -H "Accept: application/vnd.github+json" \
     -H "X-GitHub-Api-Version: 2022-11-28" \
     /repos/owner/repo/hooks/hook-id/deliveries
   ```

    After finding the webhook delivery you're looking to debug and noting the delivery ID, you can use the [ Get a delivery for a repository webhook](https://docs.github.com/en/rest/repos/webhooks?apiVersion=2022-11-28#get-a-delivery-for-a-repository-webhook) API. CodeBuild's response to the webhook's delivery payload can be found in the `response` section: 

   ```
   gh api \
     -H "Accept: application/vnd.github+json" \
     -H "X-GitHub-Api-Version: 2022-11-28" \
     /repos/owner/repo/hooks/hook-id/deliveries/delivery-id
   ```

**Issue:** Your GitHub Actions with [deployment protection](https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-deployments/reviewing-deployments) rules enabled triggers builds within CodeBuild before the deployment has been approved.

**Possible causes:** CodeBuild fetches the deployment and environment associated with the GitHub Actions job if they exist to verify if the is approved. If CodeBuild fails to fetch either the deployment or environment, the CodeBuild build may be triggered prematurely.

**Recommended solutions:** Verify that the credentials associated with your CodeBuild projects have read permissions for deployments and actions within GitHub.

# Label overrides supported with the CodeBuild-hosted GitHub Actions runner
<a name="sample-github-action-runners-update-labels"></a>

In your GitHub Actions workflow YAML, you can provide a variety of label overrides that modify your self-hosted runner build. Any builds not recognized by CodeBuild will be ignored but will not fail your webhook request. For example, the following workflow YAML includes overrides for image, instance size, fleet, and the buildspec:

```
name: Hello World
on: [push]
jobs:
  Hello-World-Job:
    runs-on:
      - codebuild-myProject-${{ github.run_id }}-${{ github.run_attempt }}
        image:${{ matrix.os }}
        instance-size:${{ matrix.size }}
        fleet:myFleet
        buildspec-override:true
    strategy:
      matrix:
        include:
          - os: arm-3.0
            size: small
          - os: linux-5.0
            size: large
    steps:
      - run: echo "Hello World!"
```

**Note**  
If your workflow job is hanging on GitHub, see [Troubleshoot the webhook](action-runner-troubleshoot-webhook.md) and [ Using custom labels to route jobs](https://docs.github.com/en/enterprise-server@3.12/actions/hosting-your-own-runners/managing-self-hosted-runners/using-self-hosted-runners-in-a-workflow?learn=hosting_your_own_runners&learnProduct=actions#using-custom-labels-to-route-jobs).

`codebuild-<project-name>-${{github.run_id}}-${{github.run_attempt}}` (required)
+ Example: `codebuild-fake-project-${{ github.run_id }}-${{ github.run_attempt }}`
+ Required for all GitHub Actions workflow YAMLs. *<project name>* should be equal to the name of the project for which the self-hosted runner webhook is configured.

`image:<environment-type>-<image-identifier>`
+ Example: `image:arm-3.0`
+ Overrides the image and environment type used when starting the self-hosted runner build with a curated image. To learn about supported values, see [Compute images supported with the CodeBuild-hosted GitHub Actions runner](sample-github-action-runners-update-yaml.images.md).
  + To override the image and environment type used with a custom image, use `image:custom-<environment-type>-<custom-image-identifier>`
  + Example: `image:custom-arm-public.ecr.aws/codebuild/amazonlinux-aarch64-standard:3.0`
**Note**  
If the custom image resides in a private registry, see [Configure a private registry credential for self-hosted runners](private-registry-sample-configure-runners.md).

`instance-size:<instance-size>`
+ Example: `instance-size:medium`
+ Overrides the instance type used when starting the self-hosted runner build. To learn about supported values, see [Compute images supported with the CodeBuild-hosted GitHub Actions runner](sample-github-action-runners-update-yaml.images.md).

`fleet:<fleet-name>`
+ Example: `fleet:myFleet`
+ Overrides the fleet settings configured on your project to use the specified fleet. For more information, see [Run builds on reserved capacity fleets](fleets.md).

`buildspec-override:<boolean>`
+ Example: `buildspec-override:true`
+ Allows the build to run buildspec commands in the `INSTALL`, `PRE_BUILD`, and `POST_BUILD` phases if set to `true`.

## Single label override (legacy)
<a name="sample-github-action-runners-update-single-labels"></a>

CodeBuild allows you to provide multiple overrides in a single label using the following:
+ To override your environment settings for an Amazon EC2/Lambda compute build, use the following syntax:

  ```
  runs-on: codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}-<environment-type>-<image-identifier>-<instance-size>
  ```
+ To override your fleet settings for Amazon EC2 compute build, use the following syntax:

  ```
  runs-on: codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}-fleet-<fleet-name>
  ```
+ To override both the fleet and the image used for the build, use the following syntax:

  ```
  runs-on: codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}-image-<image-version>-fleet-<fleet-name>
  ```
+ To run buildspec commands during the build, `-with-buildspec` can be added as a suffix to the label:

  ```
  runs-on: codebuild-<project-name>-${{ github.run_id }}-${{ github.run_attempt }}-<image>-<image-version>-<instance-size>-with-buildspec
  ```
+ Optionally, you can provide an instance size override without overriding the image. For Amazon EC2 builds, you can exclude both environment type and image identifier. For Lambda builds, you can exclude the image identifier.

# Compute images supported with the CodeBuild-hosted GitHub Actions runner
<a name="sample-github-action-runners-update-yaml.images"></a>

In the label you configured in [Tutorial: Configure a CodeBuild-hosted GitHub Actions runner](action-runner.md), you can override your Amazon EC2 environment settings by using the values in the first three columns. CodeBuild provides the following Amazon EC2 compute images. For more information about 

<a name="build-env-ref.supported-images"></a>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/sample-github-action-runners-update-yaml.images.html)

In addition, you can override your Lambda environment settings by using the following values. For more information about CodeBuild Lambda compute, see [Run builds on AWS Lambda compute](lambda.md). CodeBuild supports the following Lambda compute images:

<a name="lambda.supported-images"></a>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/sample-github-action-runners-update-yaml.images.html)

For more information, see [Build environment compute modes and types](build-env-ref-compute-types.md) and [Docker images provided by CodeBuild](build-env-ref-available.md).

# Self-managed GitLab runners in AWS CodeBuild
<a name="gitlab-runner"></a>

GitLab provides two execution modes to run GitLab jobs in your CI/CD pipeline. One mode is GitLab-hosted runners, which are managed by GitLab and fully integrated with GitLab. The other mode is self-managed runners, which allows you to bring your own customized environment to run jobs in the GitLab CI/CD pipeline.

The high-level steps to configure a CodeBuild project to run GitLab CI/CD pipeline jobs are as follows:

1. If you haven't done so already, connect with an OAuth app to connect your project to GitLab.

1. Navigate to the CodeBuild console and create a CodeBuild project with a webhook and set up your webhook filters.

1. Update your GitLab CI/CD pipeline YAML in GitLab to configure your build environment.

For a more detailed procedure, see [Tutorial: Configure a CodeBuild-hosted GitLab runner](sample-gitlab-runners.md).

This feature allows your GitLab CI/CD pipeline jobs to get native integration with AWS, which provides security and convenience through features like IAM, AWS CloudTrail, and Amazon VPC. You can access latest instance types, including ARM-based instances.

**Topics**
+ [

# About the CodeBuild-hosted GitLab runner
](gitlab-runner-questions.md)
+ [

# Tutorial: Configure a CodeBuild-hosted GitLab runner
](sample-gitlab-runners.md)
+ [

# Label overrides supported with the CodeBuild-hosted GitLab runner
](gitlab-runners-update-labels.md)
+ [

# Compute images supported with the CodeBuild-hosted GitLab runner
](sample-gitlab-runners-gitlab-ci.images.md)

# About the CodeBuild-hosted GitLab runner
<a name="gitlab-runner-questions"></a>

The following are some common questions about the CodeBuild-hosted GitLab runner.

## What source types are supported for CodeBuild-hosted GitLab runners?
<a name="gitlab-runner-source"></a>

CodeBuild-hosted GitLab runners are supported for the `GITLAB` and `GITLAB_SELF_MANAGED` source type.

## When should I include the image and instance overrides in the label?
<a name="gitlab-runner-image-label"></a>

You can include the image and instance overrides in the label in order to specify different build environment for each of your GitLab CI/CD pipeline jobs. This can be done without the need to create multiple CodeBuild projects or webhooks.

## Can I use CloudFormation for this feature?
<a name="gitlab-runner-cfn"></a>

Yes, you can include a filter group in your CloudFormation template that specifies a GitLab workflow job event filter in your project webhook.

```
Triggers:
  Webhook: true
  FilterGroups:
    - - Type: EVENT
        Pattern: WORKFLOW_JOB_QUEUED
```

For more information, see [Filter GitLab webhook events (CloudFormation)](gitlab-webhook-events-cfn.md).

If you need help setting up project credentials in your CloudFormation template, see [AWS::CodeBuild::SourceCredential](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codebuild-sourcecredential.html) in the *AWS CloudFormation User Guide* for more information.

## How can I mask secrets when using this feature?
<a name="gitlab-runner-secrets"></a>

By default, secrets that are printed in the log is not masked. If you would like to mask your secrets, you can do so by updating your CI/CD environment variable settings:

**To mask secrets in GitLab**

1. In your **GitLab Settings**, choose **CI/CD**.

1. In **Variables**, choose **Edit** for the secret you'd like to mask.

1. In **Visibility**, select **Mask variable**, and then choose **Update variable** to save your changes.

## Can I receive GitLab webhook events from multiple projects within a single group?
<a name="gitlab-runner-webhooks"></a>

CodeBuild supports group webhooks, which receive events from a specified GitLab group. For more information, see [GitLab group webhooks](gitlab-group-webhook.md).

## Can I execute a job in docker executor for the self-managed runner? For example, I want to run a pipeline job on a specific image to maintain the same build environment in a separate and isolated container.
<a name="gitlab-runner-custom-image"></a>

You can run the GitLab self-managed runner in CodeBuild with a specific image by [creating the project with a custom image](create-project.md#environment-image.console) or [overriding the image](sample-gitlab-runners.md#sample-gitlab-runners-gitlab-ci) in your `.gitlab-ci.yml` file.

## What executor does the self-managed runner in CodeBuild run with?
<a name="gitlab-runner-shell-executor"></a>

The self-managed runner in CodeBuild runs with the shell executor, where the build runs locally along with the GitLab runner that is running inside the docker container.

## Can I provide buildspec commands along with the self-managed runner?
<a name="gitlab-runner-buildspec-commands"></a>

Yes, it is possible to add buildspec commands along with self-managed runner. You can provide the buildspec.yml file in your GitLab repository and use the `buildspec-override:true` tag in the **Tags** section of the job. For more information, see [Buildspec file name and storage location](build-spec-ref.md#build-spec-ref-name-storage).

## Which regions support using a CodeBuild-hosted GitLab runner?
<a name="gitlab-runner-hosted-regions"></a>

CodeBuild-hosted GitLab runners are supported in all CodeBuild regions. For more information about AWS Regions where CodeBuild is available, see [AWS Services by Region](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/).

## Which platforms support using a CodeBuild-hosted GitLab runner?
<a name="gitlab-runner-platform"></a>

CodeBuild-hosted GitLab runners are supported on both Amazon EC2 and [AWS Lambda](lambda.md) compute. You can use the following platforms: Amazon Linux 2, Amazon Linux 2023, Ubuntu, and Windows Server Core 2019. For more information, see [EC2 compute images](ec2-compute-images.md) and [Lambda compute images](lambda-compute-images.md).

# Tutorial: Configure a CodeBuild-hosted GitLab runner
<a name="sample-gitlab-runners"></a>

This tutorial shows you how to configure your CodeBuild projects to run GitLab CI/CD pipeline jobs. For more information about using GitLab or GitLab Self Managed with CodeBuild, see [Self-managed GitLab runners in AWS CodeBuild](gitlab-runner.md).<a name="sample-gitlab-runners-prerequisites"></a>

To complete this tutorial, you must first:
+ Connect with a OAuth app by using CodeConnections. Note that when connecting with an OAuth app, you must use the CodeBuild console to do so. For more instructions, see [GitLab access in CodeBuild](access-tokens-gitlab-overview.md).
+ Connect CodeBuild to your GitLab account. To do so, you can add GitLab as a source provider in the console. For instructions, see [GitLab access in CodeBuild](access-tokens-gitlab-overview.md).
**Note**  
This only needs to be done if you haven't connected to GitLab for your account.  
With this feature, CodeBuild needs additional permissions. such as `create_runner` and `manage_runner` from the GitLab OAuth app. If there are existing CodeConnections for a particular GitLab account, then it doesn't automatically request for permission updates. To do so, you can go to the CodeConnections console and create a dummy connection to the same GitLab account to trigger the reauthorization to get the additional prmissions. With this, all the existing connections can use the runner feature. Once complete, you can delete the dummy connection.

## Step 1: Create a CodeBuild project with a webhook
<a name="sample-gitlab-runners-create-project"></a>

In this step, you will create a CodeBuild project with a webhook and review it in the GitLab console.

**To create a CodeBuild project with a webhook**

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a build project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Run a build (console)](run-build-console.md).

   In **Project type**, choose **Runner project**.
   +  In **Runner**: 
     + For **Runner provider**, choose **GitLab**.
     +  For **Credential**, choose one of the following:
       + Choose ** Default source credential**. Default connection applies a default GitLab connection across all projects.
       + Choose ** Custom source credential**. Custom connection applies a custom GitLab connection that overrides your account's default settings.
**Note**  
If you have not already created a connection to your provider, you'll have to create a new GitLab connection. For instructions, see [Connect CodeBuild to GitLab](access-tokens-gitlab-overview.md#connections-gitlab).
     + For **Runner location**, choose **Repository**.
     +  For **Repository**, choose the name of your project in GitLab by specifying the project path with the namespace.
   +  In **Environment**: 
     + Choose a supported **Environment image** and **Compute**. Note that you have the option to override the image and instance settings by using a label in your GitLab CI/CD pipeline YAML. For more information, see [Step 2: Create a .gitlab-ci.yml file in your repository](#sample-gitlab-runners-gitlab-ci).
   +  In **Buildspec**: 
     + Note that your buildspec will be ignored unless `buildspec-override:true` is added as a label. Instead, CodeBuild will override it to use commands that will setup the self-managed runner.

1. Continue with the default values and then choose **Create build project**.

1. Open the GitLab console at `https://gitlab.com/user-name/repository-name/-/hooks` to verify that a webhook has been created and is enabled to deliver **Workflow jobs** events.

## Step 2: Create a .gitlab-ci.yml file in your repository
<a name="sample-gitlab-runners-gitlab-ci"></a>

In this step, you will create a `.gitlab-ci.yml` file in [https://gitlab.com/](https://gitlab.com/) to configure your build environment and use GitLab self-managed runners in CodeBuild. For more information, see [Use self-managed runners](https://docs.gitlab.com/runner/#use-self-managed-runners).

### Update your GitLab CI/CD pipeline YAML
<a name="sample-gitlab-runners-update-yaml.setup"></a>

Navigate to `https://gitlab.com/user-name/project-name/-/tree/branch-name` and create a `.gitlab-ci.yml` file in your repository. You can configure your build environment by doing one of the following:
+ You can specify the CodeBuild project name, in which case the build will use your existing project configuration for the compute, image, image version, and instance size. The project name is needed to link the AWS-related settings of your GitLab job to a specific CodeBuild project. By including the project name in the YAML, CodeBuild is allowed to invoke jobs with the correct project settings.

  ```
  tags:
      - codebuild-<codebuild-project-name>-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
  ```

  `$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME` is required to map the build to specific pipeline job runs and stop the build when the pipeline run is cancelled.
**Note**  
Make sure that your *<project-name>* matches the name of the project that you created in CodeBuild. If it doesn't match, CodeBuild will not process the webhook and the GitLab CI/CD pipeline might hang.

  The following is an example of a GitLab CI/CD pipeline YAML:

  ```
  workflow:
    name: HelloWorld
  stages:          # List of stages for jobs, and their order of execution
    - build
  
  build-job:       # This job runs in the build stage, which runs first.
    stage: build
    script:
      - echo "Hello World!"
    tags:
      - codebuild-myProject-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
  ```
+ You can also override your image and compute type in the tag. See [Compute images supported with the CodeBuild-hosted GitLab runner](sample-gitlab-runners-gitlab-ci.images.md) for a list of curated images. For using custom images, see [Label overrides supported with the CodeBuild-hosted GitLab runner](gitlab-runners-update-labels.md). The compute type and image in the tag will override the environment settings on your project. To override your environment settings for an Amazon EC2 compute build, use the following syntax:

  ```
  tags:
      - codebuild-<codebuild-project-name>-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
      - image:<environment-type>-<image-identifier>
      - instance-size:<instance-size>
  ```

  The following is an example of a GitLab CI/CD pipeline YAML:

  ```
  stages:
    - build
  
  build-job:
    stage: build
    script:
      - echo "Hello World!"
    tags:
      - codebuild-myProject-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
      - image:arm-3.0
      - instance-size:small
  ```
+ You can override the fleet used for your build in the tag. This will override the fleet settings configured on your project to use the specified fleet. For more information, see [Run builds on reserved capacity fleets](fleets.md). To override your fleet settings for an Amazon EC2 compute build, use the following syntax:

  ```
  tags:
      - codebuild-<codebuild-project-name>-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
      - fleet:<fleet-name>
  ```

  To override both the fleet and the image used for the build, use the following syntax:

  ```
  tags:
      - codebuild-<codebuild-project-name>-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
      - fleet:<fleet-name>                    
      - image:<environment-type>-<image-identifier>
  ```

  The following is an example of a GitLab CI/CD pipeline YAML:

  ```
  stages:
    - build
  
  build-job:
    stage: build
    script:
      - echo "Hello World!"
    tags:
      - codebuild-myProject-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
      - fleet:myFleet
      - image:arm-3.0
  ```
+ In order to run your GitLab CI/CD pipeline jobs on a custom image, you can configure a custom image in your CodeBuild project and avoid providing an image override label. CodeBuild will use the image configured in the project if no image override label is provided.

After you commit your changes to `.gitlab-ci.yml`, a GitLab pipeline will be triggered and the `build-job` will send a webhook notification that will start your build in CodeBuild.

### Run buildspec commands the INSTALL, PRE\$1BUILD, and POST\$1BUILD phases
<a name="sample-gitlab-runners-update-yaml.buildspec"></a>

By default, CodeBuild ignores any buildspec commands when running a self-managed GitLab build. To run buildspec commands during the build, `buildspec-override:true` can be added as a suffix to `tags`:

```
tags:
    - codebuild-<codebuild-project-name>-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
    - buildspec-override:true
```

By using this command, CodeBuild will create a folder called `gitlab-runner` in the container's primary source folder. When the GitLab runner starts during the `BUILD` phase, the runner will run in the `gitlab-runner` directory.

There are several limitations when using a buildspec override in a self-managed GitLab build:
+ CodeBuild will not run buildspec commands during the `BUILD` phase, as the self-managed runner runs in the `BUILD` phase.
+ CodeBuild will not download any primary or secondary sources during the `DOWNLOAD_SOURCE` phase. If you have a buildspec file configured, only that file will be downloaded from the project's primary source.
+ If a build command fails in the `PRE_BUILD` or `INSTALL` phase, CodeBuild will not start the self-managed runner and the GitLab CI/CD pipeline job will need to be cancelled manually.
+ CodeBuild fetches the runner token during the `DOWNLOAD_SOURCE` phase, which has an expiration time of one hour. If your `PRE_BUILD` or `INSTALL` phases exceed an hour, the runner token may expire before the GitLab self-managed runner starts.

## Step 3: Review your results
<a name="sample-gitlab-runners-verify"></a>

Whenever a GitLab CI/CD pipeline run occurs, CodeBuild would receive the CI/CD pipeline job events through the webhook. For each job in the CI/CD pipeline, CodeBuild starts a build to run an ephemeral GitLab runner. The runner is responsible for executing a single CI/CD pipeline job. Once the job is completed, the runner and the associated build process will be immediately terminated.

To view your CI/CD pipeline job logs, navigate to your repository in GitLab, choose **Build**, **Jobs**, and then choose the specific **Job** that you'd like to review the logs for.

You can review the requested labels in the log while the job is waiting to be picked up by a self-managed runner in CodeBuild.

## Filter GitLab webhook events (CloudFormation)
<a name="sample-gitlab-runners-webhooks-cfn"></a>

The following YAML-formatted portion of an CloudFormation template creates a filter group that triggers a build when it evaluates to true. The following filter group specifies a GitLab CI/CD pipeline job request with a CI/CD pipeline name matching the regular expression `\[CI-CodeBuild\]`.

```
CodeBuildProject:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: MyProject
    ServiceRole: service-role
    Artifacts:
      Type: NO_ARTIFACTS
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/standard:5.0
    Source:
      Type: GITLAB
      Location: CODEBUILD_DEFAULT_WEBHOOK_SOURCE_LOCATION
    Triggers:
      Webhook: true
      ScopeConfiguration:
        Name: group-name
        Scope: GITLAB_GROUP
      FilterGroups:
        - - Type: EVENT
            Pattern: WORKFLOW_JOB_QUEUED
          - Type: WORKFLOW_NAME
            Pattern: \[CI-CodeBuild\]
```

# Label overrides supported with the CodeBuild-hosted GitLab runner
<a name="gitlab-runners-update-labels"></a>

In your GitLab CI/CD pipeline YAML, you can provide a variety of label overrides that modify your self-managed runner build. Any builds not recognized by CodeBuild will be ignored but will not fail your webhook request. For example, the following YAML includes overrides for image, instance size, fleet, and the buildspec:

```
workflow:
  name: HelloWorld
stages:
  - build

build-job:
  stage: build
  script:
    - echo "Hello World!"
  tags:
    - codebuild-myProject-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME
    - image:arm-3.0
    - instance-size:small
    - fleet:myFleet
    - buildspec-override:true
```

`codebuild-<project-name>-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME` (required)
+ Example: `codebuild-myProject-$CI_PROJECT_ID-$CI_PIPELINE_IID-$CI_JOB_NAME`
+ Required for all GitLab CI/CD pipeline YAMLs. *<project name>* should be equal to the name of the project for which the self-managed runner webhook is configured.

`image:<environment-type>-<image-identifier>`
+ Example: `image:arm-3.0`
+ Overrides the image and environment type used when starting the self-managed runner build. To learn about supported values, see [Compute images supported with the CodeBuild-hosted GitLab runner](sample-gitlab-runners-gitlab-ci.images.md).
  + To override the image and environment type used with a custom image, use `image:custom-<environment-type>-<custom-image-identifier>`
  + Example: `image:custom-arm-public.ecr.aws/codebuild/amazonlinux-aarch64-standard:3.0`
**Note**  
If the custom image resides in a private registry, see [Configure a private registry credential for self-hosted runners](private-registry-sample-configure-runners.md).

`instance-size:<instance-size>`
+ Example: `instance-size:small`
+ Overrides the instance type used when starting the self-managed runner build. To learn about supported values, see [Compute images supported with the CodeBuild-hosted GitLab runner](sample-gitlab-runners-gitlab-ci.images.md).

`fleet:<fleet-name>`
+ Example: `fleet:myFleet`
+ Overrides the fleet settings configured on your project to use the specified fleet. For more information, see [Run builds on reserved capacity fleets](fleets.md).

`buildspec-override:<boolean>`
+ Example: `buildspec-override:true`
+ Allows the build to run buildspec commands in the `INSTALL`, `PRE_BUILD`, and `POST_BUILD` phases if set to `true`.

# Compute images supported with the CodeBuild-hosted GitLab runner
<a name="sample-gitlab-runners-gitlab-ci.images"></a>

In the label you configured in [Tutorial: Configure a CodeBuild-hosted GitLab runner](sample-gitlab-runners.md), you can override your Amazon EC2 environment settings by using the values in the first three columns. CodeBuild provides the following Amazon EC2 compute images. For more information about 

<a name="build-env-ref.supported-images"></a>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/sample-gitlab-runners-gitlab-ci.images.html)

In addition, you can override your Lambda environment settings by using the following values. For more information about CodeBuild Lambda compute, see [Run builds on AWS Lambda compute](lambda.md). CodeBuild supports the following Lambda compute images:

<a name="lambda.supported-images"></a>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/sample-gitlab-runners-gitlab-ci.images.html)

For more information, see [Build environment compute modes and types](build-env-ref-compute-types.md) and [Docker images provided by CodeBuild](build-env-ref-available.md).

# Self-managed Buildkite runner in AWS CodeBuild
<a name="buildkite-runner"></a>

You can configure your project to set up self-hosted Buildkite runners in CodeBuild containers to process your Buildkite jobs. This can be done by setting up a webhook using your CodeBuild project, and updating your Buildkite pipeline YAML steps to use self-hosted runners hosted on CodeBuild machines.

The high-level steps to configure a CodeBuild project to run Buildkite jobs are as follows:
+ Navigate to the CodeBuild console and create a CodeBuild project with the Buildkite runner project runner type configuration
+ Add a `job.scheduled` webhook to your Buildkite organization.
+ Update your Buildkite pipeline YAML steps in Buildkite to configure your build environment.

For a more detailed procedure, see [Tutorial: Configure a CodeBuild-hosted Buildkite runner](sample-runner-buildkite.md). This feature allows your Buildkite jobs to get native integration with AWS, which provides security and convenience through features like IAM, AWS Secrets Manager, AWS CloudTrail, and Amazon VPC. You can access the latest instance types, including ARM-based instances.

# About the CodeBuild-hosted Buildkite runner
<a name="buildkite-runner-about"></a>

The following are some common questions about the CodeBuild-hosted Buildkite runner.

## When should I include the image and instance overrides in the label?
<a name="buildkite-runner-about-overrides"></a>

You can include the image and instance overrides in the label in order to specify different build environment for each of your Buildkite jobs. This can be done without the need to create multiple CodeBuild projects or webhooks. For example, this is useful when you need to use a [matrix for Buildkite jobs](https://buildkite.com/docs/pipelines/configure/workflows/build-matrix).

```
agents:
  queue: "myQueue"
steps:
  - command: "echo \"Hello World\""
    agents:
      project: "codebuild-myProject"
      image: "{{matrix.os}}"
      instance-size: "{{matrix.size}}"
    matrix:
      setup:
        os:
          - "arm-3.0"
          - "al2-5.0"
        size:
          - "small"
          - "large"
```

## Can CodeBuild create webhooks within Buildkite automatically?
<a name="buildkite-runner-about-auto-create"></a>

Currently, Buildkite requires that all webhooks are created manually using their console. You can follow the tutorial at [Tutorial: Configure a CodeBuild-hosted Buildkite runner](sample-runner-buildkite.md) to create a Buildkite webhook manually in the Buildkite console.

## Can I use CloudFormation to create Buildkite webhooks?
<a name="buildkite-runner-about-cloudformation"></a>

CloudFormation is not currently supported for Buildkite runner webhooks, as Buildkite requires webhooks to be created manually using their console.

## Which regions support using a CodeBuild-hosted Buildkite runner?
<a name="buildkite-runner-about-regions"></a>

CodeBuild-hosted Buildkite runners are supported in all CodeBuild regions. For more information about AWS Regions where CodeBuild is available, see [AWS Services by Region](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/).

# Tutorial: Configure a CodeBuild-hosted Buildkite runner
<a name="sample-runner-buildkite"></a>

This tutorial shows you how to configure your CodeBuild projects to run Buildkite jobs. For more information about using Buildkite with CodeBuild see [Self-managed Buildkite runner in AWS CodeBuild](buildkite-runner.md).<a name="sample-runner-buildkite-prerequisites"></a>

To complete this tutorial, you must first:
+ Have access to a Buildkite organization. For more information about setting up a Buildkite account and organization, you can follow this [ Getting Started Tutorial](https://buildkite.com/docs/pipelines/getting-started).
+ Create a Buildkite pipeline, cluster, and queue configured to use self-hosted runners. For more information about setting up these resources, you can reference the [ Buildkite Pipeline Setup Tutorial](https://buildkite.com/docs/pipelines/create-your-own).  
![\[Build project in Buildkite\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/buildkite-first.png)

## Step 1: Generate a Buildkite agent token
<a name="w2aac26c33c12c13b7"></a>

In this step, you will generate an agent token within Buildkite that will be used to authenticate the CodeBuild self-hosted runners. For more information about this resource, see [Buildkite Agent Tokens](https://buildkite.com/docs/agent/v3/tokens). 

**To generate a Buildkite agent token**

1. In your Buildkite cluster, choose **Agent Tokens**, and then choose **New Token**.

1. Add a description to the token and click **Create Token**.

1. Save the agent token value, as it will be used later during the CodeBuild project setup.  
![\[Agent tokens in Buildkite\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/buildkite-createtoken.png)

## Step 2: Create a CodeBuild project with a webhook
<a name="sample-runner-buildkite-create-project"></a>

**To create a CodeBuild project with a webhook**

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a self-hosted build project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Run a build (console)](run-build-console.md).
   +  In **Project configuration**, select **Runner project**. In **Runner**: 
     +  For **Runner provider**, choose **Buildkite**.
     + For **Buildkite agent token**, choose **Create a new agent token by using the create secret page**. You will be prompted to create a new secret in AWS Secrets Manager with a secret value equal to the Buildkite agent token you generated above.
     + (Optional) If you would like to use CodeBuild managed credentials for your job, select your job’s source repository provider under **Buildkite source credential options** and verify that credentials are configured for your account. Additionally, verify that your Buildkite pipeline uses **Checkout using HTTPS**.
**Note**  
Buildkite requires source credentials within the build environment in order to pull your job’s source. See [Authenticating Buildkite to a Private Repository](#sample-runner-buildkite-config) for available source credential options.
   + (Optional) In **Environment**: 
     + Choose a supported **Environment image** and **Compute**. 

       Note that you have the option to override the image and instance settings by using a label in your Buildkite YAML steps. For more information, see [Step 4: Update your Buildkite pipeline steps](#sample-runner-buildkite-update-pipeline).
   + (Optional) In **Buildspec**: 
     + Your buildspec will be ignored by default unless `buildspec-override: "true"` is added as a label. Instead, CodeBuild will override it to use commands that will set up the self-hosted runner.
**Note**  
CodeBuild does not support buildspec files for Buildkite self-hosted runner builds. For inline buildspecs, you will need to enable [ git-credential-helper](https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec.env.git-credential-helper) in your buildspec if you have configured CodeBuild managed source credentials

1. Continue with the default values and then choose **Create build project**.

1. Save the **Payload URL** and **Secret** values from the **Create Webhook** popup. Either follow the instructions in the popup to create a new Buildkite organization webhook or continue to the next section.

## Step 3: Create a CodeBuild webhook within Buildkite
<a name="sample-runner-buildkite-codebuild-webhook"></a>

In this step, you will use the **Payload URL** and **Secret** values from the CodeBuild webhook to create a new webhook within Buildkite. This webhook will be used to trigger builds within CodeBuild when a valid Buildkite job starts.

**To create a new webhook in Buildkite**

1. Navigate to your Buildkite organization’s **Settings** page.

1. Under **Integrations**, select **Notification Services**.

1. Choose **Add** next to the **Webhook** box. In the **Add Webhook Notification** page, use the following configuration:

   1. Under **Webhook URL**, add the saved **Payload URL** value.

   1. Under **Token**, verify that **Send the token as X-Buildkite-Token** is selected. Add your webhook **Secret** value to the **Token** field.

   1. Under , verify that **Send the token as X-Buildkite-Token** is selected. Add your webhook **Secret** value to the **Token** field.

   1. Under **Events**, select the `job.scheduled` webhook event.

   1. (Optional) Under **Pipelines**, you can optionally choose to only trigger builds for a specific pipeline.

1. Choose **Add Webhook Notification**.

## Step 4: Update your Buildkite pipeline steps
<a name="sample-runner-buildkite-update-pipeline"></a>

In this step, you will update your Buildkite pipeline’s steps in order to add necessary labels and optional overrides. For the full list of supported label overrides, see [Label overrides supported with the CodeBuild-hosted Buildkite runner](buildkite-runner-update-labels.md).

**Update your pipeline steps**

1. Navigate to your Buildkite pipeline steps page by selecting your Buildkite pipeline, choosing **Settings**, and then choosing **Steps**.

   If you haven’t already, choose **Convert to YAML steps**.  
![\[Steps to update YAML.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/buildkite-steps.png)

1. At a minimum, you will need to specify a [ Buildkite agent tag ](https://buildkite.com/docs/agent/v3/cli-start#agent-targeting) referencing the name of your CodeBuild pipeline. The project name is needed to link the AWS-related settings of your Buildkite job to a specific CodeBuild project. By including the project name in the YAML, CodeBuild is allowed to invoke jobs with the correct project settings.

   ```
   agents:
     project: "codebuild-<project name>"
   ```

   The following is an example of Buildkite pipeline steps with just the project label tag:

   ```
   agents:
     project: "codebuild-myProject"
   steps:
     - command: "echo \"Hello World\""
   ```

   You can also override your image and compute type in the label. See [Compute images supported with the CodeBuild-hosted Buildkite runner](buildkite-runner-update-yaml.images.md) for a list of available images. The compute type and image in the label will override the environment settings on your project. To override your environment settings for a CodeBuild EC2 or Lambda compute build, use the following syntax:

   ```
   agents:
     project: "codebuild-<project name>"
     image: "<environment-type>-<image-identifier>"
     instance-size: "<instance-size>"
   ```

   The following is an example of Buildkite pipeline steps with image and instance size overrides:

   ```
   agents:
     project: "codebuild-myProject"
     image: "arm-3.0"
     instance-size: "small"
   steps:
     - command: "echo \"Hello World\""
   ```

   You can override the fleet used for your build in the label. This will override the fleet settings configured on your project to use the specified fleet. For more information, see [ Run builds on reserved capacity fleets ](https://docs.aws.amazon.com/codebuild/latest/userguide/fleets.html).

   To override your fleet settings for an Amazon EC2 compute build, use the following syntax:

   ```
   agents:
     project: "codebuild-<project name>"
     fleet: "<fleet-name>"
   ```

   To override both the fleet and the image used for the build, use the following syntax:

   ```
   agents:
     project: "codebuild-<project name>"
     fleet: "<fleet-name>"
     image: "<environment-type>-<image-identifier>"
   ```

   The following is an example of Buildkite pipeline steps with fleet and image overrides:

   ```
   agents:
     project: "codebuild-myProject"
     fleet: "myFleet"
     image: "arm-3.0"
   steps:
     - command: "echo \"Hello World\""
   ```

1. You can choose to run inline buildspec commands during the self-hosted Buildkite runner build (see [Run buildspec commands for the INSTALL, PRE\$1BUILD, and POST\$1BUILD phases](sample-runner-buildkite-buildspec.md) for more details). To specify that the CodeBuild build should run buildspec commands during your Buildkite self-hosted runner build, use the following syntax:

   ```
   agents:
     project: "codebuild-<project name>"
     buildspec-override: "true"
   ```

   The following is an example of a Buildkite pipeline with a buildspec override:

   ```
   agents:
     project: "codebuild-myProject"
     buildspec-override: "true"
   steps:
     - command: "echo \"Hello World\""
   ```

1. Optionally, you can provide labels outside of those that CodeBuild supports. These labels will be ignored for the purpose of overriding attributes of the build, but will not fail the webhook request. For example, adding `myLabel: “testLabel"` as a label will not prevent the build from running.

## Step 5: Review your results
<a name="sample-runner-buildkite-verify"></a>

Whenever a Buildkite job is started in your pipeline, CodeBuild will receive a `job.scheduled` webhook event through the Buildkite webhook. For each job in your Buildkite build, CodeBuild will start a build to run an ephemeral Buildkite runner. The runner is responsible for executing a single Buildkite job. Once the job is completed, the runner and the associated build process will be immediately terminated.

To view your workflow job logs, navigate to your Buildkite pipeline and select the most recent build (you can trigger a new build by choosing **New Build**). Once the associated CodeBuild build for each of your jobs starts and picks up the job, you should see logs for the job within the Buildkite console

![\[Review results.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/buildkite-log.png)


## Authenticating Buildkite to a Private Repository
<a name="sample-runner-buildkite-config"></a>

If you have a private repository configured within your Buildkite pipeline, Buildkite requires [additional permissions within the build environment](https://buildkite.com/docs/agent/v3/github-ssh-keys) to pull the repository, as Buildkite does not vend credentials to self-hosted runners to pull from private repositories. In order to authenticate the Buildkite self-hosted runner agent to your external private source repository, you can use one of the following options.

**To authenticate with CodeBuild**

CodeBuild offers managed credentials handling for Supported source types. In order to use CodeBuild source credentials to pull your job’s source repository, you can use the following steps:

1. In the CodeBuild console, navigate to **Edit project** or create a new CodeBuild project using the steps in [Step 2: Create a CodeBuild project with a webhook](#sample-runner-buildkite-create-project).

1. Under **Buildkite source credential options**, select your job’s source repository provider.

   1. If you would like to use account-level CodeBuild credentials, verify that they are configured correctly. Additionally, if your project has an inline buildspec configured, verify that [ git-credential-helper ](https://docs.aws.amazon.com/codebuild/latest/userguide/build-spec-ref.html#build-spec.env.git-credential-helper) is enabled.

   1. If you would like to use project level CodeBuild credentials, select **Use override credentials for this project only** and set up credentials for your project.

1. In your Buildkite pipeline settings, navigate to **Repository Settings**. Set your source repository checkout settings to **Checkout using HTTPS**  
![\[Review results.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/buildkite-repo-https.png)

**To authenticate with Buildkite secrets**

Buildkite maintains an [ ssh-checkout plugin](https://github.com/buildkite-plugins/git-ssh-checkout-buildkite-plugin) which can be used to authenticate the self-hosted runner to an external source repository using an ssh key. The key value is stored as a [Buildkite secret](https://buildkite.com/docs/pipelines/security/secrets/buildkite-secrets) and fetched automatically by the Buildkite self-hosted runner agent when attempting to pull a private repository. In order to configure the ssh-checkout plugin for your Buildkite pipeline, you can use the following steps:

1. Generate a private and public ssh key using your email address e.g. `ssh-keygen -t rsa -b 4096 -C "myEmail@address.com"`

1. Add the public key to your private source repository. For example, you can follow [this guide](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account) to add a key to a GitHub account.

1. Add a [ new SSH key secret ](https://buildkite.com/docs/pipelines/hosted-agents/code-access#private-repositories-with-other-providers-add-the-ssh-key-secret) to your Buildkite cluster. Within your Buildkite cluster, select **Secrets** → **New Secret**. Add a name for you secret in the **Key** field and add your private SSH key into the **Value** field:  
![\[Review results.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/buildkite-secret.png)

1. Within your Buildkite pipeline, navigate to your repository settings and set checkout to use **SSH**.  
![\[Review results.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/buildkite-repo.png)

1. Update your pipeline YAML steps to use the `git-ssh-checkout` plugin. For example, the following pipeline YAML file uses the checkout action with the above Buildkite secret key:

   ```
   agents:
     project: "codebuild-myProject"
   steps:
     - command: "npm run build"
       plugins:
         - git-ssh-checkout#v0.4.1:
             ssh-secret-key-name: 'SOURCE_SSH_KEY'
   ```

1. When running a Buildkite self-hosted runner job within CodeBuild, Buildkite will now automatically use your configured secret value when pulling your private repository

## Runner configuration options
<a name="sample-buildkite-runner-auth"></a>

You can specify the following environment variables in your project configuration to modify the setup configuration of your self-hosted runners:
+ `CODEBUILD_CONFIG_BUILDKITE_AGENT_TOKEN`: CodeBuild will fetch the secret value configured as the value of this environment variable from AWS Secrets Manager in order to register the Buildkite self-hosted runner agent. This environment variable must be of type `SECRETS_MANAGER`, and the value should be the name of your secret in Secrets Manager. A Buildkite agent token environment variable is required for all Buildkite runner projects.
+ `CODEBUILD_CONFIG_BUILDKITE_CREDENTIAL_DISABLE`: By default, CodeBuild will load account or project level source credentials into the build environment, as these credentials are used by the Buildkite agent to pull the job’s source repository. To disable this behavior, you can add this environment variable to your project with the value set to `true`, which will prevent source credentials from being loaded into the build environment.

# Run buildspec commands for the INSTALL, PRE\$1BUILD, and POST\$1BUILD phases
<a name="sample-runner-buildkite-buildspec"></a>

By default, CodeBuild ignores any buildspec commands when running a self-hosted Buildkite runner build. To run buildspec commands during the build, 

```
buildspec-override: "true"
```

 can be added as a suffix to the label:

```
agents:
  project: "codebuild-<project name>"
  buildspec-override: "true"
```

By using this command, CodeBuild will create a folder called `buildkite-runner` in the container's primary source folder. When the Buildkite runner starts during the `BUILD` phase, the runner will run in the `buildkite-runner` directory.

There are several limitations when using a buildspec override in a self-hosted Buildkite build:
+ The Buildkite agent requires that source credentials exist within the build environment to pull the job’s source repository. If you use CodeBuild source credentials for authentication, you will need to enable `git-credential-helper` in your buildspec. For example, you can use the following buildspec to enable `git-credential-helper` for your Buildkite builds:

  ```
  version: 0.2
  env:
    git-credential-helper: yes
  phases:
    pre_build:
      commands:
         - echo "Hello World"
  ```
+ CodeBuild will not run buildspec commands during the `BUILD` phase, as the self-hosted runner runs in the `BUILD` phase.
+ CodeBuild does not support buildspec files for Buildkite runner builds. Only inline buildspecs are supported for Buildlkite self-hosted runners
+ If a build command fails in the `PRE_BUILD` or `INSTALL` phase, CodeBuild will not start the self-hosted runner and the Buildkite job will need to be cancelled manually.

# Setting up a Buildkite runner programmatically
<a name="sample-runner-buildkite-CLI"></a>

In order to configure a Buildkite runner project programatically, you will need to configure the following resources:

**To create a Buildkite runner programmatically**

1. Create a Buildkite agent token and save the token in plaintext within AWS Secrets Manager.

1. Set up a CodeBuild project with your preferred configuration. You will need to configure the following additional attributes:

   1. An environment value with name `CODEBUILD_CONFIG_BUILDKITE_AGENT_TOKEN`, type `SECRETS_MANAGER`, and a value equal to the Buildkite agent token associated with your Buildkite cluster.

   1. Source type equal to `NO_SOURCE`

   1. Permissions to access the secret created in step 1 in your project’s service role

   For example, you can use the following command to create a valid Buildkite runner project through the CLI:

   ```
   aws codebuild create-project \
   --name buildkite-runner-project \
   --source "{\"type\": \"NO_SOURCE\",\"buildspec\":\"\"}" \
   --environment "{\"image\":\"aws/codebuild/amazonlinux-x86_64-standard:5.0\",\"type\":\"LINUX_CONTAINER\",\"computeType\":\"BUILD_GENERAL1_MEDIUM\",\"environmentVariables\":[{\"name\":\"CODEBUILD_CONFIG_BUILDKITE_AGENT_TOKEN\",\"type\":\"SECRETS_MANAGER\",\"value\":\"<buildkite-secret-name>\"}]}" \
   --artifacts "{\"type\": \"NO_ARTIFACTS\"}" \
   --service-role <service-role>
   ```

1. Create a Buildkite runner webhook on the project created in step 2. You will need to use the following configuration options when creating the webhook:

   1. **build-type** should be equal to `RUNNER_BUILDKITE_BUILD`

   1. A filter with type `EVENT` and a pattern equal to `WORKFLOW_JOB_QUEUED` 

   For example, you can use the following command to create a valid Buildkite runner webhook through the CLI:

   ```
   aws codebuild create-webhook \
   --project-name buildkite-runner-project \
   --filter-groups "[[{\"type\":\"EVENT\",\"pattern\":\"WORKFLOW_JOB_QUEUED\"}]]" \
   --build-type RUNNER_BUILDKITE_BUILD
   ```

1. Save the **Payload URL** and **Secret** values returned by the `create-webhook` call and use the credentials to create a webhook within the Buildkite console. You can reference Step 3: Create a CodeBuild webhook within Buildkite in [Tutorial: Configure a CodeBuild-hosted Buildkite runner](sample-runner-buildkite.md) for a guide on how to set up this resource.

# Troubleshoot the webhook for failed builds or a hanging job
<a name="buildkite-runner-troubleshoot-webhook"></a>

 **Issue: ** 

The webhook you set up in [Tutorial: Configure a CodeBuild-hosted Buildkite runner](sample-runner-buildkite.md) isn't working or your workflow job is hanging in Buildkite.

 **Possible causes: ** 
+ Your webhook **job.scheduled** event might be failing to trigger a build. Review the **Response** logs to view the response or error message.
+ Your CodeBuild build fails before starting the Buildkite self-hosted runner agent to handle your job.

 **Recommended solutions: ** 

To debug failed Buildkite webhook events:

1. In your Buildkite organization settings, navigate to **Notification Services**, select your CodeBuild webhook, and then find the **Request Log**.

1. Find the `job.scheduled` webhook event associated with your stuck Buildkite job. You can use the job ID field within the webhook payload to correlate the webhook event to your Buildkite job.

1. Select the **Response** tab and check the response body. Verify that the **Response** status code is `200` and the **Response** body doesn’t contain any unexpected messages.  
![\[Response for the webhook.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/buildkite-request.png)

# Troubleshoot the webhook permission issues
<a name="buildkite-runner-troubleshoot-webhook-permissions"></a>

 **Issue: ** 

The Buildkite job fails to checkout the job's source repository due to permission issues.

 **Possible causes: ** 
+ CodeBuild does not have sufficient permissions to checkout the job's source repository.
+ The pipeline's repository settings are set to check out using SSH for CodeBuild managed credentials.

 **Recommended solutions: ** 
+ Verify that CodeBuild has sufficient permissions configured to check out the job's source repository. Additionally, verify that your CodeBuild project's service role has sufficient permissions to access the configured source permission option.
+ Verify that your Buildkite pipeline is configured to use checkout using HTTPS if you are using CodeBuild managed source repository credentials.

# Label overrides supported with the CodeBuild-hosted Buildkite runner
<a name="buildkite-runner-update-labels"></a>

In your Buildkite pipeline steps agent tag labels, you can provide a variety of label overrides that modify your self-hosted runner build. Any builds not recognized by CodeBuild will be ignored but will not fail your webhook request. For example, the following workflow YAML includes overrides for image, instance size, fleet, and the buildspec:

```
agents:
  queue: "myQueue"
steps:
  - command: "echo \"Hello World\""
    agents:
      project: "codebuild-myProject"
      image: "{{matrix.os}}"
      instance-size: "{{matrix.size}}"
      buildspec-override: "true"
    matrix:
      setup:
        os:
          - "arm-3.0"
          - "al2-5.0"
        size:
          - "small"
          - "large"
```

 `project:codebuild-<project-name>` (required)
+ Example: `project: "codebuild-myProject"`
+ Required for all Buildkite pipeline step configurations. *<project name>* should be equal to the name of the project for which the self-hosted runner webhook is configured.

`queue: "<queue-name>"`
+ Example: `queue: "<queue-name>"`
+ Used to route Buildkite jobs to a specific queue. See the [ Buildkite Agent Queue Tag ](https://buildkite.com/docs/agent/v3/cli-start#the-queue-tag) for more information.

 `image: "<environment-type>-<image-identifier>"` 
+ Example: `image: "arm-3.0"`
+ Overrides the image and environment type used when starting the self-hosted runner build with a curated image. To learn about supported values, see [Compute images supported with the CodeBuild-hosted Buildkite runner](buildkite-runner-update-yaml.images.md).

  1. To override the image and environment type used with a custom image, use `image: "custom-<environment-type>-<custom-image-identifier>"`

  1. Example: 

     ```
     image:
           "custom-arm-public.ecr.aws/codebuild/amazonlinux-aarch64-standard:3.0"
     ```
**Note**  
If the custom image resides in a private registry, you must configure the appropriate registry credentials in your CodeBuild project.

`instance-size: "<instance-size>"`
+ Example: `instance-size: "medium"`
+ Overrides the instance type used when starting the self-hosted runner build. To learn about supported values, see [Compute images supported with the CodeBuild-hosted Buildkite runner](buildkite-runner-update-yaml.images.md).

`fleet: "<fleet-name>"`
+ Example: `fleet: "myFleet"`
+ Overrides the fleet settings configured on your project to use the specified fleet. For more information, see [ Run builds on reserved capacity fleets ](https://docs.aws.amazon.com/codebuild/latest/userguide/fleets.html).

`buildspec-override: "<boolean>"`
+ Example: `buildspec-override: "true"`
+ Allows the build to run buildspec commands in the `INSTALL`, `PRE_BUILD`, and `POST_BUILD` phases if set to `true`.

# Compute images supported with the CodeBuild-hosted Buildkite runner
<a name="buildkite-runner-update-yaml.images"></a>

In the label you configured in [Self-managed Buildkite runner in AWS CodeBuild](buildkite-runner.md), you can override your Amazon EC2 environment settings by using the values in the first three columns. CodeBuild provides the following Amazon EC2 compute images. For more information about 

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/buildkite-runner-update-yaml.images.html)

In addition, you can override your Lambda environment settings by using the following values. For more information about CodeBuild Lambda compute, see [Run builds on AWS Lambda compute](lambda.md). CodeBuild supports the following Lambda compute images:

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/buildkite-runner-update-yaml.images.html)

For more information, see [Build environment compute modes and types](build-env-ref-compute-types.md) and [Docker images provided by CodeBuild](build-env-ref-available.md).

# Use webhooks with AWS CodeBuild
<a name="webhooks"></a>

AWS CodeBuild supports webhook integration with GitHub, GitHub Enterprise Server, GitLab, GitLab Self Managed, and Bitbucket. 

**Topics**
+ [

## Best practices for using webhooks with AWS CodeBuild
](#webhook-best-practices)
+ [

# Bitbucket webhook events
](bitbucket-webhook.md)
+ [

# GitHub global and organization webhooks
](github-global-organization-webhook.md)
+ [

# GitHub manual webhooks
](github-manual-webhook.md)
+ [

# GitHub webhook events
](github-webhook.md)
+ [

# GitLab group webhooks
](gitlab-group-webhook.md)
+ [

# GitLab manual webhooks
](gitlab-manual-webhook.md)
+ [

# GitLab webhook events
](gitlab-webhook.md)
+ [

# Buildkite manual webhooks
](buildkite-manual-webhook.md)
+ [

# Pull request comment approval
](pull-request-build-policy.md)

## Best practices for using webhooks with AWS CodeBuild
<a name="webhook-best-practices"></a>

For projects that use public repositories to setup webhooks, we recommend the following options:

Setup `ACTOR_ACCOUNT_ID` filters  
Add `ACTOR_ACCOUNT_ID` filters to your project’s webhook filter groups to specify which users can trigger a build. Every webhook event delivered to CodeBuild comes with sender information that specifies the actor's identifier. CodeBuild will filter the webhooks based on the regular expression pattern provided in the filters. You can specify the specific users that are allowed to trigger builds with this filter. For more information, see [GitHub webhook events](github-webhook.md) and [Bitbucket webhook events](bitbucket-webhook.md). 

Setup `FILE_PATH` filters  
Add `FILE_PATH` filters to your project’s webhook filter groups to include or exclude the files that can trigger a build when changed. For example, you can deny build requests for changes to the `buildspec.yml` file using a regular expression pattern such as `^buildspec.yml$`, along with the `excludeMatchedPattern` property. For more information, see [GitHub webhook events](github-webhook.md) and [Bitbucket webhook events](bitbucket-webhook.md). 

Scope down the permissions for your build IAM role  
Builds triggered by a webhook use the IAM service role specified in the project. We recommend setting the permissions in the service role to the minimum set of permissions required to run the build. For example, in a test and deploy scenario, create one project for testing and another project for deployment. The testing project accepts webhook builds from the repository, but provides no write permissions to your resources. The deployment project provides write permissions to your resources, and the webhook filter is configured to only allow trusted users to trigger builds.

Use an inline or an Amazon S3 stored buildspec  
If you define your buildspec inline within the project itself, or store the buildspec file in an Amazon S3 bucket, the buildspec file is only visible to the project owner. This prevents pull requests from making code changes to the buildspec file and triggering unwanted builds. For more information, see [ProjectSource.buildspec](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectSource.html#CodeBuild-Type-ProjectSource-buildspec) in the *CodeBuild API Reference*.

# Bitbucket webhook events
<a name="bitbucket-webhook"></a>

You can use webhook filter groups to specify which Bitbucket webhook events trigger a build. For example, you can specify that a build is only triggered for changes to specific branches. 

You can create one or more webhook filter groups to specify which webhook events trigger a build. A build is triggered if any filter group evaluates to true, which occurs when all the filters in the group evaluate to true. When you create a filter group, you specify: 

**An event**  
For Bitbucket, you can choose one or more of the following events:  
+ `PUSH`
+ `PULL_REQUEST_CREATED`
+ `PULL_REQUEST_UPDATED`
+ `PULL_REQUEST_MERGED`
+ `PULL_REQUEST_CLOSED`
The webhook's event type is in its header in the `X-Event-Key` field. The following table shows how `X-Event-Key` header values map to the event types.  
You must enable the `merged` event in your Bitbucket webhook setting if you create a webhook filter group that uses the `PULL_REQUEST_MERGED` event type. You must also enable the `declined` event in your Bitbucket webhook setting if you create a webhook filter group that uses the `PULL_REQUEST_CLOSED` event type.    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/bitbucket-webhook.html)
For `PULL_REQUEST_MERGED`, if a pull request is merged with the squash strategy and the pull request branch is closed, the original pull request commit no longer exists. In this case, the `CODEBUILD_WEBHOOK_MERGE_COMMIT` environment variable contains the identifier of the squashed merge commit.

**One or more optional filters**  
Use a regular expression to specify a filter. For an event to trigger a build, every filter within the group associated with it must evaluate to true.    
`ACTOR_ACCOUNT_ID` (`ACTOR_ID` in the console)  
A webhook event triggers a build when a Bitbucket account ID matches the regular expression pattern. This value appears in the `account_id` property of the `actor` object in the webhook filter payload.  
`HEAD_REF`  
A webhook event triggers a build when the head reference matches the regular expression pattern (for example, `refs/heads/branch-name` and `refs/tags/tag-name`). A `HEAD_REF` filter evaluates the Git reference name for the branch or tag. The branch or tag name appears in the `name` field of the `new` object in the `push` object of the webhook payload. For pull request events, the branch name appears in the `name` field in the `branch` object of the `source` object in the webhook payload.  
`BASE_REF`  
A webhook event triggers a build when the base reference matches the regular expression pattern. A `BASE_REF` filter works with pull request events only (for example, `refs/heads/branch-name`). A `BASE_REF` filter evaluates the Git reference name for the branch. The branch name appears in the `name` field of the `branch` object in the `destination` object in the webhook payload.  
`FILE_PATH`  
A webhook triggers a build when the path of a changed file matches the regular expression pattern.  
`COMMIT_MESSAGE`  
A webhook triggers a build when the head commit message matches the regular expression pattern.  
`WORKFLOW_NAME`  
A webhook triggers a build when the workflow name matches the regular expression pattern.

**Note**  
You can find the webhook payload in the webhook settings of your Bitbucket repository. 

**Topics**
+ [

# Filter Bitbucket webhook events (console)
](bitbucket-webhook-events-console.md)
+ [

# Filter Bitbucket webhook events (SDK)
](bitbucket-webhook-events-sdk.md)
+ [

# Filter Bitbucket webhook events (CloudFormation)
](bitbucket-webhook-events-cfn.md)

# Filter Bitbucket webhook events (console)
<a name="bitbucket-webhook-events-console"></a>

 To use the AWS Management Console to filter webhook events: 

1.  Select **Rebuild every time a code change is pushed to this repository** when you create your project. 

1.  From **Event type**, choose one or more events. 

1.  To filter when an event triggers a build, under **Start a build under these conditions**, add one or more optional filters. 

1.  To filter when an event is not triggered, under **Don't start a build under these conditions**, add one or more optional filters. 

1.  Choose **Add filter group** to add another filter group. 

 For more information, see [Create a build project (console)](create-project.md#create-project-console) and [WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html) in the *AWS CodeBuild API Reference*. 

In this example, a webhook filter group triggers a build for pull requests only:

![\[A webhook filter group that triggers a build for pull requests only.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-bitbucket.png)


Using an example of two filter groups, a build is triggered when one or both evaluate to true:
+ The first filter group specifies pull requests that are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` and head references that match `^refs/heads/branch1!`. 
+ The second filter group specifies push requests on branches with Git reference names that match the regular expression `^refs/heads/branch1$`. 

![\[An example of two filter groups.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-head-base-regexes-bitbucket.png)


In this example, a webhook filter group triggers a build for all requests except tag events. 

![\[A webhook filter group that triggers a build for all requests except tag events.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-exclude-bitbucket.png)


In this example, a webhook filter group triggers a build only when files with names that match the regular expression `^buildspec.*` change. 

![\[A webhook filter group that triggers a build only when files with names that match the regular expression specified.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-file-name-regex.png)


In this example, a webhook filter group triggers a build only when files are changed in `src` or `test` folders.

![\[A webhook filter group that triggers a build only when files are changed in specified folders.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-file-name-combined-regex.png)


In this example, a webhook filter group triggers a build only when a change is made by a Bitbucket user who does not have an account ID that matches the regular expression `actor-account-id`. 

**Note**  
 For information about how to find your Bitbucket account ID, see https://api.bitbucket.org/2.0/users/*user-name*, where *user-name* is your Bitbucket user name. 

![\[A webhook filter group that triggers a build only when a change is made by a Bitbucket user who does not have an account ID.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-actor-bitbucket.png)


In this example, a webhook filter group triggers a build for a push event when the head commit message matches the regular expression `\[CodeBuild\]`. 

![\[A webhook filter group that triggers a build for a push event when the head commit message matches the regular expression.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-commit-message.png)


# Filter Bitbucket webhook events (SDK)
<a name="bitbucket-webhook-events-sdk"></a>

 To use the AWS CodeBuild SDK to filter webhook events, use the `filterGroups` field in the request syntax of the `CreateWebhook` or `UpdateWebhook` API methods. For more information, see [WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html) in the *CodeBuild API Reference*. 

 To create a webhook filter that triggers a build for pull requests only, insert the following into the request syntax: 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_MERGED, PULL_REQUEST_CLOSED"
    }
  ]
]
```

 To create a webhook filter that triggers a build for specified branches only, use the `pattern` parameter to specify a regular expression to filter branch names. Using an example of two filter groups, a build is triggered when one or both evaluate to true:
+ The first filter group specifies pull requests that are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` and head references that match `^refs/heads/myBranch$`. 
+ The second filter group specifies push requests on branches with Git reference names that match the regular expression `^refs/heads/myBranch$`. 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_CLOSED"
    },
    {
      "type": "HEAD_REF",
      "pattern": "^refs/heads/myBranch$"
    },
    {
      "type": "BASE_REF",
      "pattern": "^refs/heads/main$"
    }
  ],
  [
    {
      "type": "EVENT",
      "pattern": "PUSH"
    },
    {
      "type": "HEAD_REF",
      "pattern": "^refs/heads/myBranch$"
    }
  ]
]
```

 You can use the `excludeMatchedPattern` parameter to specify which events do not trigger a build. In this example, a build is triggered for all requests except tag events. 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_MERGED, PULL_REQUEST_CLOSED"
    },
    {
      "type": "HEAD_REF",
      "pattern": "^refs/tags/.*",
      "excludeMatchedPattern": true
    }
  ]
]
```

You can create a filter that triggers a build only when a change is made by a Bitbucket user with account ID `actor-account-id`. 

**Note**  
 For information about how to find your Bitbucket account ID, see https://api.bitbucket.org/2.0/users/*user-name*, where *user-name* is your Bitbucket user name. 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_MERGED, PULL_REQUEST_CLOSED"
    },
    {
      "type": "ACTOR_ACCOUNT_ID",
      "pattern": "actor-account-id"
    }
  ]
]
```

You can create a filter that triggers a build only when files with names that match the regular expression in the `pattern` argument change. In this example, the filter group specifies that a build is triggered only when files with a name that matches the regular expression `^buildspec.*` change. 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PUSH"
    },
    {
      "type": "FILE_PATH",
      "pattern": "^buildspec.*"
    }
  ]
]
```

In this example, the filter group specifies that a build is triggered only when files are changed in `src` or `test` folders.

```
"filterGroups": [
    [
        {
            "type": "EVENT", 
            "pattern": "PUSH"
        },
        {
            "type": "FILE_PATH", 
            "pattern": "^src/.+|^test/.+"
        }
    ]
]
```

You can create a filter that triggers a build only when the head commit message matches the regular expression in the pattern argument. In this example, the filter group specifies that a build is triggered only when the head commit message of the push event matches the regular expression `\[CodeBuild\]`. 

```
  "filterGroups": [
    [
      {
        "type": "EVENT",
        "pattern": "PUSH"
      },
      {
        "type": "COMMIT_MESSAGE",
        "pattern": "\[CodeBuild\]"
      }
    ]
  ]
```

# Filter Bitbucket webhook events (CloudFormation)
<a name="bitbucket-webhook-events-cfn"></a>

 To use an CloudFormation template to filter webhook events, use the AWS CodeBuild project's `FilterGroups` property. The following YAML-formatted portion of an CloudFormation template creates two filter groups. Together, they trigger a build when one or both evaluate to true: 
+  The first filter group specifies pull requests are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` by a Bitbucket user who does not have account ID `12345`. 
+  The second filter group specifies push requests are created on branches with Git reference names that match the regular expression `^refs/heads/.*`. 
+ The third filter group specifies a push request with a head commit message matching the regular expression `\[CodeBuild\]`.

```
CodeBuildProject:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: MyProject
    ServiceRole: service-role
    Artifacts:
      Type: NO_ARTIFACTS
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/standard:5.0
    Source:
      Type: BITBUCKET
      Location: source-location
    Triggers:
      Webhook: true
      FilterGroups:
        - - Type: EVENT
            Pattern: PULL_REQUEST_CREATED,PULL_REQUEST_UPDATED
          - Type: BASE_REF
            Pattern: ^refs/heads/main$
            ExcludeMatchedPattern: false
          - Type: ACTOR_ACCOUNT_ID
            Pattern: 12345
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: HEAD_REF
            Pattern: ^refs/heads/.*
          - Type: FILE_PATH
            Pattern: READ_ME
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: COMMIT_MESSAGE
            Pattern: \[CodeBuild\]
          - Type: FILE_PATH
            Pattern: ^src/.+|^test/.+
```

# GitHub global and organization webhooks
<a name="github-global-organization-webhook"></a>

You can use CodeBuild GitHub global or organization webhooks to start builds on webhook events from any repository within a GitHub organization or enterprise. Global and organization webhooks work with any of the existing GitHub webhook event types, and can be configured by adding a scope configuration when creating a CodeBuild webhook. You can also use global and organization webhooks to [set up self-hosted GitHub Action runners within CodeBuild](action-runner.md) in order to receive `WORKFLOW_JOB_QUEUED` events from multiple repositories within a single project.

**Topics**
+ [

# Set up a global or organization GitHub webhook
](github-global-organization-webhook-setup.md)
+ [

# Filter GitHub global or organization webhook events (console)
](github-global-organization-webhook-events-console.md)
+ [

# Filter GitHub organization webhook events (CloudFormation)
](github-organization-webhook-events-cfn.md)

# Set up a global or organization GitHub webhook
<a name="github-global-organization-webhook-setup"></a>

The high-level steps to set up a global or organization GitHub webhook are as follows. For more information about global and organization GitHub webhooks, see [GitHub global and organization webhooks](github-global-organization-webhook.md).

1. Set your project's source location to `CODEBUILD_DEFAULT_WEBHOOK_SOURCE_LOCATION`.

1. In the webhook's scope configuration, set the scope to either `GITHUB_ORGANIZATION` or `GITHUB_GLOBAL` depending on whether it should be an organization or [ global webhook](https://docs.github.com/en/enterprise-cloud@latest/admin/monitoring-activity-in-your-enterprise/exploring-user-activity-in-your-enterprise/managing-global-webhooks). For more information, see [ Types of webhooks](https://docs.github.com/en/webhooks/types-of-webhooks).

1. Specify a name as part of the webhook's scope configuration. For organization webhooks, this is the organization name, and for global webhooks this is the enterprise name.
**Note**  
If the project's source type is `GITHUB_ENTERPRISE`, you will also need to specify a domain as part of the webhook scope configuration.

1. (Optional) If you would only like to receive webhook events for specific repositories within your organization or enterprise, you can specify `REPOSITORY_NAME` as a filter when creating the webhook.

1. If you are creating an organization webhook, ensure that CodeBuild has permissions to create organization level webhooks within GitHub. You can create a GitHub personal access token with organization webhook permissions, or use CodeBuild OAuth. For more information, see [GitHub and GitHub Enterprise Server access token](access-tokens-github.md).

   Note that organization webhooks work with any of the existing GitHub webhook event types.

1. If you are creating a global webhook, the webhook will need to be created manually. For more information about how to manually create a webhook within GitHub, see [GitHub manual webhooks](github-manual-webhook.md).

   Note that global webhooks only support the `WORKFLOW_JOB_QUEUED` event type. For more information, see [Tutorial: Configure a CodeBuild-hosted GitHub Actions runner](action-runner.md).

# Filter GitHub global or organization webhook events (console)
<a name="github-global-organization-webhook-events-console"></a>

When creating a GitHub project through the console, select the following options to create a GitHub global or organization webhook within the project. For more information about global and organization GitHub webhooks, see [GitHub global and organization webhooks](github-global-organization-webhook.md).

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a build project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Run a build (console)](run-build-console.md).
   +  In **Source**: 
     +  For **Source provider**, choose **GitHub** or **GitHub Enterprise**.
     +  For **Repository**, choose **GitHub scoped webhook**. 

        The GitHub repository will automatically be set to `CODEBUILD_DEFAULT_WEBHOOK_SOURCE_LOCATION`, which is the required source location for global and organization webhooks. 
**Note**  
If you are using organization webhooks, make sure that CodeBuild has permissions to create organization level webhooks within GitHub. If you're using an [existing OAuth connection](oauth-app-github.md), you may need to regenerate the connection in order to grant CodeBuild this permission. Alternatively, you can create the webhook manually using the [CodeBuild manual webhooks feature](github-manual-webhook.md). Note that if you have an existing GitHub OAuth token and would like to add additional organization permissions, you can [revoke the OAuth token's permission](https://docs.github.com/en/apps/oauth-apps/using-oauth-apps/reviewing-your-authorized-oauth-apps) and reconnect the token through the CodeBuild console.  
![\[The configuration of GitHub scoped webhook.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-organization-webhook-source.png)
   +  In **Primary source webhook events**: 
     +  For **Scope type**, choose **Organization level** if you're creating an organization webhook or **Enterprise level** if you're creating a global webhook.
     +  For **Name**, enter either the enterprise or organization name, depending on if the webhook is a global or organization webhook.

       If the project's source type is `GITHUB_ENTERPRISE`, you also need to specify a domain as part of the webhook organization configuration. For example, if the URL of your organization is **https://domain.com/orgs/org-name**, then the domain is **https://domain.com**.
**Note**  
 This name cannot be changed after the webhook has been created. To change the name, you can delete and re-create the webhook. If you want to remove the webhook entirely, you can also update the project source location to a GitHub repository.   
![\[The configuration of global or organization webhooks.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-organization-webhook-primary-events.png)
     +  (Optional) In **Webhook event filter groups**, you can specify which [events you would like to trigger a new build](github-webhook.md). You can also specify `REPOSITORY_NAME` as a filter to only trigger builds on webhook events from specific repositories.  
![\[A filter that only triggers builds on webhook events from specific repositories.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-organization-webhook-filter-groups.png)

       You can also set the event type to `WORKFLOW_JOB_QUEUED` to set up self-hosted GitHub Actions runners. For more information, see [Tutorial: Configure a CodeBuild-hosted GitHub Actions runner](action-runner.md).

1. Continue with the default values and then choose **Create build project**.

# Filter GitHub organization webhook events (CloudFormation)
<a name="github-organization-webhook-events-cfn"></a>

 To use an CloudFormation template to filter organization webhook events, use the AWS CodeBuild project's `ScopeConfiguration` property. For more information about global and organization GitHub webhooks, see [GitHub global and organization webhooks](github-global-organization-webhook.md).

**Note**  
Global webhooks and GitHub Enterprise webhooks are not supported by CloudFormation. 

 The following YAML-formatted portion of an CloudFormation template creates four filter groups. Together, they trigger a build when one or all evaluate to true: 
+  The first filter group specifies pull requests are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` by a GitHub user who does not have account ID `12345`. 
+  The second filter group specifies push requests are created on files with names that match the regular expression `READ_ME` in branches with Git reference names that match the regular expression `^refs/heads/.*`. 
+ The third filter group specifies a push request with a head commit message matching the regular expression `\[CodeBuild\]`.
+ The fourth filter group specifies a GitHub Actions workflow job request with a workflow name matching the regular expression `\[CI-CodeBuild\]`.

```
CodeBuildProject:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: MyProject
    ServiceRole: service-role
    Artifacts:
      Type: NO_ARTIFACTS
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/standard:5.0
    Source:
      Type: GITHUB
      Location: source-location
    Triggers:
      Webhook: true
      ScopeConfiguration:
        Name: organization-name
        Scope: GITHUB_ORGANIZATION
      FilterGroups:
        - - Type: EVENT
            Pattern: PULL_REQUEST_CREATED,PULL_REQUEST_UPDATED
          - Type: BASE_REF
            Pattern: ^refs/heads/main$
            ExcludeMatchedPattern: false
          - Type: ACTOR_ACCOUNT_ID
            Pattern: 12345
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: HEAD_REF
            Pattern: ^refs/heads/.*
          - Type: FILE_PATH
            Pattern: READ_ME
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: COMMIT_MESSAGE
            Pattern: \[CodeBuild\]
          - Type: FILE_PATH
            Pattern: ^src/.+|^test/.+
        - - Type: EVENT
            Pattern: WORKFLOW_JOB_QUEUED
          - Type: WORKFLOW_NAME
            Pattern: \[CI-CodeBuild\]
```

# GitHub manual webhooks
<a name="github-manual-webhook"></a>

You can configure manual GitHub webhooks to prevent CodeBuild from automatically attempting to create a webhook within GitHub. CodeBuild returns a payload URL in as part of the call to create the webhook and can be used to manually create the webhook within GitHub. Even if CodeBuild is not allowlisted to create a webhook in your GitHub account, you can still manually create a webhook for your build project.

Use the following procedure to create a GitHub manual webhook.

**To create a GitHub manual webhook**

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a build project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Run a build (console)](run-build-console.md).
   +  In **Source**: 
     +  For **Source provider**, choose **GitHub**.
     +  For **Repository**, choose **Repository in my GitHub account**. 
     +  For **Repository URL**, enter **https://github.com/*user-name*/*repository-name***. 
   +  In **Primary source webhook events**: 
     +  For **Webhook - optional**, choose **Rebuild every time a code change is pushed to this repository**.
     +  Choose **Additional configuration** and for **Manual creation - optional**, choose **Manually create a webhook for this repository in GitHub console.**.

1. Continue with the default values and then choose **Create build project**. Take note of the **Payload URL** and **Secret** values as you will use these later.  
![\[Payload URL and Secret configuration for manual webhooks.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-manual-webhook-values.png)

1. Open the GitHub console at `https://github.com/user-name/repository-name/settings/hooks` and choose **Add webhook**.
   + For **Payload URL**, enter the Payload URL value you took note of earlier.
   + For **Content type**, choose **application/json**.
   + For **Secret**, enter the Secret value you took note of earlier.
   + Configure the individual events that will send a webhook payload to CodeBuild. For **Which events would you like to trigger this webhook?**, choose **Let me select individual events**, and then choose from the following events: **Pushes**, **Pull requests**, and **Releases**. If you want to start builds for `WORKFLOW_JOB_QUEUED` events, choose **Workflow jobs**. To learn more about GitHub Actions runners, see [Tutorial: Configure a CodeBuild-hosted GitHub Actions runner](action-runner.md). To learn more about event types supported by CodeBuild, see [GitHub webhook events](github-webhook.md).

1. Choose **Add webhook**.

# GitHub webhook events
<a name="github-webhook"></a>

You can use webhook filter groups to specify which GitHub webhook events trigger a build. For example, you can specify that a build is only triggered for changes to specific branches. 

You can create one or more webhook filter groups to specify which webhook events trigger a build. A build is triggered if any filter group evaluates to true, which occurs when all the filters in the group evaluate to true. When you create a filter group, you specify: 

**An event**  
For GitHub, you can choose one or more of the following events: `PUSH`, `PULL_REQUEST_CREATED`, `PULL_REQUEST_UPDATED`, `PULL_REQUEST_REOPENED`, `PULL_REQUEST_MERGED`, `PULL_REQUEST_CLOSED`, `RELEASED`, `PRERELEASED`, and `WORKFLOW_JOB_QUEUED`. The webhook event type is in the `X-GitHub-Event` header in the webhook payload. In the `X-GitHub-Event` header, you might see `pull_request` or `push`. For a pull request event, the type is in the `action` field of the webhook event payload. The following table shows how `X-GitHub-Event` header values and webhook pull request payload `action` field values map to the available event types.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/github-webhook.html)
 The `PULL_REQUEST_REOPENED` event type can be used with GitHub and GitHub Enterprise Server only. The `RELEASED` and `PRERELEASED` event type can be used with GitHub only. For more information on `WORKFLOW_JOB_QUEUED`, see [Tutorial: Configure a CodeBuild-hosted GitHub Actions runner](action-runner.md). 

**One or more optional filters**  
Use a regular expression to specify a filter. For an event to trigger a build, every filter within the group associated with it must evaluate to true.    
`ACTOR_ACCOUNT_ID` (`ACTOR_ID` in the console)  
A webhook event triggers a build when a GitHub or GitHub Enterprise Server account ID matches the regular expression pattern. This value is found in the `id` property of the `sender` object in the webhook payload.  
`HEAD_REF`  
A webhook event triggers a build when the head reference matches the regular expression pattern (for example, `refs/heads/branch-name` or `refs/tags/tag-name`). For a push event, the reference name is found in the `ref` property in the webhook payload. For pull requests events, the branch name is found in the `ref` property of the `head` object in the webhook payload.   
`BASE_REF`  
A webhook event triggers a build when the base reference matches the regular expression pattern (for example, `refs/heads/branch-name`). A `BASE_REF` filter can be used with pull request events only. The branch name is found in the `ref` property of the `base` object in the webhook payload.  
`FILE_PATH`  
A webhook triggers a build when the path of a changed file matches the regular expressions pattern. A `FILE_PATH` filter can be used with GitHub push and pull request events and GitHub Enterprise Server push events. It cannot be used with GitHub Enterprise Server pull request events.   
`COMMIT_MESSAGE`  
A webhook triggers a build when the head commit message matches the regular expression pattern. A `COMMIT_MESSAGE` filter can be used with GitHub push and pull request events and GitHub Enterprise Server push events. It cannot be used with GitHub Enterprise Server pull request events.  
`TAG_NAME`  
A webhook triggers a build when the tag name of the release matches the regular expression pattern. A `TAG_NAME` filter can be used with GitHub released and prereleased request events.  
`RELEASE_NAME`  
A webhook triggers a build when the release name matches the regular expression pattern. A `RELEASE_NAME` filter can be used with GitHub released and prereleased request events.  
`REPOSITORY_NAME`  
A webhook triggers a build when the repository name matches the regular expression pattern. A `REPOSITORY_NAME` filter can only be used with GitHub global or organization webhooks.  
`ORGANIZATION_NAME`  
A webhook triggers a build when the organization name matches the regular expression pattern. A `ORGANIZATION_NAME` filter can only be used with GitHub global webhooks.  
`WORKFLOW_NAME`  
A webhook triggers a build when the workflow name matches the regular expression pattern. A `WORKFLOW_NAME` filter can be used with GitHub Actions workflow job queued request events.

**Note**  
You can find the webhook payload in the webhook settings of your GitHub repository. 

**Topics**
+ [

# Filter GitHub webhook events (console)
](github-webhook-events-console.md)
+ [

# Filter GitHub webhook events (SDK)
](github-webhook-events-sdk.md)
+ [

# Filter GitHub webhook events (CloudFormation)
](github-webhook-events-cfn.md)

# Filter GitHub webhook events (console)
<a name="github-webhook-events-console"></a>

Use the following instructions to filter GitHub webhook events using the AWS Management Console. For more information about GitHub webhook events, see [GitHub webhook events](github-webhook.md).

In **Primary source webhook events**, select the following. This section is only available when you chose **Repository in my GitHub account** for the source repository.

1. Select **Rebuild every time a code change is pushed to this repository** when you create your project. 

1. From **Event type**, choose one or more events. 

1. To filter when an event triggers a build, under **Start a build under these conditions**, add one or more optional filters. 

1. To filter when an event is not triggered, under **Don't start a build under these conditions**, add one or more optional filters. 

1. Choose **Add filter group** to add another filter group, if needed. 

 For more information, see [Create a build project (console)](create-project.md#create-project-console) and [WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html) in the *AWS CodeBuild API Reference*. 

In this example, a webhook filter group triggers a build for pull requests only:

![\[A webhook filter group that triggers a build for pull requests only.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter.png)


Using an example of two webhook filter groups, a build is triggered when one or both evaluate to true:
+ The first filter group specifies pull requests that are created, updated, or reopened on branches with Git reference names that match the regular expression `^refs/heads/main$` and head references that match `^refs/heads/branch1$`. 
+ The second filter group specifies push requests on branches with Git reference names that match the regular expression `^refs/heads/branch1$`. 

![\[An example of two filter groups.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-head-base-regexes.png)


In this example, a webhook filter group triggers a build for all requests except tag events. 

![\[A webhook filter group that triggers a build for all requests except tag events.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-exclude.png)


In this example, a webhook filter group triggers a build only when files with names that match the regular expression `^buildspec.*` change. 

![\[A webhook filter group that triggers a build only when files with names that match the regular expression specified.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-file-name-regex.png)


In this example, a webhook filter group triggers a build only when files are changed in `src` or `test` folders.

![\[A webhook filter group that triggers a build only when files are changed in specified folders.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-file-name-combined-regex.png)


In this example, a webhook filter group triggers a build only when a change is made by a specified GitHub or GitHub Enterprise Server user with an account ID that matches the regular expression `actor-account-id`. 

**Note**  
 For information about how to find your GitHub account ID, see https://api.github.com/users/*user-name*, where *user-name* is your GitHub user name. 

![\[A webhook filter group that triggers a build only when a change is made by a specified GitHub user with an account ID that matches the regular expression.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-actor.png)


In this example, a webhook filter group triggers a build for a push event when the head commit message matches the regular expression `\[CodeBuild\]`. 

![\[A webhook filter group that triggers a build for a push event when the head commit message matches the regular expression.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-commit-message.png)


In this example, a webhook filter group triggers a build for GitHub Actions workflow job events only.

**Note**  
CodeBuild will only process GitHub Actions workflow jobs if a webhook has filter groups containing the **WORKFLOW\$1JOB\$1QUEUED** event filter.

![\[A webhook filter group triggers a build for GitHub Actions workflow job events only.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-actions-workflow-job-queued-no-highlight.png)


In this example, a webhook filter group triggers a build for a workflow name that matches the regular expression `CI-CodeBuild`. 

![\[A webhook filter group triggers a build for a workflow name that matches the regular expression.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-actions-workflow-job-specific.png)


# Filter GitHub webhook events (SDK)
<a name="github-webhook-events-sdk"></a>

To use the AWS CodeBuild SDK to filter webhook events, use the `filterGroups` field in the request syntax of the `CreateWebhook` or `UpdateWebhook` API methods. For more information, see [WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html) in the *CodeBuild API Reference*. 

For more information about GitHub webhook events, see [GitHub webhook events](github-webhook.md).

 To create a webhook filter that triggers a build for pull requests only, insert the following into the request syntax: 

```
"filterGroups": [
   [
        {
            "type": "EVENT", 
            "pattern": "PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED, PULL_REQUEST_MERGED, PULL_REQUEST_CLOSED"
        }
    ]
]
```

 To create a webhook filter that triggers a build for specified branches only, use the `pattern` parameter to specify a regular expression to filter branch names. Using an example of two filter groups, a build is triggered when one or both evaluate to true:
+ The first filter group specifies pull requests that are created, updated, or reopened on branches with Git reference names that match the regular expression `^refs/heads/main$` and head references that match `^refs/heads/myBranch$`. 
+ The second filter group specifies push requests on branches with Git reference names that match the regular expression `^refs/heads/myBranch$`. 

```
"filterGroups": [
    [
        {
            "type": "EVENT", 
            "pattern": "PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED"
        },
        {
            "type": "HEAD_REF", 
            "pattern": "^refs/heads/myBranch$"
        },
        {
            "type": "BASE_REF", 
            "pattern": "^refs/heads/main$"
        }
    ],
    [
        {
            "type": "EVENT", 
            "pattern": "PUSH"
        },
        {
            "type": "HEAD_REF", 
            "pattern": "^refs/heads/myBranch$"
        }
    ]
]
```

 You can use the `excludeMatchedPattern` parameter to specify which events do not trigger a build. For example, in this example a build is triggered for all requests except tag events. 

```
"filterGroups": [
    [
        {
            "type": "EVENT", 
            "pattern": "PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED, PULL_REQUEST_MERGED, PULL_REQUEST_CLOSED"
        },
        {
            "type": "HEAD_REF", 
            "pattern": "^refs/tags/.*", 
            "excludeMatchedPattern": true
        }
    ]
]
```

You can create a filter that triggers a build only when files with names that match the regular expression in the `pattern` argument change. In this example, the filter group specifies that a build is triggered only when files with a name that matches the regular expression `^buildspec.*` change. 

```
"filterGroups": [
    [
        {
            "type": "EVENT", 
            "pattern": "PUSH"
        },
        {
            "type": "FILE_PATH", 
            "pattern": "^buildspec.*"
        }
    ]
]
```

In this example, the filter group specifies that a build is triggered only when files are changed in `src` or `test` folders.

```
"filterGroups": [
    [
        {
            "type": "EVENT", 
            "pattern": "PUSH"
        },
        {
            "type": "FILE_PATH", 
            "pattern": "^src/.+|^test/.+"
        }
    ]
]
```

You can create a filter that triggers a build only when a change is made by a specified GitHub or GitHub Enterprise Server user with account ID `actor-account-id`. 

**Note**  
 For information about how to find your GitHub account ID, see https://api.github.com/users/*user-name*, where *user-name* is your GitHub user name. 

```
"filterGroups": [
    [
        {
            "type": "EVENT", 
            "pattern": "PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_REOPENED, PULL_REQUEST_MERGED, PULL_REQUEST_CLOSED"
        },
        {
            "type": "ACTOR_ACCOUNT_ID", 
            "pattern": "actor-account-id"
        }
    ]
]
```

You can create a filter that triggers a build only when the head commit message matches the regular expression in the pattern argument. In this example, the filter group specifies that a build is triggered only when the head commit message of the push event matches the regular expression `\[CodeBuild\]`. 

```
"filterGroups": [
    [
        {
            "type": "EVENT",
            "pattern": "PUSH"
        },
        {
            "type": "COMMIT_MESSAGE",
            "pattern": "\[CodeBuild\]"
        }
    ]
]
```

To create a webhook filter that triggers a build for GitHub Actions workflow jobs only, insert the following into the request syntax:

```
"filterGroups": [
   [
        {
            "type": "EVENT", 
            "pattern": "WORKFLOW_JOB_QUEUED"
        }
    ]
]
```

# Filter GitHub webhook events (CloudFormation)
<a name="github-webhook-events-cfn"></a>

 To use an CloudFormation template to filter webhook events, use the AWS CodeBuild project's `FilterGroups` property.

For more information about GitHub webhook events, see [GitHub webhook events](github-webhook.md).

The following YAML-formatted portion of an CloudFormation template creates two filter groups. Together, they trigger a build when one or both evaluate to true: 
+  The first filter group specifies pull requests are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` by a GitHub user who does not have account ID `12345`. 
+  The second filter group specifies push requests are created on files with names that match the regular expression `READ_ME` in branches with Git reference names that match the regular expression `^refs/heads/.*`. 
+ The third filter group specifies a push request with a head commit message matching the regular expression `\[CodeBuild\]`.
+ The fourth filter group specifies a GitHub Actions workflow job request with a workflow name matching the regular expression `\[CI-CodeBuild\]`.

```
CodeBuildProject:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: MyProject
    ServiceRole: service-role
    Artifacts:
      Type: NO_ARTIFACTS
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/standard:5.0
    Source:
      Type: GITHUB
      Location: source-location
    Triggers:
      Webhook: true
      FilterGroups:
        - - Type: EVENT
            Pattern: PULL_REQUEST_CREATED,PULL_REQUEST_UPDATED
          - Type: BASE_REF
            Pattern: ^refs/heads/main$
            ExcludeMatchedPattern: false
          - Type: ACTOR_ACCOUNT_ID
            Pattern: 12345
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: HEAD_REF
            Pattern: ^refs/heads/.*
          - Type: FILE_PATH
            Pattern: READ_ME
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: COMMIT_MESSAGE
            Pattern: \[CodeBuild\]
          - Type: FILE_PATH
            Pattern: ^src/.+|^test/.+
        - - Type: EVENT
            Pattern: WORKFLOW_JOB_QUEUED
          - Type: WORKFLOW_NAME
            Pattern: \[CI-CodeBuild\]
```

# GitLab group webhooks
<a name="gitlab-group-webhook"></a>

You can use CodeBuild GitLab group webhooks to start builds on webhook events from any repository within a GitLab group. Group webhooks work with any of the existing GitLab webhook event types, and can be configured by adding a scope configuration when creating a CodeBuild webhook. You can also use group webhooks to [set up self-hosted GitLab runners within CodeBuild](gitlab-runner.md) in order to receive `WORKFLOW_JOB_QUEUED` events from multiple repositories within a single project.

**Topics**
+ [

# Set up a group GitLab webhook
](gitlab-group-webhook-setup.md)
+ [

# Filter GitLab group webhook events (console)
](gitlab-group-webhook-events-console.md)
+ [

# Filter GitLab group webhook events (CloudFormation)
](gitlab-group-webhook-events-cfn.md)

# Set up a group GitLab webhook
<a name="gitlab-group-webhook-setup"></a>

The high-level steps to set up a group GitLab webhook are as follows. For more information about group GitLab webhooks, see [GitLab group webhooks](gitlab-group-webhook.md).

1. Set your project's source location to `CODEBUILD_DEFAULT_WEBHOOK_SOURCE_LOCATION`.

1. In the webhook's scope configuration, set the scope to `GITLAB_GROUP`.

1. Specify a name as part of the webhook's scope configuration. For group webhooks, this is the group name.
**Note**  
If the project's source type is `GITLAB_SELF_MANAGED`, you will also need to specify a domain as part of the webhook scope configuration.

1. (Optional) If you would only like to receive webhook events for specific repositories within your organization or enterprise, you can specify `REPOSITORY_NAME` as a filter when creating the webhook.

1. When creating a group webhook, ensure that CodeBuild has permissions to create group level webhooks within GitLab. To do so, you can use CodeBuild OAuth though CodeConnections. For more information, see [GitLab access in CodeBuild](access-tokens-gitlab-overview.md).

   Note that group webhooks work with any of the existing GitLab webhook event types.

# Filter GitLab group webhook events (console)
<a name="gitlab-group-webhook-events-console"></a>

When creating a GitLab project through the console, select the following options to create a GitLab group webhook within the project. For more information about group GitLab webhooks, see [GitLab group webhooks](gitlab-group-webhook.md).

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a build project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Run a build (console)](run-build-console.md).
   +  In **Source**: 
     +  For **Source provider**, choose **GitLab** or **GitLab Self Managed**.
     +  For **Repository**, choose **GitLab scoped webhook**. 

        The GitLab repository will automatically be set to `CODEBUILD_DEFAULT_WEBHOOK_SOURCE_LOCATION`, which is the required source location for group webhooks. 
**Note**  
When using group webhooks, make sure that CodeBuild has permissions to create group level webhooks within GitLab. If you're using an [existing OAuth connection](access-tokens-gitlab-overview.md#connections-gitlab), you may need to regenerate the connection in order to grant CodeBuild this permission.  
![\[The configuration of GitLab scoped webhook.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/gitlab-group-source.png)
   +  In **Primary source webhook events**: 
     +  For **Group name**, enter the group name.

       If the project's source type is `GITLAB_SELF_MANAGED`, you also need to specify a domain as part of the webhook group configuration. For example, if the URL of your group is **https://domain.com/group/group-name**, then the domain is **https://domain.com**.
**Note**  
 This name cannot be changed after the webhook has been created. To change the name, you can delete and re-create the webhook. If you want to remove the webhook entirely, you can also update the project source location to a GitLab repository.   
![\[The configuration of group webhooks.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/gitlab-group-webhook-primary-events.png)
     +  (Optional) In **Webhook event filter groups**, you can specify which [events you would like to trigger a new build](gitlab-webhook.md). You can also specify `REPOSITORY_NAME` as a filter to only trigger builds on webhook events from specific repositories.  
![\[A filter that only triggers builds on webhook events from specific repositories.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-organization-webhook-filter-groups.png)

       You can also set the event type to `WORKFLOW_JOB_QUEUED` to set up self-hosted GitLab runners. For more information, see [Self-managed GitLab runners in AWS CodeBuild](gitlab-runner.md).

1. Continue with the default values and then choose **Create build project**.

# Filter GitLab group webhook events (CloudFormation)
<a name="gitlab-group-webhook-events-cfn"></a>

 To use an CloudFormation template to filter group webhook events, use the AWS CodeBuild project's `ScopeConfiguration` property. For more information about group GitLab webhooks, see [GitLab group webhooks](gitlab-group-webhook.md).

 The following YAML-formatted portion of an CloudFormation template creates four filter groups. Together, they trigger a build when one or all evaluate to true: 
+  The first filter group specifies pull requests are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` by a GitLab user who does not have account ID `12345`. 
+  The second filter group specifies push requests are created on files with names that match the regular expression `READ_ME` in branches with Git reference names that match the regular expression `^refs/heads/.*`. 
+ The third filter group specifies a push request with a head commit message matching the regular expression `\[CodeBuild\]`.
+ The fourth filter group specifies a GitLab CI/CD pipeline job request with a CI/CD pipeline name matching the regular expression `\[CI-CodeBuild\]`.

```
CodeBuildProject:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: MyProject
    ServiceRole: service-role
    Artifacts:
      Type: NO_ARTIFACTS
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/standard:5.0
    Source:
      Type: GITLAB
      Location: source-location
    Triggers:
      Webhook: true
      ScopeConfiguration:
        Name: group-name
        Scope: GITLAB_GROUP
      FilterGroups:
        - - Type: EVENT
            Pattern: PULL_REQUEST_CREATED,PULL_REQUEST_UPDATED
          - Type: BASE_REF
            Pattern: ^refs/heads/main$
            ExcludeMatchedPattern: false
          - Type: ACTOR_ACCOUNT_ID
            Pattern: 12345
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: HEAD_REF
            Pattern: ^refs/heads/.*
          - Type: FILE_PATH
            Pattern: READ_ME
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: COMMIT_MESSAGE
            Pattern: \[CodeBuild\]
          - Type: FILE_PATH
            Pattern: ^src/.+|^test/.+
        - - Type: EVENT
            Pattern: WORKFLOW_JOB_QUEUED
          - Type: WORKFLOW_NAME
            Pattern: \[CI-CodeBuild\]
```

# GitLab manual webhooks
<a name="gitlab-manual-webhook"></a>

You can configure manual GitLab webhooks to prevent CodeBuild from automatically attempting to create a webhook within GitLab. CodeBuild returns a payload URL in as part of the call to create the webhook and can be used to manually create the webhook within GitLab. Even if CodeBuild is not allowlisted to create a webhook in your GitLab account, you can still manually create a webhook for your build project.

Use the following procedure to create a GitLab manual webhook.

**To create a GitLab manual webhook**

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a build project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Run a build (console)](run-build-console.md).
   +  In **Source**: 
     +  For **Source provider**, choose **GitLab**.
     +  For **Repository**, choose **Repository in my GitLab account**. 
     +  For **Repository URL**, enter **https://gitlab.com/*user-name*/*repository-name***. 
   +  In **Primary source webhook events**: 
     +  For **Webhook - optional**, choose **Rebuild every time a code change is pushed to this repository**.
     +  Choose **Additional configuration** and for **Manual creation - optional**, choose **Manually create a webhook for this repository in GitLab console.**.

1. Continue with the default values and then choose **Create build project**. Take note of the **Payload URL** and **Secret** values as you will use these later.

1. Open the GitLab console at `https://gitlab.com/user-name/repository-name/-/hooks` and choose **Add new webhook**.
   + For **URL**, enter the Payload URL value you took note of earlier.
   + For **Secret token**, enter the Secret value you took note of earlier.
   + Configure the individual events that will send a webhook payload to CodeBuild. For **Trigger**, choose from the following events: **Push events**, **Merge request events**, **Releases events**, and **Job events**. To learn more about event types supported by CodeBuild, see [GitLab webhook events](gitlab-webhook.md).

1. Choose **Add webhook**.

# GitLab webhook events
<a name="gitlab-webhook"></a>

You can use webhook filter groups to specify which GitLab webhook events trigger a build. For example, you can specify that a build is only triggered for changes to specific branches. 

You can create one or more webhook filter groups to specify which webhook events trigger a build. A build is triggered if any filter group evaluates to true, which occurs when all the filters in the group evaluate to true. When you create a filter group, you specify: 

**An event**  
For GitLab, you can choose one or more of the following events: `PUSH`, `PULL_REQUEST_CREATED`, `PULL_REQUEST_UPDATED`, `PULL_REQUEST_MERGED`, `PULL_REQUEST_REOPENED`, `PULL_REQUEST_CLOSED`, `RELEASED`, and `WORKFLOW_JOB_QUEUED`.  
The webhook's event type is in its header in the `X-GitLab-Event` field. The following table shows how `X-GitLab-Event` header values map to the event types. For the `Merge Request Hook` webhook event, the payload's `object_atttributes.action` will contain additional information on merge request type.      
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/codebuild/latest/userguide/gitlab-webhook.html)
For `PULL_REQUEST_MERGED`, if a pull request is merged with the squash strategy and the pull request branch is closed, the original pull request commit no longer exists. In this case, the `CODEBUILD_WEBHOOK_MERGE_COMMIT` environment variable contains the identifier of the squashed merge commit.

**One or more optional filters**  
Use a regular expression to specify a filter. For an event to trigger a build, every filter within the group associated with it must evaluate to true.    
`ACTOR_ACCOUNT_ID` (`ACTOR_ID` in the console)  
A webhook event triggers a build when a GitLab account ID matches the regular expression pattern. This value appears in the `account_id` property of the `actor` object in the webhook filter payload.  
`HEAD_REF`  
A webhook event triggers a build when the head reference matches the regular expression pattern (for example, `refs/heads/branch-name` and `refs/tags/tag-name`). A `HEAD_REF` filter evaluates the Git reference name for the branch or tag. The branch or tag name appears in the `name` field of the `new` object in the `push` object of the webhook payload. For pull request events, the branch name appears in the `name` field in the `branch` object of the `source` object in the webhook payload.  
`BASE_REF`  
A webhook event triggers a build when the base reference matches the regular expression pattern. A `BASE_REF` filter works with pull request events only (for example, `refs/heads/branch-name`). A `BASE_REF` filter evaluates the Git reference name for the branch. The branch name appears in the `name` field of the `branch` object in the `destination` object in the webhook payload.  
`FILE_PATH`  
A webhook triggers a build when the path of a changed file matches the regular expression pattern.  
`COMMIT_MESSAGE`  
A webhook triggers a build when the head commit message matches the regular expression pattern.  
`WORKFLOW_NAME`  
A webhook triggers a build when the workflow name matches the regular expression pattern.

**Note**  
You can find the webhook payload in the webhook settings of your GitLab repository. 

**Topics**
+ [

# Filter GitLab webhook events (console)
](gitlab-webhook-events-console.md)
+ [

# Filter GitLab webhook events (SDK)
](gitlab-webhook-events-sdk.md)
+ [

# Filter GitLab webhook events (CloudFormation)
](gitlab-webhook-events-cfn.md)

# Filter GitLab webhook events (console)
<a name="gitlab-webhook-events-console"></a>

Use the following instructions to use the AWS Management Console to filter webhook events. For more information about GitLab webhook events, see [GitLab webhook events](gitlab-webhook.md).

1.  Select **Rebuild every time a code change is pushed to this repository** when you create your project. 

1.  From **Event type**, choose one or more events. 

1.  To filter when an event triggers a build, under **Start a build under these conditions**, add one or more optional filters. 

1.  To filter when an event is not triggered, under **Don't start a build under these conditions**, add one or more optional filters. 

1.  Choose **Add filter group** to add another filter group. 

 For more information, see [Create a build project (console)](create-project.md#create-project-console) and [WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html) in the *AWS CodeBuild API Reference*. 

In this example, a webhook filter group triggers a build for pull requests only:

![\[A webhook filter group that triggers a build for pull requests only.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-gitlab.png)


Using an example of two filter groups, a build is triggered when one or both evaluate to true:
+ The first filter group specifies pull requests that are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` and head references that match `^refs/heads/branch1!`. 
+ The second filter group specifies push requests on branches with Git reference names that match the regular expression `^refs/heads/branch1$`. 

![\[An example of two filter groups.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-head-base-regexes-gitlab.png)


In this example, a webhook filter group triggers a build for all requests except tag events. 

![\[A webhook filter group that triggers a build for all requests except tag events.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-exclude-gitlab.png)


In this example, a webhook filter group triggers a build only when files with names that match the regular expression `^buildspec.*` change. 

![\[A webhook filter group that triggers a build only when files with names that match the regular expression specified.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-file-name-regex-gitlab.png)


In this example, a webhook filter group triggers a build only when files are changed in `src` or `test` folders.

![\[A webhook filter group that triggers a build only when files are changed in specified folders.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-file-name-combined-regex-gitlab.png)


In this example, a webhook filter group triggers a build only when a change is made by a GitLab user who does not have an account ID that matches the regular expression `actor-account-id`. 

**Note**  
 For information about how to find your GitLab account ID, see https://api.github.com/users/*user-name*, where *user-name* is your GitLab user name. 

![\[A webhook filter group that triggers a build only when a change is made by a GitLab user who does not have an account ID.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-actor-gitlab.png)


In this example, a webhook filter group triggers a build for a push event when the head commit message matches the regular expression `\[CodeBuild\]`. 

![\[A webhook filter group that triggers a build for a push event when the head commit message matches the regular expression.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-webhook-filter-commit-message-gitlab.png)


# Filter GitLab webhook events (SDK)
<a name="gitlab-webhook-events-sdk"></a>

 To use the AWS CodeBuild SDK to filter webhook events, use the `filterGroups` field in the request syntax of the `CreateWebhook` or `UpdateWebhook` API methods. For more information, see [WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html) in the *CodeBuild API Reference*. 

For more information about GitLab webhook events, see [GitLab webhook events](gitlab-webhook.md).

 To create a webhook filter that triggers a build for pull requests only, insert the following into the request syntax: 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_MERGED"
    }
  ]
]
```

 To create a webhook filter that triggers a build for specified branches only, use the `pattern` parameter to specify a regular expression to filter branch names. Using an example of two filter groups, a build is triggered when one or both evaluate to true:
+ The first filter group specifies pull requests that are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` and head references that match `^refs/heads/myBranch$`. 
+ The second filter group specifies push requests on branches with Git reference names that match the regular expression `^refs/heads/myBranch$`. 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED"
    },
    {
      "type": "HEAD_REF",
      "pattern": "^refs/heads/myBranch$"
    },
    {
      "type": "BASE_REF",
      "pattern": "^refs/heads/main$"
    }
  ],
  [
    {
      "type": "EVENT",
      "pattern": "PUSH"
    },
    {
      "type": "HEAD_REF",
      "pattern": "^refs/heads/myBranch$"
    }
  ]
]
```

 You can use the `excludeMatchedPattern` parameter to specify which events do not trigger a build. In this example, a build is triggered for all requests except tag events. 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_MERGED"
    },
    {
      "type": "HEAD_REF",
      "pattern": "^refs/tags/.*",
      "excludeMatchedPattern": true
    }
  ]
]
```

You can create a filter that triggers a build only when a change is made by a GitLab user with account ID `actor-account-id`. 

**Note**  
 For information about how to find your GitLab account ID, see https://api.github.com/users/*user-name*, where *user-name* is your GitLab user name. 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PUSH, PULL_REQUEST_CREATED, PULL_REQUEST_UPDATED, PULL_REQUEST_MERGED"
    },
    {
      "type": "ACTOR_ACCOUNT_ID",
      "pattern": "actor-account-id"
    }
  ]
]
```

You can create a filter that triggers a build only when files with names that match the regular expression in the `pattern` argument change. In this example, the filter group specifies that a build is triggered only when files with a name that matches the regular expression `^buildspec.*` change. 

```
"filterGroups": [
  [
    {
      "type": "EVENT",
      "pattern": "PUSH"
    },
    {
      "type": "FILE_PATH",
      "pattern": "^buildspec.*"
    }
  ]
]
```

In this example, the filter group specifies that a build is triggered only when files are changed in `src` or `test` folders.

```
"filterGroups": [
    [
        {
            "type": "EVENT", 
            "pattern": "PUSH"
        },
        {
            "type": "FILE_PATH", 
            "pattern": "^src/.+|^test/.+"
        }
    ]
]
```

You can create a filter that triggers a build only when the head commit message matches the regular expression in the pattern argument. In this example, the filter group specifies that a build is triggered only when the head commit message of the push event matches the regular expression `\[CodeBuild\]`. 

```
  "filterGroups": [
    [
      {
        "type": "EVENT",
        "pattern": "PUSH"
      },
      {
        "type": "COMMIT_MESSAGE",
        "pattern": "\[CodeBuild\]"
      }
    ]
  ]
```

# Filter GitLab webhook events (CloudFormation)
<a name="gitlab-webhook-events-cfn"></a>

 To use an CloudFormation template to filter webhook events, use the AWS CodeBuild project's `FilterGroups` property. For more information about GitLab webhook events, see [GitLab webhook events](gitlab-webhook.md).

The following YAML-formatted portion of an CloudFormation template creates two filter groups. Together, they trigger a build when one or both evaluate to true: 
+  The first filter group specifies pull requests are created or updated on branches with Git reference names that match the regular expression `^refs/heads/main$` by a GitLab user who does not have account ID `12345`. 
+  The second filter group specifies push requests are created on branches with Git reference names that match the regular expression `^refs/heads/.*`. 
+ The third filter group specifies a push request with a head commit message matching the regular expression `\[CodeBuild\]`.
+ The fourth filter group specifies a GitHub Actions workflow job request with a workflow name matching the regular expression `\[CI-CodeBuild\]`.

```
CodeBuildProject:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: MyProject
    ServiceRole: service-role
    Artifacts:
      Type: NO_ARTIFACTS
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/standard:5.0
    Source:
      Type: GITLAB
      Location: source-location
    Triggers:
      Webhook: true
      FilterGroups:
        - - Type: EVENT
            Pattern: PULL_REQUEST_CREATED,PULL_REQUEST_UPDATED
          - Type: BASE_REF
            Pattern: ^refs/heads/main$
            ExcludeMatchedPattern: false
          - Type: ACTOR_ACCOUNT_ID
            Pattern: 12345
            ExcludeMatchedPattern: true
        - - Type: EVENT
            Pattern: PUSH
          - Type: HEAD_REF
            Pattern: ^refs/heads/.*
        - - Type: EVENT
            Pattern: PUSH
          - Type: COMMIT_MESSAGE
            Pattern: \[CodeBuild\]
        - - Type: EVENT
            Pattern: WORKFLOW_JOB_QUEUED
          - Type: WORKFLOW_NAME
            Pattern: \[CI-CodeBuild\]
```

# Buildkite manual webhooks
<a name="buildkite-manual-webhook"></a>

Currently, CodeBuild requires all Buildkite webhooks to be created manually. CodeBuild returns a payload URL as part of the call to create the webhook, which can be used to manually create the webhook within Buildkite.

Use the following procedure to create a Buildkite manual webhook.

**To create a CodeBuild project with a webhook**

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. Create a build project. For information, see [Create a build project (console)](create-project.md#create-project-console) and [Run a build (console)](run-build-console.md).

1. In **Project configuration**, choose **Runner project**.

   In **Runner**:
   + For **Runner provider**, choose **Buildkite**.
   + For **Buildkite agent token**, choose **Create a new agent token by using the create secret page**. You will be prompted to create a new secret in AWS Secrets Manager with a secret value equal to the Buildkite agent token you generated above.
   + (Optional) If you would like to use CodeBuild managed credentials for your job, select your job’s source repository provider under **Buildkite source credential options** and verify that credentials are configured for your account. Additionally, verify that your Buildkite pipeline uses **Checkout using HTTPS**.

1. 
   +  In **Environment**: 
     + Choose a supported **Environment image** and **Compute**. Note that you have the option to override the image and instance settings by using a label in your GitHub Actions workflow YAML. For more information, see [Step 2: Update your GitHub Actions workflow YAML](action-runner.md#sample-github-action-runners-update-yaml)
   +  In **Buildspec**: 
     + Note that your buildspec will be ignored unless `buildspec-override:true` is added as a label. Instead, CodeBuild will override it to use commands that will setup the self-hosted runner.

1. Continue with the default values and then choose **Create build project**.

1. Save the **Payload URL** and **Secret** values from the **Create Webhook** popup. Follow the instructions in the popup to create a new Buildkite organization webhook.

# Pull request comment approval
<a name="pull-request-build-policy"></a>

CodeBuild supports pull request build policies that provide additional control over builds triggered by pull requests. You may not want to automatically build pull requests from unknown users until their changes can be reviewed. This feature allows you to require one of your team members to first review the code and then run the pipeline. This is commonly used as a security measure when building a code submitted by unknown contributors.

Pull request build policies allow you to control when CodeBuild triggers builds for pull requests based on the contributor's permissions and approval status. This is particularly important for public repositories or repositories that accept contributions from external collaborators.

When enabled, this feature ensures that builds are only triggered for pull requests when either:
+ The pull request is created by a trusted contributor.
+ A trusted contributor approves the pull request by posting a specific comment.

## How it works
<a name="pull-request-build-policy.how-it-works"></a>

**Trusted contributors**  
Trusted contributor is a user who’s current role in the source control system is set in the pull request based policy as an approver roles. When a trusted contributor creates a pull request, CodeBuild triggers the build automatically, maintaining the current behavior.

**Untrusted contributors**  
Untrusted contributor is a user who’s role is not set in the list of the approver roles. When an untrusted contribute creates a pull request:  

1. CodeBuild marks the build status as “Failed" with the message "Pull request approval required for starting a build".

1. A trusted contributor must review the changes and post a comment with `/codebuild_run(<SHA_OF_THE_LATEST_COMMIT>)` to trigger the build. For example, `/codebuild_run(046e8b67481d53bdc86c3f6affdd5d1afae6d369)`.

1. CodeBuild validates the commenter's permissions and triggers the build if approved.

1. Build results are reported back on the pull request page.

**Comment approval syntax**  
Trusted contributors can approve builds using the following comment formats:  
+ `/codebuild_run(046e8b67481d53bdc86c3f6affdd5d1afae6d369)` - Triggers build on the specified commit SHA.

## Configuration
<a name="pull-request-build-policy.configuration"></a>

**Default behavior**  
Pull request build policy is enabled by default for all newly created CodeBuild projects.

**API parameters**  
The pull request build policy is configured using the `PullRequestBuildPolicy` parameter in the following actions:  
+ `CreateWebhook`
+ `UpdateWebhook`

**`PullRequestBuildPolicy` structure**  

```
{
    "requiresCommentApproval": "string",
    "approverRoles": ["string", ...]
}
```

**`requiresCommentApproval`**  
Specifies when comment-based approval is required before triggering a build on pull requests. This setting determines whether builds run automatically or require explicit approval through comments.  
Type: String  
Valid values:  
+ `DISABLED` - Builds trigger automatically without requiring comment approval.
+ `FORK_PULL_REQUESTS` - Only pull requests from forked repositories require comment approval (unless contributor is one of the approver roles).
+ `ALL_PULL_REQUESTS` - All pull requests require comment approval before builds execute (unless contributor is one of the approver roles). This is the default value.

**`approverRoles`**  
List of repository roles that have approval privileges for pull request builds when comment approval is required. Only users with these roles can provide valid comment approvals. If a pull request contributor is one of these roles, their pull request builds will trigger automatically.   
Type: Array of strings  
Valid values for GitHub projects (the values are mapped to the GitHub roles):  
+ `GITHUB_ADMIN` - Repository administrators
+ `GITHUB_MAINTAIN` - Repository maintainers
+ `GITHUB_WRITE` - User with write permissions
+ `GITHUB_TRIAGE` - User with triage permissions
+ `GITHUB_READ` - User with read permissions
+ Default: `["GITHUB_ADMIN", "GITHUB_MAINTAINER", "GITHUB_WRITE"]`
Valid values for GitLab projects (the values are mapped to the GitLab roles):  
+ `GITLAB_OWNER` - Repository owner
+ `GITLAB_MAINTAINER` - Repository maintainer
+ `GITLAB_DEVELOPER` - User with developer permissions
+ `GITLAB_REPORTER` - User with reporter permissions
+ `GITLAB_PLANNER` - User with planner permissions
+ `GITLAB_GUEST ` - User with guest permissions
+ Default: `["GITLAB_OWNER", "GITLAB_MAINTAINER", "GITLAB_DEVELOPER"]`
Valid values for Bitbucket projects (the values are mapped to the Bitbucket roles):  
+ `BITBUCKET_ADMIN ` - Repository administrator
+ `BITBUCKET_WRITE` - User with write permissions
+ `BITBUCKET_READ ` - User with read permissions
+ Default: `["BITBUCKET_ADMIN", "BITBUCKET_WRITE"]`

## Examples
<a name="pull-request-build-policy.examples"></a>

**Enable comment approval for all pull requests**  
To use the AWS CodeBuild SDK to enable or disable Pull Request Build policy for a webhook, use the `pullRequestBuildPolicy` field in the request syntax of the `CreateWebhook` or `UpdateWebhook` API methods. For more information, see [WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html) in the *CodeBuild API Reference*.  
Users with Github roles Admin, Maintain, and Write will be treated as trusted contributors.  

```
"pullRequestBuildPolicy": {
    "requiresCommentApproval": "ALL_PULL_REQUESTS",
    "approverRoles": ["GITHUB_ADMIN", "GITHUB_MAINTAIN", "GITHUB_WRITE"]
}
```

**Enable comment approval only for repository admins and maintainers**  
Users with GitHub roles Admin, Maintain, will be treated as trusted contributors.  

```
"pullRequestBuildPolicy": {
    "requiresCommentApproval": "FORK_PULL_REQUESTS",
    "approverRoles": ["GITHUB_ADMIN", "GITHUB_MAINTAINER"]
}
```

**Disable comment approval**  

```
"pullRequestBuildPolicy": { 
    "requiresCommentApproval": "DISABLED"
}
```

## AWS CloudFormation
<a name="pull-request-build-policy.cloudformation"></a>

To use an AWS CloudFormation template to enable or disable Pull Request Build policy for a webhook use PullRequestBuildPolicy property. The following YAML-formatted portion of an AWS CloudFormation template create a project with a webhook that has Pull Request Build Policy enabled for all pull requests. Maintain and Admin roles as specified as approvers.

```
CodeBuildProject:
  Type: AWS::CodeBuild::Project
  Properties:
    Name: MyProject
    ServiceRole: service-role
    Artifacts:
      Type: NO_ARTIFACTS
    Environment:
      Type: LINUX_CONTAINER
      ComputeType: BUILD_GENERAL1_SMALL
      Image: aws/codebuild/standard:5.0
    Source:
      Type: BITBUCKET
      Location: source-location
    Triggers:
      Webhook: true
      FilterGroups:
        - - Type: EVENT
            Pattern: PULL_REQUEST_CREATED,PULL_REQUEST_UPDATED
          - Type: BASE_REF
            Pattern: ^refs/heads/main$
            ExcludeMatchedPattern: false
      PullRequestBuildPolicy:
        RequiresCommentApproval: ALL_PULL_REQUESTS
        ApproverRoles:
          - GITHUB_MAINTAIN
          - GITHUB_ADMIN
```

## Console configuration
<a name="pull-request-build-policy.console"></a>

To use the AWS Management Console to filter webhook events:

1. For **Comment approval**, select either disabled or enabled for all pull requests (`ALL_PULL_REQUEST`) or only for pull requests from forks (`FORK_PULL_REQUEST`).

1. For **Approver roles**, select repository roles that have approval privileges for pull request builds when comment approval is required.

For more information, see [Create a build project (console)](create-project.md#create-project-console) and [WebhookFilter](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_WebhookFilter.html) in the *CodeBuild API Reference*.

![\[Primary source webhook events console with comment approval.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/pull-request-comment-approval.png)


# View a build project's details in AWS CodeBuild
<a name="view-project-details"></a>

You can use the AWS CodeBuild console, AWS CLI, or AWS SDKs to view the details of a build project in CodeBuild.

**Topics**
+ [

## View a build project's details (console)
](#view-project-details-console)
+ [

## View a build project's details (AWS CLI)
](#view-project-details-cli)
+ [

## View a build project's details (AWS SDKs)
](#view-project-details-sdks)

## View a build project's details (console)
<a name="view-project-details-console"></a>

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. In the navigation pane, choose **Build projects**.
**Note**  
By default, only the 10 most recent build projects are displayed. To view more build projects, choose the gear icon, and then choose a different value for **Projects per page** or use the back and forward arrows.

1. In the list of build projects, in the **Name** column, choose the link for the build project.

1. On the **Build project: *project-name*** page, choose **Build details**.

## View a build project's details (AWS CLI)
<a name="view-project-details-cli"></a>



Run the **batch-get-projects** command:

```
aws codebuild batch-get-projects --names names
```

In the preceding command, replace the following placeholder:
+ *names*: Required string used to indicate one or more build project names to view details about. To specify more than one build project, separate each build project's name with a space. You can specify up to 100 build project names. To get a list of build projects, see [View a list of build project names (AWS CLI)](view-project-list.md#view-project-list-cli).

For example, if you run this command:

```
aws codebuild batch-get-projects --names codebuild-demo-project codebuild-demo-project2 my-other-demo-project
```

A result similar to the following might appear in the output. Ellipses (`...`) are used to represent data omitted for brevity.

```
{
  "projectsNotFound": [
    "my-other-demo-project"
  ],
  "projects": [
    {
      ...
      "name": codebuild-demo-project,
      ...
    },
    {
      ...
      "name": codebuild-demo-project2",
      ...
    }
  ]
}
```

In the preceding output, the `projectsNotFound` array lists any build project names that were specified, but not found. The `projects` array lists details for each build project where information was found. Build project details have been omitted from the preceding output for brevity. For more information, see the output of [Create a build project (AWS CLI)](create-project.md#create-project-cli).

The **batch-get-projects** command does not support filtering for certain property values, but you can write a script that enumerates the properties for a project. For example, the following Linux shell script enumerates the projects in the current region for the current account, and prints the image used by each project.

```
#!/usr/bin/sh

# This script enumerates all of the projects for the current account 
# in the current region and prints out the image that each project is using.

imageName=""

function getImageName(){
  local environmentValues=(${1//$'\t'/ })
  imageName=${environmentValues[1]}
}

function processProjectInfo() {
  local projectInfo=$1

  while IFS=$'\t' read -r section value; do
    if [[ "$section" == *"ENVIRONMENT"* ]]; then
      getImageName "$value"
    fi
  done <<< "$projectInfo"
}

# Get the list of projects.
projectList=$(aws codebuild list-projects --output=text)

for projectName in $projectList
do
  if [[ "$projectName" != *"PROJECTS"* ]]; then
    echo "==============================================="

    # Get the detailed information for the project.
    projectInfo=$(aws codebuild batch-get-projects --output=text --names "$projectName")

    processProjectInfo "$projectInfo"

    printf 'Project "%s" has image "%s"\n' "$projectName" "$imageName"
  fi
done
```

For more information about using the AWS CLI with AWS CodeBuild, see the [Command line reference](cmd-ref.md).

## View a build project's details (AWS SDKs)
<a name="view-project-details-sdks"></a>

For more information about using AWS CodeBuild with the AWS SDKs, see the [AWS SDKs and tools reference](sdk-ref.md).

# View build project names in AWS CodeBuild
<a name="view-project-list"></a>

You can use the AWS CodeBuild console, AWS CLI, or AWS SDKs to view a list of build projects in CodeBuild.

**Topics**
+ [

## View a list of build project names (console)
](#view-project-list-console)
+ [

## View a list of build project names (AWS CLI)
](#view-project-list-cli)
+ [

## View a list of build project names (AWS SDKs)
](#view-project-list-sdks)

## View a list of build project names (console)
<a name="view-project-list-console"></a>

You can view a list of build projects in an AWS Region in the console. Information includes the name, source provider, repository, latest build status, and description, if any.

1. Open the AWS CodeBuild console at [https://console.aws.amazon.com/codesuite/codebuild/home](https://console.aws.amazon.com/codesuite/codebuild/home).

1. In the navigation pane, choose **Build projects**.
**Note**  
By default, only the 10 most recent build projects are displayed. To view more build projects, choose the gear icon, and then choose a different value for **Projects per page** or use the back and forward arrows.

## View a list of build project names (AWS CLI)
<a name="view-project-list-cli"></a>

Run the **list-projects** command:

```
aws codebuild list-projects --sort-by sort-by --sort-order sort-order --next-token next-token
```

In the preceding command, replace the following placeholders:
+ *sort-by*: Optional string used to indicate the criterion to be used to list build project names. Valid values include:
  + `CREATED_TIME`: List the build project names based on when each build project was created. 
  + `LAST_MODIFIED_TIME`: List the build project names based on when information about each build project was last changed. 
  + `NAME`: List the build project names based on each build project's name.
+ *sort-order*: Optional string used to indicate the order in which to list build projects, based on *sort-by*. Valid values include `ASCENDING` and `DESCENDING`.
+ *next-token*: Optional string. During a previous run, if there were more than 100 items in the list, only the first 100 items are returned, along with a unique string called *next token*. To get the next batch of items in the list, run this command again, adding the next token to the call. To get all of the items in the list, keep running this command with each subsequent next token, until no more next tokens are returned.

For example, if you run this command:

```
aws codebuild list-projects --sort-by NAME --sort-order ASCENDING
```

A result similar to the following might appear in the output:

```
{
  "nextToken": "Ci33ACF6...The full token has been omitted for brevity...U+AkMx8=",
  "projects": [
    "codebuild-demo-project",
    "codebuild-demo-project2",
    ... The full list of build project names has been omitted for brevity ...
    "codebuild-demo-project99"
  ]
}
```

If you run this command again:

```
aws codebuild list-projects  --sort-by NAME --sort-order ASCENDING --next-token Ci33ACF6...The full token has been omitted for brevity...U+AkMx8=
```

A result similar to the following might appear in the output:

```
{
  "projects": [
    "codebuild-demo-project100",
    "codebuild-demo-project101",
    ... The full list of build project names has been omitted for brevity ...
    "codebuild-demo-project122"
  ]
}
```

## View a list of build project names (AWS SDKs)
<a name="view-project-list-sdks"></a>

For more information about using AWS CodeBuild with the AWS SDKs, see the [AWS SDKs and tools reference](sdk-ref.md).