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

6 minute read

CodeStar

AWS CodeStar allows you to build an environment for rapid development and deployment of applications. Several templates are prepared, and you can build a development project simply by clicking on the management console.

Built environment

  • Code repository (choose CodeCommit or GitHub)
  • CodeBuilde environment
  • CodePipeline environment
  • Application
  • IDE (when Cloud9 is selected)

Fee

There is no charge for CodeStar itself. Only the resource usage fee for the code repository built by CodeStar, the pipeline, and the deployed application.

Precautions

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 the environment with Cloud9 this time, we will select Northern Virginia (us-east-1) as the region.

Environment construction procedure

First, select CodeStar from the service in the management console. This time in the IDE I want to use Cloud9, so I’ll set the region to Northern Virginia.

CodeStar1.png

You can select the application type and language. This time, let’s create a project using Lambda + Java Spring template.

CodeStar3.png

Then select the code repository. This time, let’s select Code Commit.

CodeStart4.png

Check the contents and create the project.

Finally select IDE. This time, it is AWS Cloud9. Please note that Cloud9 cannot be selected depending on the region. If you select Cloud9, you will be asked the instance type, so this time keep the default t2.micro.

CodeStar5.png

Project and IDE creation will start (CloudFormation works behind the scenes).

CodeStar6.png

The environment construction is completed in about 3 minutes for the project. Since the IDE has an EC2 instance created, it also takes about 3 minutes. When both are ready, the following screen will appear.

CodeStar7.png

Repository status

Select “Code” from the menu on the left to display the Code Commit screen. Spring template structure has been created, up to buildspec.yml.

CodeCommit1.png

The contents of buildspec.yml look 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 OpenJDK8 is compiled with Maven.

IDE

Now try selecting IDE from the menu. Then, CLoud9 will be started, and the code will be automatically retrieved from the CodeCommit repository by git clone.

CodeCommit1.png

If you set up a team, you can also share code repositories with cross accounts and mob programming.

Create an environment for mob programming with [AWS] Cloud9

Run app

This time, it is an API by Lambda. When you press the “Show app” button on the dashboard, the API included in the project template is called.

{"Output":"Hello World!"}

What about the specific API Gateway and Lambda?

API Gateway

You can see that there is one REST API.

APIGateway.png

This is itself defined in the code tenpkate.yml.

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 the template.yml described in API Gateway.

Lambda1.png

Try running # Pipeline On Cloud9, try editing springproject/src/main/java/com/aws/codestar/project/handler/HelloWorldHandler.java.

HelloWorldHandler.java

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

After changing

HelloWorldHandler.java


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

After saving the file, let’s push 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 check 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 it’s because the test code doesn’t match the expected response. So, edit springproject/test/java/com/aws/codestar/project/handler/HelloWorldTest.java.

HelloWorldTest.java

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

After changing

HelloWorldTest.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/SpringProjectf0ba0d6..f003591 master -> master

Next, Build and Deploy were successful! After accessing the application for a while, the results 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 for the region to use Cloud9 for the IDE, but you can also develop with IDEs such as Eclipse and VSS by using Git commands normally from the code repository.

SAM command etc. is an approach of creating an environment locally and then deploying it, but in the case of CodeStar, first prepare a template on the AWS side and build an application ~ application from there. .. To get started more easily, I think that there is an all-in-one use of CodeStar, from managing code repositories to pipelines. This time it was a combination of Lambda + Spring, but since there are many other templates, I am happy that you can select the project configuration according to the requirements of the application and the skill set of the development members. If possible, I hope that Cloud9 will be compatible with the Tokyo region as soon as possible, but even if it is deducted, it seems to be useful.