Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple cloud instance manager based on jclouds
import org.jclouds.ContextBuilder;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.ec2.domain.InstanceType;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;
/**
*
*/
public class InstanceManager {
private final ComputeService computeService;
public InstanceManager() {
ComputeServiceContext context = ContextBuilder.newBuilder("aws-ec2")
.credentials(accessKey(), secretKey())
.buildView(ComputeServiceContext.class);
computeService = context.getComputeService();
}
private String accessKey() {
return credentialsAsProperties().getProperty("accessKey");
}
private String secretKey() {
return credentialsAsProperties().getProperty("secretKey");
}
private Properties credentialsAsProperties() {
Properties properties = new Properties();
try {
properties.load(getClass().getResourceAsStream("/aws/credentials.properties"));
return properties;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void createNode() {
NodeMetadata metadata = createMicroNode(computeService, OsFamily.UBUNTU);
System.out.println("Created node: " + metadata);
}
public void stop() {
computeService.getContext().close();
}
public void printAllAssignableLocations() {
System.out.println("assignable locations: " + computeService.listAssignableLocations());
}
public void printAllNodes() {
Set<? extends ComputeMetadata> nodes = computeService.listNodes();
for (ComputeMetadata node : nodes) {
System.out.println(node.getId() + " : " + node.getName());
System.out.println("Region: " + node.getLocation());
NodeMetadata metadata = computeService.getNodeMetadata(node.getId());
System.out.println("* " + metadata);
}
}
public NodeMetadata createMicroNode(
ComputeService computeService, OsFamily osFamily) {
Template template = computeService.templateBuilder()
.hardwareId(InstanceType.T1_MICRO)
.osFamily(osFamily)
//.fromHardware(new HardwareBuilder().id(Hardware.).is64Bit(true).build())
.build();
try {
return computeService.createNodesInGroup("renatogroup", 1, template).iterator().next();
} catch (RunNodesException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
InstanceManager m = new InstanceManager();
//m.createNode();
m.printAllNodes();
m.stop();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment