

# Third-party source repository samples for CodeBuild
<a name="sample-third-party-source"></a>

This section describes sample integrations between third-party source repositories and CodeBuild.


| Sample | Description | 
| --- | --- | 
|  BitBucket pull request and webhook filter sample – see [Run the 'Bitbucket pull request and webhook filter' sample for CodeBuild](sample-bitbucket-pull-request.md)  |  This sample shows you how to create a pull request using a Bitbucket repository. It also shows you how to use a Bitbucket webhook to trigger CodeBuild to create a build of a project.  | 
|  GitHub Enterprise Server sample – see [Run the GitHub Enterprise Server sample for CodeBuild](sample-github-enterprise.md)  |  This sample shows you how to set up your CodeBuild projects when your GitHub Enterprise Server repository has a certificate installed. It also shows how to enable webhooks so that CodeBuild rebuilds the source code every time a code change is pushed to your GitHub Enterprise Server repository.  | 
|  GitHub pull request and webhook filter sample – see [Run the GitHub pull request and webhook filter sample for CodeBuild](sample-github-pull-request.md)  |  This sample shows you how to create a pull request using a GitHub Enterprise Server repository. It also shows how to enable webhooks so that CodeBuild rebuilds the source code every time a code change is pushed to your GitHub Enterprise Server repository.  | 

# Run the 'Bitbucket pull request and webhook filter' sample for CodeBuild
<a name="sample-bitbucket-pull-request"></a>

AWS CodeBuild supports webhooks when the source repository is Bitbucket. This means that for a CodeBuild build project that has its source code stored in a Bitbucket repository, webhooks can be used to rebuild the source code every time a code change is pushed to the repository. For more information, see [Bitbucket webhook events](bitbucket-webhook.md). 

This sample shows you how to create a pull request using a Bitbucket repository. It also shows you how to use a Bitbucket webhook to trigger CodeBuild to create a build of a project.

**Note**  
When using webhooks, it is possible for a user to trigger an unexpected build. To mitigate this risk, see [Best practices for using webhooks](webhooks.md#webhook-best-practices).

**Topics**
+ [Prerequisites](#sample-bitbucket-pull-request-prerequisites)
+ [Step 1: Create a build project with Bitbucket and enable webhooks](#sample-bitbucket-pull-request-create)
+ [Step 2: Trigger a build with a Bitbucket webhook](#sample-bitbucket-pull-request-trigger)

## Prerequisites
<a name="sample-bitbucket-pull-request-prerequisites"></a>

 To run this sample you must connect your AWS CodeBuild project with your Bitbucket account. 

**Note**  
 CodeBuild has updated its permissions with Bitbucket. If you previously connected your project to Bitbucket and now receive a Bitbucket connection error, you must reconnect to grant CodeBuild permission to manage your webhooks. 

## Step 1: Create a build project with Bitbucket and enable webhooks
<a name="sample-bitbucket-pull-request-create"></a>

 The following steps describe how to create an AWS CodeBuild project with Bitbucket as a source repository and enable webhooks. 

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

1.  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**. 

1. Choose **Create build project**. 

1. In **Project configuration**:  
**Project name**  
Enter a name for this build project. Build project names must be unique across each AWS account. You can also include an optional description of the build project to help other users understand what this project is used for.

1. In **Source**:  
**Source provider**  
Choose **Bitbucket**. Follow the instructions to connect (or reconnect) with Bitbucket and then choose **Authorize**.  
**Repository**  
Choose **Repository in my Bitbucket account**.  
If you have not previously connected to your Bitbucket account, enter your Bitbucket username and app password, and select **Save Bitbucket credentials**.  
**Bitbucket repository**  
Enter the URL for your Bitbucket repository.

1. In **Primary source webhook events**, select the following. 
**Note**  
The **Primary source webhook events** section is only visible if you chose **Repository in my Bitbucket account** in the previous step.

   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 about Bitbucket webhook event types and filters, see [Bitbucket webhook events](bitbucket-webhook.md).

1. In **Environment**:  
**Environment image**  
Choose 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*.  
**Service role**  
Choose 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 or update 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.

1. In **Buildspec**, do one of the following:
   + Choose **Use a buildspec file** to use the buildspec.yml file in the source code root directory.
   + Choose **Insert build commands** to use the console to insert build commands.

   For more information, see the [Buildspec reference](build-spec-ref.md).

1. In **Artifacts**:  
**Type**  
Choose one of the following:  
   + If you do not want to create build output artifacts, choose **No artifacts**.
   + 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. By default, the artifact name is the project name. If you want to use a different name, enter it in the artifacts name box. If you want to output a ZIP file, include the zip extension.
     + For **Bucket name**, choose the name of the output bucket.
     + If you chose **Insert build commands** earlier in this procedure, 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).  
**Additional configuration**  
Expand **Additional configuration** and set options as appropriate.

1. Choose **Create build project**. On the **Review** page, choose **Start build** to run the build.

## Step 2: Trigger a build with a Bitbucket webhook
<a name="sample-bitbucket-pull-request-trigger"></a>

For a project that uses Bitbucket webhooks, AWS CodeBuild creates a build when the Bitbucket repository detects a change in your source code. 

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

1. On the navigation pane, choose **Build projects**, and then choose a project associated with a Bitbucket repository with webhooks. For information about creating a Bitbucket webhook project, see [Step 1: Create a build project with Bitbucket and enable webhooks](#sample-bitbucket-pull-request-create). 

1. Make some changes in the code in your project's Bitbucket repository. 

1. Create a pull request on your Bitbucket repository. For more information, see [Making a pull request](https://www.atlassian.com/git/tutorials/making-a-pull-request). 

1. On the Bitbucket webhooks page, choose **View request** to see a list of recent events. 

1. Choose **View details** to see details about the response returned by CodeBuild. It might look something like this: 

   ```
   "response":"Webhook received and build started: https://us-east-1.console.aws.amazon.com/codebuild/home..."
   "statusCode":200
   ```

1. Navigate to the Bitbucket pull request page to see the status of the build. 

# Run the GitHub Enterprise Server sample for CodeBuild
<a name="sample-github-enterprise"></a>

AWS CodeBuild supports GitHub Enterprise Server as a source repository. This sample shows how to set up your CodeBuild projects when your GitHub Enterprise Server repository has a certificate installed. It also shows how to enable webhooks so that CodeBuild rebuilds the source code every time a code change is pushed to your GitHub Enterprise Server repository.

**Topics**
+ [Prerequisites](#sample-github-enterprise-prerequisites)
+ [Step 1: Create a build project with GitHub Enterprise Server and enable webhooks](#sample-github-enterprise-running)

## Prerequisites
<a name="sample-github-enterprise-prerequisites"></a>

1. Generate a personal access token for your CodeBuild project. We recommend that you create a GitHub Enterprise user and generate a personal access token for this user. Copy it to your clipboard so that it can be used 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.

   When you create the personal access token, include the **repo** scope in the definition.  
![\[The repo scope in the definition.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/scopes.png)

1. Download your certificate from GitHub Enterprise Server. CodeBuild uses the certificate to make a trusted SSL connection to the repository.

   **Linux/macOS clients:**

   From a terminal window, run the following command:

   ```
   echo -n | openssl s_client -connect HOST:PORTNUMBER \
       | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /folder/filename.pem
   ```

   Replace the placeholders in the command with the following values:

   *HOST*. The IP address of your GitHub Enterprise Server repository.

   *PORTNUMBER*. The port number you are using to connect (for example, 443).

   *folder*. The folder where you downloaded your certificate.

   *filename*. The file name of your certificate file.
**Important**  
Save the certificate as a .pem file.

   **Windows clients:**

   Use your browser to download your certificate from GitHub Enterprise Server. To see the site's certificate details, choose the padlock icon. For information about how to export the certificate, see your browser documentation.
**Important**  
Save the certificate as a .pem file.

1. Upload your certificate file to an S3 bucket. For information about how to create an S3 bucket, see [How do I create an S3 Bucket?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket.html) For information about how to upload objects to an S3 bucket, see [How do I upload files and folders to a bucket?](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)
**Note**  
This bucket must be in the same AWS region as your builds. For example, if you instruct CodeBuild to run a build in the US East (Ohio) Region, the bucket must be in the US East (Ohio) Region.

## Step 1: Create a build project with GitHub Enterprise Server and enable webhooks
<a name="sample-github-enterprise-running"></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.  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**. 

1. In **Project name**, enter a name for this build project. Build project names must be unique across each AWS account. You can also include an optional description of the build project to help other users understand what this project is used for.

1. In **Source**, in **Source provider**, choose **GitHub Enterprise Server**.
   + Choose **Manage account credentials**, and then choose **Personal access token**. For **Service**, choose **Secrets Manager (recommended)**, and configure your secret. Then in **,GitHub Enterprise personal access token**, enter your personal access token and choose **Save**.
   + In **Repository URL**, enter the path to your repository, including the name of the repository.
   + Expand **Additional configuration**.
   + Select **Rebuild every time a code change is pushed to this repository** to rebuild every time a code change is pushed to this repository.
   + Select **Enable insecure SSL** to ignore SSL warnings while you connect to your GitHub Enterprise Server project repository.
**Note**  
We recommend that you use **Enable insecure SSL** for testing only. It should not be used in a production environment.  
![\[The GitHub Enterprise Server project repository configuration.\]](http://docs.aws.amazon.com/codebuild/latest/userguide/images/github-enterprise.png)

1. In **Environment**:

   For **Environment image**, 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*.

1. In **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.
**Note**  
When you use the console to create or update 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.

1. Expand **Additional configuration**.

   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).

1. In **Buildspec**, do one of the following:
   + Choose **Use a buildspec file** to use the buildspec.yml file in the source code root directory.
   + Choose **Insert build commands** to use the console to insert build commands.

   For more information, see the [Buildspec reference](build-spec-ref.md).

1. In **Artifacts**, for **Type**, do one of the following:
   + If you do not want to create build output artifacts, choose **No artifacts**.
   + 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. By default, the artifact name is the project name. If you want to use a different name, enter it in the artifacts name box. If you want to output a ZIP file, include the zip extension.
     + For **Bucket name**, choose the name of the output bucket.
     + If you chose **Insert build commands** earlier in this procedure, 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).

1. 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). 

1. Choose **Create build project**. On the build project page, choose **Start build**.

# Run the GitHub pull request and webhook filter sample for CodeBuild
<a name="sample-github-pull-request"></a>

AWS CodeBuild supports webhooks when the source repository is GitHub. This means that for a CodeBuild build project that has its source code stored in a GitHub repository, webhooks can be used to rebuild the source code every time a code change is pushed to the repository. For CodeBuild samples, see [AWS CodeBuild Samples](https://github.com/aws-samples/aws-codebuild-samples).

**Note**  
When using webhooks, it is possible for a user to trigger an unexpected build. To mitigate this risk, see [Best practices for using webhooks](webhooks.md#webhook-best-practices).

**Topics**
+ [Step 1: Create a build project with GitHub and enable webhooks](#sample-github-pull-request-running)
+ [Step 2: Verify that webhooks are enabled](#verification-checks)

## Step 1: Create a build project with GitHub and enable webhooks
<a name="sample-github-pull-request-running"></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.  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**. 

1. Choose **Create build project**. 

1. In **Project configuration**:  
**Project name**  
Enter a name for this build project. Build project names must be unique across each AWS account. You can also include an optional description of the build project to help other users understand what this project is used for.

1. In **Source**:  
**Source provider**  
Choose **GitHub**. Follow the instructions to connect (or reconnect) with GitHub and then choose **Authorize**.  
**Repository**  
Choose **Repository in my GitHub account**.  
**GitHub repository**  
Enter the URL for your GitHub repository.

1. In **Primary source webhook events**, select the following.
**Note**  
The **Primary source webhook events** section is only visible if you chose **Repository in my GitHub account** in the previous step.

   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 about GitHub webhook event types and filters, see [GitHub webhook events](github-webhook.md).

1. In **Environment**:  
**Environment image**  
Choose 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*.  
**Service role**  
Choose 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 or update 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.

1. In **Buildspec**, do one of the following:
   + Choose **Use a buildspec file** to use the buildspec.yml file in the source code root directory.
   + Choose **Insert build commands** to use the console to insert build commands.

   For more information, see the [Buildspec reference](build-spec-ref.md).

1. In **Artifacts**:  
**Type**  
Choose one of the following:  
   + If you do not want to create build output artifacts, choose **No artifacts**.
   + 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. By default, the artifact name is the project name. If you want to use a different name, enter it in the artifacts name box. If you want to output a ZIP file, include the zip extension.
     + For **Bucket name**, choose the name of the output bucket.
     + If you chose **Insert build commands** earlier in this procedure, 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).  
**Additional configuration**  
Expand **Additional configuration** and set options as appropriate.

1. Choose **Create build project**. On the **Review** page, choose **Start build** to run the build.

## Step 2: Verify that webhooks are enabled
<a name="verification-checks"></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 link for the build project with webhooks you want to verify, and then choose **Build details**.
   + Choose the button next to the build project with webhooks you want to verify, choose **View details**, and then choose the **Build details** tab.

1. In **Primary source webhook events**, choose the **Webhook** URL link. 

1. In your GitHub repository, on the **Settings** page, under **Webhooks**, verify that **Pull Requests** and **Pushes** are selected.

1. In your GitHub profile settings, under **Personal settings**, **Applications**, **Authorized OAuth Apps**, you should see that your application has been authorized to access the AWS Region you selected.

# Tutorial: Apple code signing with Fastlane in CodeBuild using S3 for certificate storage
<a name="sample-fastlane"></a>

[fastlane](https://docs.fastlane.tools/) is a popular open source automation tool to automate beta deployments and releases for your iOS and Android apps. It handles all tedious tasks, like generating screenshots, dealing with code signing, and releasing your application.

## Prerequisites
<a name="sample-fastlane-prerequisites"></a>

To complete this tutorial, you must first have set up the following:
+ An AWS account
+ An [ Apple Developer account ](https://developer.apple.com/)
+ An S3 bucket for storing certificates
+ fastlane installed in your project - [ Guide ](https://docs.fastlane.tools/getting-started/ios/setup/) to install fastlane

## Step 1: Set up Fastlane Match with S3 on your local machine
<a name="sample-fastlane-S3"></a>

[Fastlane Match](https://docs.fastlane.tools/actions/match/) is one of the [ Fastlane tools](https://fastlane.tools/), and it allows for seamless configuration for code signing in both your local development environment and on CodeBuild. Fastlane Match stores all of your code signing certificates and provisioning profiles in a Git repository/S3 Bucket/Google Cloud Storage, and downloads and installs the necessary certificates and profiles when required.

In this example configuration, you will set up and use an Amazon S3 bucket for storage. 

****

1. Initialize match in your project:

   ```
   fastlane match init
   ```

1. When prompted, choose S3 as the storage mode.

1. Update your `*Matchfile*` to use S3:

   ```
   storage_mode("s3")
      s3_bucket("your-s3-bucket-name")
      s3_region("your-aws-region")
      type("appstore") # The default type, can be: appstore, adhoc, enterprise or development
   ```

## Step 2: Set up your Fastfile
<a name="sample-fastlane-S3-fastfile"></a>

Create or update your `Fastfile` with the following lane.

On CodeBuild, Fastlane Match will need to be run every time you build and sign your app. The easiest way to do this is to add the `match` action to the lane which builds your app.

```
default_platform(:ios)

platform :ios do
  before_all do
    setup_ci
  end
  
  desc "Build and sign the app"
  lane :build do
    match(type: "appstore", readonly: true)
    gym(
      scheme: "YourScheme",
      export_method: "app-store"
    )
  end
end
```

**Note**  
Make sure to add `setup_ci` to the `before_all `section in `Fastfile` for the match action to work correctly. This ensures that a temporary Fastlane keychain with the appropriate permissions is used. Without using this you may see build failures or inconsistent results. 



## Step 3: Run the `fastlane match` command to generate respective certificates and profiles
<a name="sample-fastlane-S3-certificates"></a>

The fastlane match command for the given type (i.e., development, appstore, adhoc, enterprise) will generate the certificate and profile if not available in remote store. The certificates and profiles will be stored in S3 by fastlane.

```
bundle exec fastlane match appstore
```

The command execution will be interactive and fastlane will ask to set pass phrase for decrypting the certificates.

## Step 4: Create the application file for your project
<a name="sample-fastlane-S3-appfile"></a>

Create or add the application file as appropriate for your project.

****

1. Create or add the [Gymfile](http://docs.fastlane.tools/actions/gym/#gymfile), [Appfile](http://docs.fastlane.tools/advanced/Appfile/), [Snapfile](http://docs.fastlane.tools/actions/snapshot/#snapfile), [Deliverfile](http://docs.fastlane.tools/actions/deliver/#editing-the-deliverfile) based on your project build requirements.

1. Commit the changes to your remote repository

## Step 5: Create environment variables in Secrets Manager
<a name="sample-fastlane-S3-secrets"></a>

Create two secrets for storing the fastlane session cookie and matching pass phrase. For more information about creating secrets in Secrets Manager, see [Create an AWS Secrets Manager secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html).

****

1. Access your fastlane session cookie as follows.

   1. Secret key - `FASTLANE_SESSION`

   1. Secret value - session cookie generated from running the following command on your local machine.
**Note**  
This value is available after authentication in a local file: `~/.fastlane/spaceship/my_appleid_username/cookie`.

      ```
      fastlane spaceauth -u <apple account>
      ```

1. Fastlane Match pass phrase - To enable Fastlane Match to decrypt the certificates and profiles stored in the S3 bucket, it is necessary to add the encryption passphrase that you configured in the Match setup step to the CodeBuild project’s environment variables.

   1. Secret key - `MATCH_PASSWORD`

   1. Secret value - *<match passphrase to decrypt certificates>*. The passphrase is set while generating the certificates in Step 3.

**Note**  
While creating the above secrets in Secrets Manager, remember to give a secret name with the following prefix: `/CodeBuild/`

## Step 6: Create a compute fleet
<a name="sample-fastlane-S3-fleet"></a>

Create the compute fleet for your project.

****

1. In the console, go to CodeBuild and create a new compute fleet.

1. Choose "macOS" as the operating system and select an appropriate compute type and image.

## Step 7: Create a project in CodeBuild
<a name="sample-fastlane-S3-project"></a>

Create your project in CodeBuild.



****

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. Set up your source provider (such as GitHub, CodeCommit). This is iOS project source repository and not certificates repository.

1.  In **Environment**: 
   + Choose **Reserved Capacity**.
   + For **Fleet**, select the fleet created above.
   + Provide the name of the service role that CodeBuild will create for you.
   + Provide the below environment variables.
     + Name: `MATCH_PASSWORD`, Value: *<secrets arn>*, Type: Secrets Manager (Secrets ARN created in step 5 for MATCH\$1PASSWORD)
     + Name: `FASTLANE_SESSION`, Value: *<secrets arn>*, Type: Secrets Manager (Secrets ARN created in Step 5 for FASTLANE\$1SESSION)

1. In **Buildspec**, add the following:

   ```
   version: 0.2
   
   phases:
     install:
       commands:
         - gem install bundler
         - bundle install
     build:
       commands:
         - echo "Building and signing the app..."
         - bundle exec fastlane build
     post_build:
       commands:
         - echo "Build completed on date"
   
   artifacts:
     files:
       - '*/.ipa'
     name: app-$(date +%Y-%m-%d)
   ```

## Step 8: Configure IAM role
<a name="sample-fastlane-S3-role"></a>

Once the project is created, ensure your CodeBuild project's service role has permissions to access the S3 bucket containing the certificates. Add the following policy to the role:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:ListBucket"
            ],
            "Resource": "arn:aws:s3:::your-s3-bucket-name"
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:DeleteObject"
            ],
            "Resource": "arn:aws:s3:::your-s3-bucket-name/*"
        }
    ]
}
```

------

## Step 9: Run the build
<a name="sample-fastlane-S3-run"></a>

Run the build. You can review the build status and logs in CodeBuild.

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

## Troubleshooting
<a name="sample-fastlane-S3-troubleshooting"></a>
+ If you encounter issues with certificate fetching, ensure your IAM permissions are set up correctly for S3 access.
+ If you encounter issues with certificate decrypting, ensure you set correct passphrase in MATCH\$1PASSWORD environment variable.
+ For code signing issues, verify that your Apple Developer account has the necessary certificates and profiles, and that the bundle identifier in your Xcode project matches the one in your provisioning profile.

## Security considerations
<a name="sample-fastlane-considerations"></a>

The following are security considerations for this tutorial.
+ Ensure your S3 bucket has appropriate security settings, including encryption at rest. In particular, make sure the bucket has no public access and restrict access to only CodeBuild and the system that needs to have an access.
+ Consider using AWS Secrets Manager for storing sensitive information like the MATCH\$1PASSWORD and FASTLANE\$1SESSION.

This sample provides a setup for iOS code signing with Fastlane in CodeBuild using Amazon S3 for certificate storage. You may need to adjust some steps based on your specific project requirements and CodeBuild environment. This approach leverages AWS services for enhanced security and integration within the AWS ecosystem.

# Tutorial: Apple code signing with Fastlane in CodeBuild using GitHub for certificate storage
<a name="sample-fastlane-github"></a>

[fastlane](https://docs.fastlane.tools/) is a popular open source automation tool to automate beta deployments and releases for your iOS and Android apps. It handles all tedious tasks, like generating screenshots, dealing with code signing, and releasing your application.

This sample demonstrates how to set up Apple code signing using Fastlane in a CodeBuild project running on Mac fleet, with GitHub as the storage for certificates and provisioning profiles.

## Prerequisites
<a name="sample-fastlane-github-prerequisites"></a>

To complete this tutorial, you must first have set up the following:
+ An AWS account
+ An [ Apple Developer account ](https://developer.apple.com/)
+ A private GitHub repository for storing certificates
+ fastlane installed in your project - [ Guide ](https://docs.fastlane.tools/getting-started/ios/setup/) to install fastlane

## Step 1: Set up Fastlane Match with GitHub on your local machine
<a name="sample-fastlane-github-certificates"></a>

[Fastlane Match](https://docs.fastlane.tools/actions/match/) is one of the [ Fastlane tools](https://fastlane.tools/), and it allows for seamless configuration for code signing in both your local development environment and on CodeBuild. Fastlane Match stores all of your code signing certificates and provisioning profiles in a Git repository/S3 Bucket/Google Cloud Storage, and downloads and installs the necessary certificates and profiles when required.

In this example configuration, we will set up and use a Git repository for storage. 

****

1. Initialize match in your project:

   ```
   fastlane match init
   ```

1. When prompted, choose GitHub as the storage mode.

1. Update your `*Matchfile*` to use GitHub:

   ```
   git_url("https://github.com/your-username/your-certificate-repo.git")
   storage_mode("git")
   type("development") # The default type, can be: appstore, adhoc, enterprise or development
   ```

**Note**  
Make sure you enter HTTPS URL for your Git repository for fastlane to successfully authenticate and clone. Otherwise, you may see an authentication error when you attempt to use match.

## Step 2: Set up your Fastfile
<a name="sample-fastlane-github-fastfile"></a>

Create or update your `Fastfile` with the following lane.

On CodeBuild, Fastlane Match will need to be run every time you build and sign your app. The easiest way to do this is to add the `match` action to the lane which builds your app.

```
default_platform(:ios)

platform :ios do
  before_all do
    setup_ci
  end
  
  desc "Build and sign the app"
  lane :build do
    match(type: "appstore", readonly: true)
    gym(
      scheme: "YourScheme",
      export_method: "app-store"
    )
  end
end
```

**Note**  
Make sure to add `setup_ci` to the `before_all `section in `Fastfile` for the match action to work correctly. This ensures that a temporary Fastlane keychain with the appropriate permissions is used. Without using this you may see build failures or inconsistent results. 

## Step 3: Run the `fastlane match` command to generate respective certificates and profiles
<a name="sample-fastlane-github-certificates"></a>

The fastlane match command for the given type (i.e. development, appstore, adhoc, enterprise) will generate the certificate and profile if not available in remote store. The certificates and profiles will be stored in GitHub by fastlane.

```
bundle exec fastlane match appstore
```

The command execution will be interactive and fastlane will ask to set pass phrase for decrypting the certificates.

## Step 4: Create the application file for your project
<a name="sample-fastlane-github-appfile"></a>

Create or add the application file as appropriate for your project.

****

1. Create or add the [Gymfile](http://docs.fastlane.tools/actions/gym/#gymfile), [Appfile](http://docs.fastlane.tools/advanced/Appfile/), [Snapfile](http://docs.fastlane.tools/actions/snapshot/#snapfile), [Deliverfile](http://docs.fastlane.tools/actions/deliver/#editing-the-deliverfile) based on your project build requirements.

1. Commit the changes to your remote repository.

## Step 5: Create environment variables in Secrets Manager
<a name="sample-fastlane-github-secrets"></a>

Create three secrets for storing the fastlane session cookie and matching pass phrase. For more information about creating secrets in Secrets Manager, see [Create an AWS Secrets Manager secret](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html).

****

1. Access your fastlane session cookie as follows.

   1. Secret key - `FASTLANE_SESSION`

   1. Secret value - session cookie generated from running the following command on your local machine.
**Note**  
This value is available after authentication in a local file: `~/.fastlane/spaceship/my_appleid_username/cookie`.

      ```
      fastlane spaceauth -u <Apple_account>
      ```

1. Fastlane Match pass phrase - To enable Fastlane Match to decrypt the certificates and profiles stored in the Git repository, it is necessary to add the encryption passphrase that you configured in the Match setup step to the CodeBuild project’s environment variables.

   1. Secret key - `MATCH_PASSWORD`

   1. Secret value - `<match passphrase to decrypt certificates>`. The passphrase is set while generating the certificates in Step 3.

1. Fastlane `MATCH_GIT_BASIC_AUTHORIZATION` - set a basic authorization for *match*:

   1. Secret key: 

      `MATCH_GIT_BASIC_AUTHORIZATION`

   1. Secret value - The value should be a base64 encoded string of your username and personal access token (PAT) in the format `username:password`. You can generate it using the following command:

      ```
      echo -n your_github_username:your_personal_access_token | base64
      ```

      You can generate your PAT on the GitHub console in **Your Proﬁle > Settings > Developers Settings > Personal Access Token**. For more information, see the following guide: [https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens).

**Note**  
While creating the above secrets in Secrets Manager, remember to give a secret name with the following prefix: `/CodeBuild/`

## Step 6: Create a compute fleet
<a name="sample-fastlane-github-fleet"></a>

Create the compute fleet for your project.

****

1. In the console, go to CodeBuild and create a new compute fleet.

1. Choose `macOS` as the operating system and select an appropriate compute type and image.

## Step 7: Create a project in CodeBuild
<a name="sample-fastlane-github-project"></a>

Create your project in CodeBuild.

****

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. Set up your source provider (such as GitHub, CodeCommit). This is iOS project source repository and not certificates repository.

1.  In **Environment**: 
   + Choose **Reserved Capacity**.
   + For **Fleet**, select the fleet created above.
   + Provide the name of the service role that CodeBuild will create for you.
   + Provide the below environment variables.
     + Name: `MATCH_PASSWORD`, Value: *<secrets arn>*, Type: Secrets Manager (Secrets ARN created in step 5 for MATCH\$1PASSWORD)
     + Name: `FASTLANE_SESSION`, Value: *<secrets arn>*, Type: Secrets Manager (Secrets ARN created in step 5 for FASTLANE\$1SESSION)
     + Name: `MATCH_GIT_BASIC_AUTHORIZATION`, Value: *<secrets ARN>*, Type: Secrets Manager Secrets ARN (created in step 5 for `MATCH_GIT_BASIC_AUTHORIZATION`)

1. In **Buildspec**, add the following:

   ```
   version: 0.2
   
   phases:
     install:
       commands:
         - gem install bundler
         - bundle install
     build:
       commands:
         - echo "Building and signing the app..."
         - bundle exec fastlane build
     post_build:
       commands:
         - echo "Build completed on date"
   
   artifacts:
     files:
       - '*/.ipa'
     name: app-$(date +%Y-%m-%d)
   ```

## Step 8: Run the build
<a name="sample-fastlane-github-run"></a>

Run the build. You can review the build status and logs in CodeBuild.

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

## Troubleshooting
<a name="sample-fastlane-github-troubleshooting"></a>
+ If you encounter issues accessing the GitHub repository, double-check your personal access token and the MATCH\$1GIT\$1BASIC\$1AUTHORIZATION environment variable.
+ If you encounter issues with certificate decrypting, ensure you set correct passphrase in MATCH\$1PASSWORD environment variable.
+ For code signing issues, verify that your Apple Developer account has the necessary certificates and profiles, and that the bundle identifier in your Xcode project matches the one in your provisioning profile.

## Security considerations
<a name="sample-fastlane-github-considerations"></a>

The following are security considerations for this tutorial.
+ Keep your GitHub repository for certificates private and regularly audit access.
+ Consider using AWS Secrets Manager for storing sensitive information like the MATCH\$1PASSWORD and FASTLANE\$1SESSION.

This sample provides a setup for iOS code signing with Fastlane in CodeBuild using GitHub for certificate storage. You may need to adjust some steps based on your specific project requirements and CodeBuild environment. This approach leverages AWS services for enhanced security and integration within the AWS ecosystem.