Using Java with AWS Lambda-Implementation-Stop / Launch EC2

Thing you want to do

Start / stop EC2 with Java running on Lambda (Try writing ↓ in Java and customize it a little. https://aws.amazon.com/jp/premiumsupport/knowledge-center/start-stop-lambda-cloudwatch/)

Using Java with AWS Lambda Table of Contents

Eclipse Preparation ・ Registration execution (someday) -Implementation-Stop / Start EC2 -Implementation-Check CloudWatch arguments -Implementation Tips --Get Instance Name from Reagion and Instance ID

Create a class for the time being

Since I made it possible to create a sample class in Eclipse last time, Use it to create a Lambda project with input type "Custom". image.png

Here is what you can do with

LambdaFunctionHandler.java


	package com.amazonaws.lambda.demo;

	import com.amazonaws.services.lambda.runtime.Context;
	import com.amazonaws.services.lambda.runtime.RequestHandler;

	public class LambdaFunctionHandler implements RequestHandler<Object, String> {

	    @Override
	    public String handleRequest(Object input, Context context) {
	        context.getLogger().log("Input: " + input);

	        // TODO: implement your handler
	        return "Hello from Lambda!";
	    }
	}

Since the handleRequest method is created, write the content you want to execute with Lambda. See below for handler description https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/java-handler.html You can receive json as an argument. https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/java-handler-pojo.html

Go to EC2

Create an EC2 object

//Create an EC2 object
AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion("us-east-1").build();

Now you can work with EC2 in the argument region. See here for region code https://docs.aws.amazon.com/ja_jp/general/latest/gr/rande.html I won't use it this time, but since Enum is also prepared under the name Regions, the class below can also be used. com.amazonaws.regions.Regions

Launch an instance

//Start the instance ID stored in the argument list
StartInstancesResult ret = ec2.startInstances(new StartInstancesRequest(instanceIdList));

Now you can launch the instance ID in the List.

Stop the instance

//Stop the instance ID stored in the argument list
StopInstancesResult ret = ec2.stopInstances(new StopInstancesRequest(instanceIdList));

You can stop the instance ID of List in the same way as starting. Since AmazonWebServiceResult is inherited by the return value of both start and stop, it can be done as below.

AmazonWebServiceResult<?> ret 

Here is the finished product

Make the argument like ↓ so that you can operate on multiple regions and instances.

{"targets":[
    {
         "action":"start"
        ,"targetReagion":"us-east-1"
        ,"targetInstances":"x-xxxxxxxxxxxxx"
    }
    ,{
         "action":"stop"
        ,"targetReagion":"ap-northeast-1"
        ,"targetInstances":"y-yyyyyyyyyyy"
    }
]}

In the example of this argument, start an instance called x-xxxxxxxxxxxxx in northern Virginia, Stop the y-yyyyyyyyyyy instance in Tokyo.

ActionEC2Instances


package com.amazonaws.lambda.demo;

import java.util.ArrayList;
import java.util.List;

import com.amazonaws.AmazonWebServiceResult;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.StartInstancesRequest;
import com.amazonaws.services.ec2.model.StopInstancesRequest;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

import com.amazonaws.lambda.demo.ActionEC2Instances.Input;
import com.amazonaws.lambda.demo.ActionEC2Instances.Output;

public class ActionEC2Instances implements RequestHandler<Input, Output> {

	@Override
	public Output handleRequest(Input input, Context context) {
		context.getLogger().log("Input : " + input);
		Output output = new Output();

		for (Target action : input.targets) {
			output.result.add(doAction(action));
		}

		return output;
	}

	private String doAction(Target target) {
		AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(target.targetReagion).build();
		List<String> instances = target.targetInstances;

		AmazonWebServiceResult<?> ret = null;
		if ("start".equals(target.action)) {
			ret = ec2.startInstances(new StartInstancesRequest(instances));

		} else if ("stop".equals(target.action)) {
			ret = ec2.stopInstances(new StopInstancesRequest(instances));

		} else {
			return "Unexpected Action";

		}
		return ret.toString();
	}

	public static class Input {
		public List<Target> targets;

		@Override
		public String toString() {
			StringBuffer sbf = new StringBuffer();
			for (Target target : targets) {
				sbf.append(target);
			}
			return sbf.toString();
		}
	}

	public static class Target {

		private String action;
		private String targetReagion;
		private List<String> targetInstances;

		public String getAction() {
			return action;
		}

		public void setAction(String action) {
			this.action = action;
		}

		public String getTargetReagion() {
			return targetReagion;
		}

		public void setTargetReagion(String targetReagion) {
			this.targetReagion = targetReagion;
		}

		public List<String> getTargetInstances() {
			return targetInstances;
		}

		public void setTargetInstances(List<String> targetInstances) {
			this.targetInstances = targetInstances;
		}

		@Override
		public String toString() {
			StringBuffer sbf = new StringBuffer();
			sbf.append("{action :").append(action).append(" targetReagion :").append(targetReagion)
					.append(" targetInstances :").append(targetInstances).append("}");

			return sbf.toString();
		}

	}

	public static class Output {
		public List<String> result = new ArrayList<String>();
	}
}

Added pom

<dependency>
	<groupId>com.amazonaws</groupId>
	<artifactId>aws-java-sdk-core</artifactId>
	<version>1.11.719</version>
</dependency>
<dependency>
	<groupId>com.amazonaws</groupId>
	<artifactId>aws-lambda-java-events</artifactId>
	<version>1.3.0</version>
</dependency>
<dependency>
	<groupId>com.amazonaws</groupId>
	<artifactId>aws-lambda-java-core</artifactId>
	<version>1.1.0</version>
</dependency>
<dependency>
	<groupId>com.amazonaws</groupId>
	<artifactId>aws-java-sdk-ec2</artifactId>
	<version>1.11.602</version>
	<scope>compile</scope>
</dependency>

Recommended Posts

Using Java with AWS Lambda-Implementation-Stop / Launch EC2
Using Java with AWS Lambda-Eclipse Preparation
Using Java with AWS Lambda-Implementation-Check CloudWatch Arguments
Using Mapper with Java (Spring)
Try using Redis with Java (jar)
Html5 development with Java using TeaVM
Using proxy service with Java crawling
Until INSERT S3 object into EC2 DB with Lambda @ java: AWS
Deployed using Docker + Rails + AWS (EC2 + RDS)
Easy deployment with Capistrano + AWS (EC2) + Rails
Using JupyterLab + Java with WSL on Windows 10
AWS Lambda with Java starting now Part 1
Game development with two people using java 2
I tried using OpenCV with Java + Tomcat
Game development with two people using java 1
Try managing Java libraries with AWS CodeArtifact
Launch java verification environment locally with Vagrant
Game development with two people using java 3
Try using the Wii remote with Java
Using Java with AWS Lambda-Implementation Tips-Get Instance Name from Reagion and Instance ID
Interact with LINE Message API using Lambda (Java)
How to use Java framework with AWS Lambda! ??
Specify ClassPath when using jupyter + Java with WSL
Using Gradle with VS Code, build Java → run
Set a signed cookie (for CloudFront) with a custom policy using the AWS SDK for Java
Using Java 8 with Bluemix (on Liberty Runtime & DevOps Service)
Getting started with Java programs using Visual Studio Code
Submit a job to AWS Batch with Java (Eclipse)
How to deploy Java to AWS Lambda with Serverless Framework
Deploy laravel using docker on EC2 on AWS ① (Create EC2 instance)
I tried to operate SQS using AWS Java SDK
[Java] Development with multiple files using package and import
Install java with Homebrew
Sorting using java comparator
Launch Rails on EC2
Change seats with java
Install Java with Ansible
Using Pair with OpenJDK
Launch MariaDB with Docker
Comfortable download with JAVA
Scraping practice using Java ②
Switch java with direnv
AWS SSM Agent Launch
Scraping practice using Java ①
Download Java with Ansible
Let's scrape with Java! !!
Build Java with Wercker
Endian conversion with JAVA
Deploy laravel using docker on EC2 on AWS ② (Elastic IP acquisition-linking)
Regularly post imaged tweets on Twitter with AWS Lambda + Java
Log aggregation and analysis (working with AWS Athena in Java)
Using multiple versions of Java with Brew on Mac + jEnv
Register your own Docker image with ECR using AWS CLI
Deploy laravel using docker on EC2 on AWS ④ (git clone ~ deploy, migration)
Create a SlackBot with AWS lambda & API Gateway in Java
I tried automatic deployment with CircleCI + Capistrano + AWS (EC2) + Rails
Problems with Dijkstra's algorithm using PriorityQueue and adjacency list (java)
Socket communication with a web browser using Java and JavaScript ②
Try Spark Submit to EMR using AWS SDK for Java
Socket communication with a web browser using Java and JavaScript ①
I tried using the CameraX library with Android Java Fragment