Issue
I have a Java program running on the AWS Lambda and an EC2 instance with a jar file.
To execute the jar, I am connecting manually to the instance with ssh:
ssh -i "key.pem" user@instanceDNS
java -cp myJar.jar com.example.Main
Is there any solution for executing this jar programmatically and directly from the Lambda?
Also, if it is a solution to automatically execute this jar every time after the instance has started, it also will be helpful, because I have to start the instance every day, then run this jar and then stop the instance.
This is how I am starting the instance. After it has started, I have to execute jar:
StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
.withInstanceIds(INSTANCE_ID);
ec2Client.startInstances(startInstancesRequest);
After it has started, I have to execute the jar.
Solution
To run a command every time the server boots, you should add this entry to the server's crontab:
@reboot java -cp myJar.jar com.example.Main
You may need to provide the full paths to java, and the jar file in the command. Then your process to start and stop the instance is all that is needed, you will no longer need to automate the process of starting the Java process.
Answered By - Mark B