amazon-web-servicesaws-lambdaaws-codebuildaws-codecommitbuildspec

Upload jar to Lambda when I do CodeCommit in AWS


When i push changes in AWS CodeCommit Repo, I want to make JAR file with mvn install command for that Java Code and upload it to AWS Lambda function. Location of that Jar file should be inside src/main/target. Can anyone suggest buildspec.yaml file?


Solution

  • Assuming that you're using AWS SAM (Serverless Application Model), this is as simple as calling a single command in the post_build section of your buildspec.yaml. Example:

    version: 0.2
    
    phases:
      install:
        runtime-versions:
          java: corretto8
      pre_build:
        commands:
          - mvn clean
      build:
        commands:
          - mvn install
      post_build:
        commands:
          - sam deploy --stack-name lambda-java --no-confirm-changeset
    artifacts:
      files:
        - target/lambda-java.jar
      discard-paths: no
    

    Please note though that you'll also have to set up a mechanism that kicks off the build process when you push any changes to your repository. The easiest way doing this is using AWS CodePipeline, as that nicely integrates with CodeCommit. Simply create a new pipeline, choose your existing CodeCommit repository where the Java-based Lambda is stored, and select CodeBuild as the build provider (skip the deploy stage).

    Also note that your CodeBuild service role will have to have the appropriate permissions to deploy the Lambda function. As SAM is leveraged, this includes permissions to upload to S3 and update the corresponding CloudFormation stack (see stack-name parameter above).

    From here on, whenever you push any changes to your repo, CodePipeline will trigger a build using CodeCommit, which will then deploy a new version of your Lambda via the sam deploy command in your buildspec.yaml.