Skip to content

Instantly share code, notes, and snippets.

@mathieubolla
Created October 19, 2010 16:22
Show Gist options
  • Select an option

  • Save mathieubolla/634493 to your computer and use it in GitHub Desktop.

Select an option

Save mathieubolla/634493 to your computer and use it in GitHub Desktop.
Launches an EC2 micro instance, running a script, which stops it by default. Requires Amazon Java SDK and Apache Commons Codec.
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.RunInstancesRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.codec.binary.Base64;
/**
* This will start an Amazon EC2 micro instance with Ubuntu 10.10 installed
* and terminate it almost immediately. Please provide a properties file path
* instead of sample one, pointing to file with two keys:
* - accessKey=<your_access_key>
* - secretKey=<your_secret_key>
*/
public class EC2Starter {
public static void main(String[] args) throws FileNotFoundException, IOException {
AmazonEC2 service = new AmazonEC2Client(new PropertiesCredentials(new File("/path/to/your/credentials.properties")));
String userData = new Base64().encodeToString("#!/bin/sh\nset -e -x\necho \"Stopping now!\"\nsudo halt\n".getBytes());
service.runInstances(new RunInstancesRequest().//
withInstanceType("t1.micro").//
withMinCount(1).//
withMaxCount(1).//
withImageId("ami-548c783d").//
withInstanceInitiatedShutdownBehavior("terminate").//
withUserData(userData)//
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment