

# Run builds on AWS Lambda compute
<a name="lambda"></a>

AWS Lambda compute offers optimized start-up speeds for your builds. AWS Lambda supports faster builds due to a lower start-up latency. AWS Lambda also automatically scales, so builds aren’t waiting in queue to run. However, there are some use-cases which AWS Lambda does not support, and if they impact you, use the EC2 compute. For more information, see [Limitations of AWS Lambda compute](#lambda.limitations).

**Topics**
+ [Which tools and runtimes will be included in the curated runtime environment docker images which run on AWS Lambda?](#lambda.tools)
+ [What if the curated image doesn't include the tools I need?](#lambda.custom)
+ [Which regions support AWS Lambda compute in CodeBuild?](#lambda.regions)
+ [Limitations of AWS Lambda compute](#lambda.limitations)
+ [Deploy a Lambda function using AWS SAM with CodeBuild Lambda Java](sample-lambda-sam-gradle.md)
+ [Create a single page React app with CodeBuild Lambda Node.js](sample-lambda-react-nodejs.md)
+ [Update a Lambda function configuration with CodeBuild Lambda Python](sample-lambda-boto3-python.md)

## Which tools and runtimes will be included in the curated runtime environment docker images which run on AWS Lambda?
<a name="lambda.tools"></a>

AWS Lambda supports the following tools: AWS CLI v2, AWS SAM CLI, git, go, Java, Node.js, Python, pip, Ruby, and .NET.

## What if the curated image doesn't include the tools I need?
<a name="lambda.custom"></a>

If the curated image doesn't include the tools you need, you can provide a custom environment Docker image that includes the necessary tools.

**Note**  
Lambda does not support functions that use multi-architecture container images. For more information, see [Create a Lambda function using a container image ](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html#images-reqs) in the *AWS Lambda Developer Guide*.

Note that you require the following Amazon ECR permissions to use custom images for Lambda compute:

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:GetAuthorizationToken"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage"
            ],
            "Resource": "arn:aws:ecr:us-east-1:111122223333:repository/image-repo"
        }
    ]
}
```

------

Also note that `curl` or `wget` must be installed in order to use custom images.

## Which regions support AWS Lambda compute in CodeBuild?
<a name="lambda.regions"></a>

In CodeBuild, AWS Lambda compute is supported in the following AWS Regions: US East (N. Virginia), US East (Ohio), US West (Oregon), Asia Pacific (Mumbai), Asia Pacific (Singapore), Asia Pacific (Sydney), Asia Pacific (Tokyo), Europe (Frankfurt), Europe (Ireland), and South America (São Paulo). 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/).

## Limitations of AWS Lambda compute
<a name="lambda.limitations"></a>

There are some use-cases which AWS Lambda does not support, and if they impact you, use the EC2 compute:
+ AWS Lambda doesn't support tools that require root permissions. For tools such as `yum` or `rpm`, use the EC2 compute type or other tools that don't require root permissions.
+ AWS Lambda doesn't support Docker builds or runs.
+ AWS Lambda doesn't support writing to files outside `/tmp`. The included package managers are configured to use the `/tmp` directory by default for downloading and referencing packages.
+ AWS Lambda doesn't support the environment type `LINUX_GPU_CONTAINER` and isn't supported on Windows Server Core 2019.
+ AWS Lambda doesn't support caching, custom build timeouts, queue timeout, build badges, privileged mode, custom runtime environments, or runtimes longer than 15 minutes.
+ AWS Lambda doesn't support VPC connectivity, a fixed range of CodeBuild source IP addresses, EFS, installing certificates, or SSH access with Session Manager.

# Deploy a Lambda function using AWS SAM with CodeBuild Lambda Java
<a name="sample-lambda-sam-gradle"></a>

The AWS Serverless Application Model (AWS SAM) is an open-source framework for building serverless applications. For more information, see the [AWS Serverless Application Model repository](https://github.com/aws/serverless-application-model) on GitHub. The following Java sample uses Gradle to build and test a AWS Lambda function. After which, the AWS SAM CLI is used to deploy the CloudFormation template and deployment bundle. By using CodeBuild Lambda, the build, test, and deployment steps are all handled automatically, allowing for infrastructure to be quickly updated without manual intervention in a single build.

## Set up your AWS SAM repository
<a name="sample-lambda-sam-gradle.set-up-repo"></a>

Create an AWS SAM `Hello World` project using the AWS SAM CLI.

**To create your AWS SAM Project**

1. Follow the instructions in the *AWS Serverless Application Model Developer Guide* for [ Installing the AWS SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html) on your local machine.

1. Run `sam init` and select the following project configuration.

   ```
   Which template source would you like to use?: 1 - AWS Quick Start Templates
   Choose an AWS Quick Start application template: 1 - Hello World Example
   Use the most popular runtime and package type? (Python and zip) [y/N]: N
   Which runtime would you like to use?: 8 - java21
   What package type would you like to use?: 1 - Zip
   Which dependency manager would you like to use?: 1 - gradle
   Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: N
   Would you like to enable monitoring using CloudWatch Application Insights? [y/N]: N
   Would you like to set Structured Logging in JSON format on your Lambda functions? [y/N]:  N
   Project name [sam-app]: <insert project name>
   ```

1. Upload the AWS SAM project folder to a supported source repository. For a list of supported source types, see [ProjectSource](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectSource.html).

## Create a CodeBuild Lambda Java project
<a name="sample-lambda-sam-gradle.create-project"></a>

Create an AWS CodeBuild Lambda Java project and set up the IAM permissions needed for the build.

**To create your CodeBuild Lambda Java 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.  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**, select the source repository where your AWS SAM project is located.

1. In **Environment**:
   + For **Compute**, select **Lambda**.
   + For **Runtime(s)**, select **Java**.
   + For **Image**, select **aws/codebuild/amazonlinux-x86\$164-lambda-standard:corretto21**.
   + For **Service role**, leave **New service role** selected. Make a note of the **Role name**. This will be required when you update the project’s IAM permissions later in this sample.

1. Choose **Create build project**.

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

1. In the navigation pane, choose **Roles** and select the service role associated with your project. You can find your project role in CodeBuild by selecting your build project, choosing **Edit**, **Environment**, and then **Service role**.

1. Choose the **Trust relationships** tab, and then choose **Edit trust policy**.

1. Add the following inline policy to your IAM role. This will be used to deploy your AWS SAM infrastructure later on. For more information, see [Adding and removing IAM identity permissions](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *IAM User Guide*.

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "",
               "Effect": "Allow",
               "Action": [
                   "cloudformation:*",
                   "lambda:*",
                   "iam:*",
                   "apigateway:*",
                   "s3:*"
               ],
               "Resource": "arn:aws:iam::*:role/Service*"
           }
       ]
   }
   ```

------

## Set up the project buildspec
<a name="sample-lambda-sam-gradle.set-up-buildspec"></a>

In order to build, test, and deploy your Lambda function, CodeBuild reads and executes build commands from a buildspec.

**To set up your project buildspec**

1. In the CodeBuild console, select your build project, then choose **Edit** and **Buildspec**.

1. In **Buildspec**, choose **Insert build commands** and then **Switch to editor**.

1. Delete the pre-filled build commands and paste in the following buildspec.

   ```
   version: 0.2
   env:
     variables:
       GRADLE_DIR: "HelloWorldFunction"
   phases:
     build:
       commands:
         - echo "Running unit tests..."
         - cd $GRADLE_DIR; gradle test; cd ..
         - echo "Running build..."
         - sam build --template-file template.yaml
         - echo "Running deploy..."
         - sam package --output-template-file packaged.yaml --resolve-s3 --template-file template.yaml
         - yes | sam deploy
   ```

1. Choose **Update buildspec**.

## Deploy your AWS SAM Lambda infrastructure
<a name="sample-lambda-sam-gradle.deploy"></a>

Use CodeBuild Lambda to automatically deploy your Lambda infrastructure

**To deploy your Lambda infrastructure**

1. Choose **Start build**. This will automatically build, test, and deploy your AWS SAM application to AWS Lambda using CloudFormation.

1. Once the build has finished, navigate to the AWS Lambda console and search for your new Lambda function under the AWS SAM project name.

1. Test your Lambda function by selecting **API Gateway** under the **Function** overview, then clicking the **API endpoint** URL. You should see a page open with the message `"message": "hello world"`.

## Clean up your infrastructure
<a name="sample-lambda-sam-gradle.clean-up"></a>

To avoid further charges for resources you used during this tutorial, delete the resources created by your AWS SAM template and CodeBuild.

**To clean up your infrastructure**

1. Navigate to the CloudFormation console and select the `aws-sam-cli-managed-default`.

1. In **Resources**, empty the deployment bucket `SamCliSourceBucket`.

1. Delete the `aws-sam-cli-managed-default` stack.

1. Delete the CloudFormation stack associated with your AWS SAM project. This stack should have the same name as your AWS SAM project.

1. Navigate to the CloudWatch console and delete the CloudWatch log groups associated with your CodeBuild project.

1. Navigate to the CodeBuild console and delete your CodeBuild project by choosing **Delete build project**.

# Create a single page React app with CodeBuild Lambda Node.js
<a name="sample-lambda-react-nodejs"></a>

[Create React App](https://create-react-app.dev/) is a way to create single-page React applications. The following Node.js sample uses Node.js to build the source artifacts from Create React App and returns the build artifacts.

## Set up your source repository and artifacts bucket
<a name="sample-lambda-react-nodejs.set-up-repo"></a>

Create a source repository for your project using yarn and Create React App.

**To set up the source repository and artifacts bucket**

1. On your local machine, run `yarn create react-app <app-name>` to create a simple React app.

1. Upload the React app project folder to a supported source repository. For a list of supported source types, see [ProjectSource](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectSource.html).

## Create a CodeBuild Lambda Node.js project
<a name="sample-lambda-react-nodejs.create-project"></a>

Create an AWS CodeBuild Lambda Node.js project.

**To create your CodeBuild Lambda Node.js 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.  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**, select the source repository where your AWS SAM project is located.

1. In **Environment**:
   + For **Compute**, select **Lambda**.
   + For **Runtime(s)**, select **Node.js**.
   + For **Image**, select **aws/codebuild/amazonlinux-x86\$164-lambda-standard:nodejs20**.

1. In **Artifacts**:
   + For **Type**, select **Amazon S3**.
   + For **Bucket name**, select the project artifacts bucket you created earlier.
   + For **Artifacts packaging**, select **Zip**.

1. Choose **Create build project**.

## Set up the project buildspec
<a name="sample-lambda-react-nodejs.set-up-buildspec"></a>

In order to build your React app, CodeBuild reads and executes build commands from a buildspec file.

**To set up your project buildspec**

1. In the CodeBuild console, select your build project, then choose **Edit** and **Buildspec**.

1. In **Buildspec**, choose **Insert build commands** and then **Switch to editor**.

1. Delete the pre-filled build commands and paste in the following buildspec.

   ```
   version: 0.2
   phases:
     build:
       commands:
         - yarn
         - yarn add --dev jest-junit @babel/plugin-proposal-private-property-in-object
         - yarn run build
         - yarn run test -- --coverage --watchAll=false --testResultsProcessor="jest-junit" --detectOpenHandles
   artifacts:
     name: "build-output"
     files:
       - "**/*"
   reports:
     test-report:
       files:
         - 'junit.xml'
       file-format: 'JUNITXML'
     coverage-report:
       files:
         - 'coverage/clover.xml'
       file-format: 'CLOVERXML'
   ```

1. Choose **Update buildspec**.

## Build and run your React app
<a name="sample-lambda-react-nodejs.build"></a>

Build the React app on CodeBuild Lambda, download the build artifacts, and run the React app locally.

**To build and run your React app**

1. Choose **Start build**.

1. Once the build has finished, navigate to your Amazon S3 project artifacts bucket and download the React app artifact.

1. Unzip the React build artifact and `run npm install -g serve && serve -s build` in the project folder.

1. The `serve` command will serve the static site on a local port and print output to your terminal. You can visit the localhost URL under `Local:` in the terminal output to view your React app.

To learn more about how to handle deployment for a React based server, see [Create React App Deployment](https://create-react-app.dev/docs/deployment/).

## Clean up your infrastructure
<a name="sample-lambda-react-nodejs.clean-up"></a>

To avoid further charges for resources you used during this tutorial, delete the resources created for your CodeBuild project.

**To clean up your infrastructure**

1. Delete your project artifacts Amazon S3 bucket

1. Navigate to the CloudWatch console and delete the CloudWatch log groups associated with your CodeBuild project.

1. Navigate to the CodeBuild console and delete your CodeBuild project by choosing **Delete build project**.

# Update a Lambda function configuration with CodeBuild Lambda Python
<a name="sample-lambda-boto3-python"></a>

The following Python sample uses [Boto3](https://aws.amazon.com/sdk-for-python/) and CodeBuild Lambda Python to update a Lambda function’s configuration. This sample can be extended to manage other AWS resources programmatically. For more information, see [Boto3 documentation](https://aws.amazon.com/sdk-for-python/).

## Prerequisites
<a name="sample-lambda-boto3-python.prerequisites"></a>

Create or find a Lambda function in your account.

This sample assumes that you have already created a Lambda function in your account and will use CodeBuild to update the Lambda function’s environment variables. For more information on setting up a Lambda function through CodeBuild, see the [Deploy a Lambda function using AWS SAM with CodeBuild Lambda Java](sample-lambda-sam-gradle.md) sample or visit [AWS Lambda](https://aws.amazon.com/lambda/).

## Set up your source repository
<a name="sample-lambda-boto3-python.set-up-repo"></a>

Create a source repository to store your Boto3 python script.

**To set up the source repository**

1. Copy the following python script to a new file called `update_lambda_environment_variables.py`.

   ```
   import boto3
   from os import environ
   
   
   def update_lambda_env_variable(lambda_client):
       lambda_function_name = environ['LAMBDA_FUNC_NAME']
       lambda_env_variable = environ['LAMBDA_ENV_VARIABLE']
       lambda_env_variable_value = environ['LAMBDA_ENV_VARIABLE_VALUE']
       print("Updating lambda function " + lambda_function_name + " environment variable "
             + lambda_env_variable + " to " + lambda_env_variable_value)
       lambda_client.update_function_configuration(
           FunctionName=lambda_function_name,
           Environment={
               'Variables': {
                   lambda_env_variable: lambda_env_variable_value
               }
           },
       )
   
   
   if __name__ == "__main__":
       region = environ['AWS_REGION']
       client = boto3.client('lambda', region)
       update_lambda_env_variable(client)
   ```

1. Upload the python file to a supported source repository. For a list of supported source types, see [ProjectSource](https://docs.aws.amazon.com/codebuild/latest/APIReference/API_ProjectSource.html).

## Create a CodeBuild Lambda Python project
<a name="sample-lambda-boto3-python.create-project"></a>

Create a CodeBuild Lambda Python project.

**To create your CodeBuild Lambda Java 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.  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**, select the source repository where your AWS SAM project is located.

1. In **Environment**:
   + For **Compute**, select **Lambda**.
   + For **Runtime(s)**, select **Python**.
   + For **Image**, select **aws/codebuild/amazonlinux-x86\$164-lambda-standard:python3.12**.
   + For **Service role**, leave **New service role** selected. Make a note of the **Role name**. This will be required when you update the project’s IAM permissions later in this sample.

1. Choose **Create build project**.

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

1. In the navigation pane, choose **Roles** and select the service role associated with your project. You can find your project role in CodeBuild by selecting your build project, choosing **Edit**, **Environment**, and then **Service role**.

1. Choose the **Trust relationships** tab, and then choose **Edit trust policy**.

1. Add the following inline policy to your IAM role. This will be used to deploy your AWS SAM infrastructure later on. For more information, see [Adding and removing IAM identity permissions](https://docs.aws.amazon.com//IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *IAM User Guide*.

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

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "UpdateLambdaPermissions",
               "Effect": "Allow",
               "Action": [
                   "lambda:UpdateFunctionConfiguration"
               ],
               "Resource": [
                   "*"
               ]
           }
       ]
   }
   ```

------

## Set up the project buildspec
<a name="sample-lambda-boto3-python.set-up-buildspec"></a>

In order to update the Lambda function, the script reads environment variables from the buildspec to find the Lambda function’s name, environment variable name, and environment variable value.

**To set up your project buildspec**

1. In the CodeBuild console, select your build project, then choose **Edit** and **Buildspec**.

1. In **Buildspec**, choose **Insert build commands** and then **Switch to editor**.

1. Delete the pre-filled build commands and paste in the following buildspec.

   ```
   version: 0.2
   env:
     variables:
       LAMBDA_FUNC_NAME: "<lambda-function-name>"
       LAMBDA_ENV_VARIABLE: "FEATURE_ENABLED"
       LAMBDA_ENV_VARIABLE_VALUE: "true"
   phases:
     install:
       commands:
          - pip3 install boto3
     build:
       commands:
          - python3 update_lambda_environment_variables.py
   ```

1. Choose **Update buildspec**.

## Update your Lambda configuration
<a name="sample-lambda-boto3-python.update"></a>

Use CodeBuild Lambda Python to automatically update your Lambda function’s configuration.

**To update your Lambda function’s configuration**

1. Choose **Start build**.

1. Once the build has finished, navigate to your Lambda function.

1. Select **Configuration** and then **Environment** variables. You should see a new environment variable with key `FEATURE_ENABLED` and value `true`.

## Clean up your infrastructure
<a name="sample-lambda-boto3-python.clean-up"></a>

To avoid further charges for resources you used during this tutorial, delete the resources created for your CodeBuild project.

**To clean up your infrastructure**

1. Navigate to the CloudWatch console and delete the CloudWatch log groups associated with your CodeBuild project.

1. Navigate to the CodeBuild console and delete your CodeBuild project by choosing **Delete build project**.

1. If you created a Lambda function for the purpose of this sample, choose **Actions** and **Delete function** to clean up your Lambda function.

## Extensions
<a name="sample-lambda-boto3-python.extensions"></a>

If you want to extend this sample to manage other AWS resources using AWS CodeBuild Lambda Python:
+ Update the Python script to modify the new resources using Boto3.
+ Update the IAM role associated with your CodeBuild project to have permissions for the new resources.
+ Add any new environment variables associated with the new resources to your buildspec.