

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

The Amazon Serverless Application Model (Amazon SAM) is an open-source framework for building serverless applications. For more information, see the [Amazon Serverless Application Model repository](https://github.com/aws/serverless-application-model) on GitHub. The following Java sample uses Gradle to build and test a Amazon Lambda function. After which, the Amazon SAM CLI is used to deploy the Amazon 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 Amazon SAM repository
<a name="sample-lambda-sam-gradle.set-up-repo"></a>

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

**To create your Amazon SAM Project**

1. Follow the instructions in the *Amazon Serverless Application Model Developer Guide* for [ Installing the Amazon SAM CLI](https://docs.amazonaws.cn/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 Amazon SAM project folder to a supported source repository. For a list of supported source types, see [ProjectSource](https://docs.amazonaws.cn/codebuild/latest/APIReference/API_ProjectSource.html).

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

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

**To create your CodeBuild Lambda Java project**

1. Open the Amazon CodeBuild console at [https://console.amazonaws.cn/codesuite/codebuild/home](https://console.amazonaws.cn/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 Amazon 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 Amazon 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 Amazon SAM infrastructure later on. For more information, see [Adding and removing IAM identity permissions](https://docs.amazonaws.cn//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-cn: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 Amazon 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 Amazon SAM application to Amazon Lambda using Amazon CloudFormation.

1. Once the build has finished, navigate to the Amazon Lambda console and search for your new Lambda function under the Amazon 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 Amazon SAM template and CodeBuild.

**To clean up your infrastructure**

1. Navigate to the Amazon 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 Amazon CloudFormation stack associated with your Amazon SAM project. This stack should have the same name as your Amazon 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**.