AWS Java API - Create EC2 (runInstances) and execute command

907 views Asked by At

I am able to easily create instances using the AWS Java API from a snapshot that I have created in the environment using runInstances(...). I have the snapshot set up in such a way that it auto-launches a set of processes and other things so that I have a fully functional configuration.

What I would like to do, is have the instance automatically run a command I configure and set a launch time WITHOUT POLLING. Is there any functionality to do this?

Right now I am polling for when it becomes available using the Java Secure Channel library; however, I would prefer to not have to worry about it and just let AWS handle it if at all possible.

The command changes at launch time depending on how/when things run, so I may need to execute a command such as:

SomeBashScript.sh -e SOME_ID some_command
1

There are 1 answers

2
el n00b On BEST ANSWER

The API for creating instances has the following method available on it on the RunInstancesRequest class which I am using to launch the data:

public void setUserData(String userData)

This covers exactly what @birryee was saying in the User Guide.

My sample application is therefore using the following Java code in order to get things launched:

// create the actual request
RunInstancesRequest request = new RunInstancesRequest();
request.withMinCount(1).withMaxCount(count);
request.withKeyName("TheOwner");
request.withSecurityGroups("SSH");
request.withInstanceType(InstanceType.T2Micro);
request.withImageId("MyImageID");
request.withRegion(Region.getRegion(Regions.US_EAST_1));

// add a web hook call to notify us when the instance is launched
request.withUserData("#!/bin/bash\ncurl -X POST http://domain.com/email-me");

// launch it
RunInstancesResult awsResponse = awsClient.runInstances(request);