With [AWS] CodeStar, you can build a Spring (Java) project running on Lambda in just 3 minutes! !!

CodeStar AWS CodeStar allows you to build an environment that allows you to quickly develop and deploy your applications. There are several templates available, and you can build a development project just by selecting them from the management console.

Environment to be built

--Code repository (CodeCommit and GitHub can be selected) --CodeBuilde environment --CodePipeline environment --Application --IDE (when Cloud9 is selected)

Fee

There is no charge for CodeStar itself. Only resource usage fees for code repositories, pipelines, and deployed applications built by CodeStar.

Notes

If you select the Tokyo region as the region, you cannot select Cloud9 as the IDE (as of August 2020). Since we want to build an environment with Cloud9 this time, we will select northern Virginia (us-east-1) as the region.

Environment construction procedure

First, in the management console, select CodeStar from Services. This time to IDE I want to use Cloud9, so I'm going to make the region northern Virginia.

CodeStar1.png

You can select the application type and language. This time, I will create a project with a Lambda + Java Spring template.

CodeStar3.png

Then select the code repository. This time, let's select CodeCommit.

CodeStart4.png

Check the contents and create a project.

Finally select the IDE. This time, it's AWS Cloud9. Please note that Cloud9 may not be available in all regions. If you select Cloud9, you will be asked for the instance type, so this time we will proceed with the default t2.micro.

CodeStar5.png

The project and IDE will start to be created (CloudFormation works behind the scenes).

CodeStar6.png

The environment construction is completed in about 3 minutes for the project. Since the IDE creates an EC2 instance, it also takes about 3 minutes. When both are ready, you will see the screen below.

CodeStar7.png

Repository status

Select "Code" from the menu on the left to display the CodeCommit screen. The Spring template structure has been created, up to buildspec.yml.

CodeCommit1.png

The contents of buildspec.yml are like this.

codespec.yml


version: 0.2

phases:
  install:
    runtime-versions:
      java: openjdk8
    commands:
      # Upgrade AWS CLI to the latest version
      - pip install --upgrade awscli
  pre_build:
    commands:
      - echo Test started on `date`
      - mvn clean compile test
  build:
    commands:
      - echo Build started on `date`
      - mvn package shade:shade
      - mv target/HelloWorld-1.0.jar .
      - unzip HelloWorld-1.0.jar
      - rm -rf target tst src buildspec.yml pom.xml HelloWorld-1.0.jar
      - aws cloudformation package --template template.yml --s3-bucket $S3_BUCKET --output-template template-export.yml
  post_build:
    commands:
      # Do not remove this statement. This command is required for AWS CodeStar projects.
      # Update the AWS Partition, AWS Region, account ID and project ID in the project ARN on template-configuration.json file so AWS CloudFormation can tag project resources.
      - sed -i.bak 's/\$PARTITION\$/'${PARTITION}'/g;s/\$AWS_REGION\$/'${AWS_REGION}'/g;s/\$ACCOUNT_ID\$/'${ACCOUNT_ID}'/g;s/\$PROJECT_ID\$/'${PROJECT_ID}'/g' template-configuration.json
artifacts:
  files:
    - template-export.yml
    - template-configuration.json

You can see that it is compiled with Maven in OpenJDK8.

IDE Now, let's select IDE from the menu. Then CLoud9 will start and will automatically retrieve the code from the CodeCommit repository with git clone.

CodeCommit1.png

If you set up a team, you can share the code repository with a cross account and do mob programming.

[AWS] Let's create a mob programming environment with Cloud9

App execution

This time, it is an API by Lambda. Pressing the "View App" button on the dashboard will call the first API included in the project template.

{"Output":"Hello World!"}

What about specific API Gateways and Lambda?

API Gateway You can see that there is one REST API.

APIGateway.png

It itself is defined in tenpkate.yml in the code.

template.yml


Resources:
  GetHelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub 'awscodestar-${ProjectId}-lambda-GetHelloWorld'
      Handler: com.aws.codestar.projecttemplates.handler.HelloWorldHandler
      Runtime: java8
      Role:
        Fn::GetAtt:
        - LambdaExecutionRole
        - Arn
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /
            Method: get

  PostHelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: !Sub 'awscodestar-${ProjectId}-lambda-PostHelloWorld'
      Handler: com.aws.codestar.projecttemplates.handler.HelloWorldHandler
      Runtime: java8
      Role:
        Fn::GetAtt:
        - LambdaExecutionRole
        - Arn
      Events:
        PostEvent:
          Type: Api
          Properties:
            Path: /
            Method: post

Lambda

There are two, one for Get and one for Post. This is also the content defined in template.yml described in API Gateway.

Lambda1.png

Try moving Pipeline

Try editing springproject / src / main / java / com / aws / codestar / project / handler / HelloWorldHandler.java on Cloud9.

HelloWorldHandler.before java change


return new GatewayResponse(new JSONObject().put("Output", "Hello World!").toString(), headers, 200);

HelloWorldHandler.After changing java


return new GatewayResponse(new JSONObject().put("Output", "Hello World Update!").toString(), headers, 200);

After saving the file, let's push it to CodeCommit from the Cloud9 terminal.

$ git add .
$ git commit -m "update response."
[master f0ba0d6] update response.
 Committer: EC2 Default User <[email protected]>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

    git config --global user.name "Your Name"
    git config --global user.email [email protected]

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

 1 file changed, 1 insertion(+), 1 deletion(-)
$ git push
Enumerating objects: 21, done.
Counting objects: 100% (21/21), done.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (11/11), 719 bytes | 239.00 KiB/s, done.
Total 11 (delta 3), reused 0 (delta 0)
To https://git-codecommit.us-east-1.amazonaws.com/v1/repos/SpringProject
   182e230..f0ba0d6  master -> master

If you look at the pipeline, you can see that the build has started.

build1.png

Actually, I get an error here. When I check it, it seems that the test has failed.

[ERROR] Failures: 
[ERROR]   HelloWorldHandlerTest.testHandleRequest:59 expected: <Hello World!> but was: <Hello World Update!>
[INFO] 
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  10.048 s
[INFO] Finished at: 2020-08-10T14:16:40Z
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.0:test (default-test) on project HelloWorld: There are test failures.
[ERROR] 
[ERROR] Please refer to /codebuild/output/src139859990/src/target/surefire-reports for the individual test results.
[ERROR] Please refer to dump files (if any exist) [date]-jvmRun[N].dump, [date].dumpstream and [date]-jvmRun[N].dumpstream.
[ERROR] -> [Help 1]
[ERROR] 
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR] 
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

[Container] 2020/08/10 14:16:40 Command did not exit successfully mvn clean compile test exit status 1
[Container] 2020/08/10 14:16:40 Phase complete: PRE_BUILD State: FAILED
[Container] 2020/08/10 14:16:40 Phase context status code: COMMAND_EXECUTION_ERROR Message: Error while executing command: mvn clean compile test. Reason: exit status 1

Apparently, the cause is that the test code doesn't match the expected response. So edit springproject / test / java / com / aws / codestar / project / handler / HelloWorldTest.java.

HelloWorldTest.before java change


    private static final String EXPECTED_RESPONSE_VALUE = "Hello World!";

HelloWorldTest.After changing java


    private static final String EXPECTED_RESPONSE_VALUE = "Hello World Update!";
$ git add.
$ git commit -m "update test code."
[master f003591] update test code.
 Committer: EC2 Default User <[email protected]>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

    git config --global user.name "Your Name"
    git config --global user.email [email protected]

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

 1 file changed, 1 insertion(+), 1 deletion(-)
$ git push
Enumerating objects: 21, done.
Counting objects: 100% (21/21), done.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (11/11), 715 bytes | 238.00 KiB/s, done.
Total 11 (delta 2), reused 0 (delta 0)
To https://git-codecommit.us-east-1.amazonaws.com/v1/repos/SpringProject
   f0ba0d6..f003591  master -> master

Next, both Build and Deploy were successful! After accessing the application for a while, the results will change and you can see that the latest application has been deployed.

{"Output":"Hello World Update!"}

Summary

This time, I didn't use the Tokyo region as the region to use Cloud9 as the IDE, but if you use the Git command normally from the code repository, you can also develop with IDEs such as Eclipse and VSS.

The approach of SAM command etc. is to create an environment locally and then Dploy, but in the case of CodeStar, the flow is to first prepare a template on the AWS side and build an application from there. .. To get started more easily, you might want to use CodeStar, which is all-in-one from managing your code repository to your pipeline. This time it was a combination of Lambda + Spring, but since there are many other templates, I am happy to be able to select the project configuration according to the requirements of the application and the skill set of the development members. If possible, I hope Cloud9 will be compatible with the Tokyo region as soon as possible, but even if it is subtracted, it seems to be useful.

Recommended Posts

With [AWS] CodeStar, you can build a Spring (Java) project running on Lambda in just 3 minutes! !!
Create a SlackBot with AWS lambda & API Gateway in Java
Build a Java project with Gradle
Java tips-Create a Spring Boot project in Gradle
Notify the build result with slack with CircleCI. You can do it in 5 minutes.
You can do it right away with Serverless Framework Serverless on AWS (API + Lambda [java] is easy to set up)
Until you build a project described in scala with Maven and execute it with the scala command.
Regularly post imaged tweets on Twitter with AWS Lambda + Java
In Ruby you can define a method with any name
In Redmine you can get the project with Project.find (<identifier>)
Build AWS Lambda with Quarkus
Let's touch on Deep Java Library (DJL), a library that can handle Deep Learning in Java released from AWS.
Try running SlackBot made with Ruby x Sinatra on AWS Lambda
[Gradle] Build a Java project with a configuration different from the convention
Build a Minecraft server on AWS
Is Java on AWS Lambda slow?
Hello World on AWS Lambda + Java
Try running AWS X-Ray in Java
A story about a Spring Boot project written in Java that supports Kotlin
Starting with installing Docker on EC2 and running Yellowfin in a container
I wrote a Lambda function in Java and deployed it with SAM
Build a development environment on AWS EC2 with CentOS7 + Nginx + pm2 + Nuxt.js
I want to ForEach an array with a Lambda expression in Java
Find out if there is a font that can use Japanese (Hiragana, Katakana, Kanji) with AWS Lambda + Java
Try running Word2vec model on AWS Lambda
Create Java Spring Boot project in IntelliJ
AWS Lambda with Java starting now Part 1
Build a Maven repository on AWS S3
Build a Java development environment on Mac
Build Java 8 development environment on AWS Cloud9
Split a string with ". (Dot)" in Java
Build OpenCV with Java Wrapper on Ubuntu 18.04
Working with huge JSON in Java Lambda
Build an environment with Docker on AWS
I built a Java EE environment on AWS and tried running a web application
Hello World, a cross-platform GUI app with Groovy running on the Java platform
Validate the identity token of a user authenticated with AWS Cognito in Java
From creating a Spring Boot project to running an application with VS Code