Example usage for com.amazonaws.services.ec2.model RunInstancesRequest withImageId

List of usage examples for com.amazonaws.services.ec2.model RunInstancesRequest withImageId

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2.model RunInstancesRequest withImageId.

Prototype


public RunInstancesRequest withImageId(String imageId) 

Source Link

Document

The ID of the AMI.

Usage

From source file:EC2LaunchWaitTerminate.java

License:Open Source License

public static void main(String[] args) throws Exception {

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS Java SDK!");
    System.out.println("===========================================");

    init();//from   ww  w  . j av  a 2  s  .com

    /*
     * Amazon EC2
     *
     * The AWS EC2 client allows you to create, delete, and administer
     * instances programmatically.
     *
     * In this sample, we use an EC2 client to get a list of all the
     * availability zones, and all instances sorted by reservation id, then 
     * create an instance, list existing instances again, wait a minute and 
     * the terminate the started instance.
     */
    try {
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");
        /* using AWS Ireland. 
         * TODO: Pick the zone where you have your AMI, sec group and keys */
        ec2.setEndpoint("ec2.us-west-2.amazonaws.com");
        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();

        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        System.out.println("Starting a new instance.");
        RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

        /* TODO: configure to use your AMI, key and security group */
        runInstancesRequest.withImageId("ami-ede6128d").withInstanceType("t2.micro").withMinCount(1)
                .withMaxCount(1).withKeyName("CNV-lab-AWS").withSecurityGroups("CNV-ssh+http");
        RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
        String newInstanceId = runInstancesResult.getReservation().getInstances().get(0).getInstanceId();
        describeInstancesRequest = ec2.describeInstances();
        reservations = describeInstancesRequest.getReservations();
        instances = new HashSet<Instance>();

        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");
        System.out.println("Waiting 4 minutes. See your instance in the AWS console...");
        Thread.sleep(60000 * 4);
        System.out.println("Terminating the instance.");
        TerminateInstancesRequest termInstanceReq = new TerminateInstancesRequest();
        termInstanceReq.withInstanceIds(newInstanceId);
        ec2.terminateInstances(termInstanceReq);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }
}

From source file:virtualIT.java

License:Open Source License

private void runInstance(String keyName, String securityGroupName, int instanceCount, String availableZone)
        throws Exception {
    /*********************************************
      * /*from   w w  w . ja  va2s.  c  om*/
      *  #6 Create an Instance
      *  
      *********************************************/
    System.out.println("#5 Create an Instance");
    String imageId = "ami-ab844dc2";//Basic 32-bit Amazon Linux AMI
    String instanceType = "t1.micro";
    int minInstanceCount = instanceCount; // create 1 instance
    int maxInstanceCount = instanceCount;
    Placement placement = new Placement(availableZone);
    RunInstancesRequest instanceRun = new RunInstancesRequest();
    instanceRun.withImageId(imageId).withInstanceType(instanceType).withMinCount(minInstanceCount)
            .withMaxCount(maxInstanceCount).withKeyName(keyName).withPlacement(placement)
            .withSecurityGroups(securityGroupName);

    RunInstancesResult result = ec2.runInstances(instanceRun);

    Thread.currentThread();
    Thread.sleep(100000);

}

From source file:virtualIT.java

License:Open Source License

private void StartUsingOldAmi(int userId) throws Exception {
    /*Run instances */
    String imageId = mapUserImage.get(userId);
    System.out.println("Old Instance");
    Placement placement = new Placement(availableZone);
    RunInstancesRequest instanceRun = new RunInstancesRequest();
    instanceRun.withImageId(imageId).withInstanceType("t1.micro").withMinCount(1).withMaxCount(1)
            .withPlacement(placement).withKeyName(keyName).withSecurityGroups(securityGroupName);
    RunInstancesResult result = ec2.runInstances(instanceRun);
    describeCurrentInstances(userId);/*from   w  w  w .  jav a2s  .c o  m*/
    AttachVolume(userId);
}

From source file:AwsSample.java

License:Open Source License

public static void main(String[] args) throws Exception {

    AWSCredentials credentials = new PropertiesCredentials(
            AwsSample.class.getResourceAsStream("AwsCredentials.properties"));

    /*********************************************
     * /*from   w w w. j ava 2 s  .  com*/
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);

    /*********************************************
     * Added By Chenyun Zhang
     *  # Create an Amazon EC2 Security Group
     *  
     *********************************************/
    System.out.println("#1 Create an Amazon EC2 Security Group");
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();

    createSecurityGroupRequest.withGroupName("JavaSecurityGroup").withDescription("My Java Security Group");

    CreateSecurityGroupResult createSecurityGroupResult = ec2.createSecurityGroup(createSecurityGroupRequest);

    /*********************************************
     * Added By Chenyun Zhang
     *  # Authorize Security Group Ingress
     *  
     *********************************************/
    System.out.println("#2 Authorize Security Group Ingress");

    ArrayList<IpPermission> ipPermission = new ArrayList<IpPermission>();

    //SSH
    IpPermission ipssh = new IpPermission();
    ipssh.setIpProtocol("tcp");
    ipssh.setFromPort(new Integer(22));
    ipssh.setToPort(new Integer(22));
    //ipssh.withIpRanges(ipRanges);
    ipssh.withIpRanges("72.69.22.123/32");
    ipPermission.add(ipssh);

    //HTTP
    IpPermission iphttp = new IpPermission();

    iphttp.setIpProtocol("tcp");
    iphttp.setFromPort(new Integer(80));
    iphttp.setToPort(new Integer(80));
    iphttp.withIpRanges("0.0.0.0/0");
    ipPermission.add(iphttp);

    //TCP
    IpPermission iptcp = new IpPermission();
    iptcp.setIpProtocol("tcp");
    iptcp.setFromPort(new Integer(49152));
    iptcp.setToPort(new Integer(49152));
    iptcp.withIpRanges("0.0.0.0/0");
    ipPermission.add(iptcp);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();

    authorizeSecurityGroupIngressRequest.withGroupName("JavaSecurityGroup").withIpPermissions(ipPermission);

    ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    /*********************************************
     * Added By Chenyun Zhang
     *  # Create a Key Pair
     *  
     *********************************************/
    System.out.println("#3 Create a Key Pair");

    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();

    createKeyPairRequest.withKeyName("HW2");

    CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);

    KeyPair keyPair = new KeyPair();

    keyPair = createKeyPairResult.getKeyPair();

    String privateKey = keyPair.getKeyMaterial();

    //Calling createKeyPair is the only way to obtain the private key programmatically.
    /*********************************************
     * Added By Chenyun Zhang
     *  # Download KeyPair
     *  
     *********************************************/
    PrintWriter Storekey = new PrintWriter(
            "/Users/Annabelle/Documents/NYU-POLY/3/Cloud Computing/HW2" + "/" + "Hw2" + ".pem", "UTF-8");
    Storekey.print(privateKey);
    Storekey.close();
    System.out.println("Already store the key!");

    try {

        /*********************************************
         * 
          *  #2 Describe Availability Zones.
          *  
          *********************************************/
        System.out.println("#2 Describe Availability Zones.");
        DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
        System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size()
                + " Availability Zones.");

        /*********************************************
         * 
         *  #3 Describe Available Images
         *  
         *********************************************/
        System.out.println("#3 Describe Available Images");
        DescribeImagesResult dir = ec2.describeImages();
        List<Image> images = dir.getImages();
        System.out.println("You have " + images.size() + " Amazon images");

        /*********************************************
         *                 
         *  #4 Describe Key Pair
         *                 
         *********************************************/
        System.out.println("#9 Describe Key Pair");
        DescribeKeyPairsResult dkr = ec2.describeKeyPairs();
        System.out.println(dkr.toString());

        /*********************************************
         * 
         *  #5 Describe Current Instances
         *  
         *********************************************/
        System.out.println("#4 Describe Current Instances");
        DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
        List<Reservation> reservations = describeInstancesRequest.getReservations();
        Set<Instance> instances = new HashSet<Instance>();
        // add all instances to a Set.
        for (Reservation reservation : reservations) {
            instances.addAll(reservation.getInstances());
        }

        System.out.println("You have " + instances.size() + " Amazon EC2 instance(s).");
        for (Instance ins : instances) {

            // instance id
            String instanceId = ins.getInstanceId();

            // instance state
            InstanceState is = ins.getState();
            System.out.println(instanceId + " " + is.getName());
        }

        /*********************************************
         * 
         *  #6 Create an Instance
         *  
         *********************************************/
        System.out.println("#5 Create an Instance");
        String imageId = "ami-76f0061f"; //Basic 64-bit Amazon Linux AMI
        int minInstanceCount = 1; // create 1 instance
        int maxInstanceCount = 1;
        //RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        RunInstancesRequest rir = new RunInstancesRequest();
        rir.withImageId(imageId).withInstanceType("t1.micro").withMinCount(minInstanceCount)
                .withMaxCount(maxInstanceCount).withKeyName("HW2").withSecurityGroups("JavaSecurityGroup");
        RunInstancesResult result = ec2.runInstances(rir);

        /*********************************************
         * Added by Chenyun Zhang
         *  # Get the public Ip address
         *  
         *********************************************/
        //get instanceId from the result
        List<Instance> resultInstance = result.getReservation().getInstances();
        String createdInstanceId = null;
        for (Instance ins : resultInstance) {
            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());

            //DescribeInstancesRequest and get ip
            String createdInstanceIp = null;
            while (createdInstanceIp == null) {
                System.out.println("Please waiting for 10 seconds!");
                Thread.sleep(10000);

                DescribeInstancesRequest newdescribeInstances = new DescribeInstancesRequest();
                DescribeInstancesResult newdescribeInstancesRequest = ec2
                        .describeInstances(newdescribeInstances);
                List<Reservation> newreservations = newdescribeInstancesRequest.getReservations();
                Set<Instance> allinstances = new HashSet<Instance>();
                for (Reservation reservation : newreservations) {
                    allinstances.addAll(reservation.getInstances());
                }

                for (Instance myinst : allinstances) {
                    String instanceId = myinst.getInstanceId();
                    if (instanceId.equals(createdInstanceId)) {
                        createdInstanceIp = myinst.getPublicIpAddress();
                    }
                }

            }
            System.out.println("Already get the Ip!");
            System.out.println("New instance's ip address is:" + createdInstanceIp);
            IP = createdInstanceIp;
        }

        /*********************************************
         * 
         *  #7 Create a 'tag' for the new instance.
         *  
         *********************************************/
        System.out.println("#6 Create a 'tag' for the new instance.");
        List<String> resources = new LinkedList<String>();
        List<Tag> tags = new LinkedList<Tag>();
        Tag nameTag = new Tag("Name", "MyFirstInstance");

        resources.add(createdInstanceId);
        tags.add(nameTag);

        CreateTagsRequest ctr = new CreateTagsRequest(resources, tags);
        ec2.createTags(ctr);

        /*********************************************
         *  Added By Chenyun Zhang
         *  # SSH connect into EC2
         *  
         *********************************************/

        Thread.sleep(100000);
        ssh con = new ssh();
        con.sshcon(IP);

        /*********************************************
         * 
         *  #8 Stop/Start an Instance
         *  
         *********************************************/
        System.out.println("#7 Stop the Instance");
        List<String> instanceIds = new LinkedList<String>();
        instanceIds.add(createdInstanceId);

        //stop
        StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds);
        //ec2.stopInstances(stopIR);

        //start
        StartInstancesRequest startIR = new StartInstancesRequest(instanceIds);
        //ec2.startInstances(startIR);

        /*********************************************
         * 
         *  #9 Terminate an Instance
         *  
         *********************************************/
        System.out.println("#8 Terminate the Instance");
        TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);
        //ec2.terminateInstances(tir);

        /*********************************************
         *  
         *  #10 shutdown client object
         *  
         *********************************************/
        ec2.shutdown();

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:InstallYarn.java

License:Open Source License

public static void main(String[] args) throws JSchException, IOException, InterruptedException {

    /*/* ww w.  ja  v a2s.  c  om*/
     * The ProfileCredentialsProvider will return your [default]
     * credential profile by reading from the credentials file located at
     * (C:\\Users\\CH\\.aws\\credentials).
     */

    AWSCredentials credentials = null;
    try {
        credentials = new BasicAWSCredentials("Your Access Key ID", "Your Secret Access Key");

    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (C:\\Users\\CH\\.aws\\credentials), and is in valid format.", e);
    }

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    ec2.setRegion(usWest2);

    /*
    // Create a new security group.
    try {
    CreateSecurityGroupRequest securityGroupRequest = new CreateSecurityGroupRequest(
            "GettingStartedGroup", "Getting Started Security Group");
    CreateSecurityGroupResult result = ec2
            .createSecurityGroup(securityGroupRequest);
    System.out.println(String.format("Security group created: [%s]",
            result.getGroupId()));
    } catch (AmazonServiceException ase) {
    // Likely this means that the group is already created, so ignore.
    System.out.println(ase.getMessage());
    }
            
    String ipAddr = "0.0.0.0/0";
            
    // Get the IP of the current host, so that we can limit the Security Group
    // by default to the ip range associated with your subnet.
    try {
    InetAddress addr = InetAddress.getLocalHost();
            
    // Get IP Address
    ipAddr = addr.getHostAddress()+"/10";
    } catch (UnknownHostException e) {
    }
            
    // Create a range that you would like to populate.
    List<String> ipRanges = Collections.singletonList(ipAddr);
            
    // Open up port 23 for TCP traffic to the associated IP from above (e.g. ssh traffic).
    IpPermission ipPermission = new IpPermission()
        .withIpProtocol("tcp")
        .withFromPort(new Integer(22))
        .withToPort(new Integer(22))
        .withIpRanges(ipRanges);
            
    List<IpPermission> ipPermissions = Collections.singletonList(ipPermission);
            
    try {
    // Authorize the ports to the used.
    AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(
            "GettingStartedGroup", ipPermissions);
    ec2.authorizeSecurityGroupIngress(ingressRequest);
    System.out.println(String.format("Ingress port authroized: [%s]",
            ipPermissions.toString()));
    } catch (AmazonServiceException ase) {
    // Ignore because this likely means the zone has already been authorized.
    System.out.println(ase.getMessage());
    }
    */
    //CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
    //.withKeyName("CHENHAO");

    //CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);

    //KeyPair keyPair = new KeyPair();
    //keyPair = createKeyPairResult.getKeyPair();
    //String privateKey = keyPair.getKeyMaterial();

    int cluster_size = Integer
            .parseInt(JOptionPane.showInputDialog("Enter number of machines you want to set"));
    String ami_name = JOptionPane.showInputDialog("Enter your ami name");
    String key_name = JOptionPane.showInputDialog("Enter your key name");
    String s_group_name = JOptionPane.showInputDialog("Enter your security group name");

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.withImageId(ami_name).withInstanceType("t2.micro").withMinCount(cluster_size)
            .withMaxCount(cluster_size).withKeyName(key_name).withSecurityGroups(s_group_name);

    RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);

    Thread.sleep(10000);

    Vector<String> instanceId = new Vector<String>();
    for (Instance ins : runInstancesResult.getReservation().getInstances())
        instanceId.add(ins.getInstanceId());

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(instanceId);
    DescribeInstancesResult result = ec2.describeInstances(request);
    List<Reservation> reservations = result.getReservations();

    List<Instance> instances_list = new Vector<Instance>();
    for (int i = 0; i < reservations.size(); i++)
        instances_list.addAll(reservations.get(i).getInstances());

    System.out.println("Plan cluster size:" + cluster_size + " Real size:" + instances_list.size());

    JSch jsch = new JSch();
    JFileChooser chooser = new JFileChooser();
    chooser.setDialogTitle("Choose your privatekey");
    chooser.setFileHidingEnabled(false);
    int returnVal = chooser.showOpenDialog(null);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        System.out.println("You chose " + chooser.getSelectedFile().getAbsolutePath() + ".");
        jsch.addIdentity(chooser.getSelectedFile().getAbsolutePath());
    }

    Session session;
    UserInfo ui = new MyUserInfo();
    for (int i = 0; i < instances_list.size(); i++) {
        if (instances_list.get(i).getPublicIpAddress() == null)
            System.out.println("Error, public ip is null\n");

        System.out.println("Connect to:" + instances_list.get(i).getPublicIpAddress() + "\n");
        session = jsch.getSession("ubuntu", instances_list.get(i).getPublicIpAddress(), 22);
        session.setUserInfo(ui);
        session.connect();

        //
        //if(i==0)
        //{
        //  transfer_file_to("/home/ubuntu","C:/Users/CH/Downloads/ch.pem",session);
        // exec("chmod 400 /home/ubuntu/ch.pem",session);
        //}

        //slaves file
        for (int j = 0; j < instances_list.size(); j++) {
            if (j != 0)
                exec("echo " + instances_list.get(j).getPrivateIpAddress()
                        + "\n >> /usr/local/hadoop/etc/hadoop/slaves", session);
        }
        //core-site file
        String command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        //hdfs-size file
        command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        command = "sed -i 's#replication#" + Integer.toString(cluster_size - 1)
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        //yarn-size file
        command = "sed -i 's#Master#" + instances_list.get(0).getPrivateIpAddress()
                + "#g' /usr/local/hadoop/etc/hadoop/core-site.xml";
        exec(command, session);

        session.disconnect();
    }

    //username and passphrase will be given via UserInfo interface.

    //slaves file

}

From source file:EC2InstanceLaunch.java

License:Open Source License

private static String createInstance(String imageId, String instanceType, int minInstanceCount,
        int maxInstanceCount, String keyName, String groupName) {
    /*//from  w  ww .ja va2 s  . c  o  m
    * http://docs.aws.amazon.com/AWSSdkDocsJava/latest//DeveloperGuide/run-instance.html
    */

    System.out.println("# Create an Instance");

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.withImageId(imageId).withInstanceType(instanceType).withMinCount(minInstanceCount)
            .withMaxCount(maxInstanceCount).withKeyName(keyName).withSecurityGroups(groupName);

    RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
    // get instanceId from the result
    List<Instance> resultInstance = runInstancesResult.getReservation().getInstances();
    String createdInstanceId = null;
    for (Instance ins : resultInstance) {
        createdInstanceId = ins.getInstanceId();
        System.out.println("New instance(s) has been created: " + createdInstanceId);
    }
    return createdInstanceId;
}

From source file:Assignment1.java

License:Open Source License

public static void main(String[] args) throws Exception {

    AWSCredentials credentials = new PropertiesCredentials(
            Assignment1.class.getResourceAsStream("AwsCredentials.properties"));

    /*********************************************
     *  #1 Create Amazon Client object//from   ww w  .  j  a  va2  s.  c o m
     **********************************************/
    ec2 = new AmazonEC2Client(credentials);

    // We assume that we've already created an instance. Use the id of the instance.
    //String instanceId = "i-4e6c2a3d"; //put your own instance id to test this code.

    try {

        CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest();

        createSecurityGroupRequest.withGroupName("mini").withDescription("My Java Security Group");

        CreateSecurityGroupResult createSecurityGroupResult = ec2
                .createSecurityGroup(createSecurityGroupRequest);

        IpPermission ipPermission = new IpPermission();

        ipPermission.withIpRanges("0.0.0.0/0", "150.150.150.150/32").withIpProtocol("tcp").withFromPort(22)
                .withToPort(22);
        AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest();

        authorizeSecurityGroupIngressRequest.withGroupName("mini").withIpPermissions(ipPermission);
        ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

        CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest();

        createKeyPairRequest.withKeyName("E3instance_key");

        CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest);

        KeyPair keyPair = new KeyPair();
        keyPair = createKeyPairResult.getKeyPair();

        String privateKey = keyPair.getKeyMaterial();

        System.out.print(privateKey);

        /*********************************************
         *                 
         *  #1.1 Describe Key Pair
         *                 
         *********************************************/
        System.out.println("\n#1.1 Describe Key Pair");
        DescribeKeyPairsResult dkr = ec2.describeKeyPairs();
        System.out.println(dkr.toString());

        /*********************************************
         * 
         *  #1.2 Create an Instance
         *  
         *********************************************/

        RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

        runInstancesRequest.withImageId("ami-ab844dc2").withInstanceType("t1.micro").withMinCount(2)
                .withMaxCount(2).withKeyName("E3instance_key").withSecurityGroups("mini");
        RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);

        System.out.println("\n#1.2 Create an Instance");

        List<Instance> resultInstance = runInstancesResult.getReservation().getInstances();

        String createdInstanceId = null;

        for (Instance ins : resultInstance) {
            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());
        }

        String myinstanceZone = resultInstance.get(0).getPlacement().getAvailabilityZone();
        String myinstanceZone1 = resultInstance.get(1).getPlacement().getAvailabilityZone();
        String myinstanceID = resultInstance.get(0).getInstanceId();
        String myinstanceID1 = resultInstance.get(1).getInstanceId();

        Thread.sleep(1000 * 1 * 60);

        /*********************************************
         *  #2.1 Create a volume
         *********************************************/
        //create a volume
        CreateVolumeRequest cvr = new CreateVolumeRequest();
        CreateVolumeRequest cvr1 = new CreateVolumeRequest();
        cvr.setAvailabilityZone(myinstanceZone);
        cvr1.setAvailabilityZone(myinstanceZone1);
        cvr.setSize(10); //size = 10 gigabytes
        cvr1.setSize(10);
        CreateVolumeResult volumeResult = ec2.createVolume(cvr);
        CreateVolumeResult volumeResult1 = ec2.createVolume(cvr1);
        String createdVolumeId = volumeResult.getVolume().getVolumeId();
        String createdVolumeId1 = volumeResult1.getVolume().getVolumeId();
        String[] volumeID = new String[2];
        volumeID[0] = createdVolumeId;
        volumeID[1] = createdVolumeId1;
        System.out.println("\n#2.1 Create a volume for each instance");

        Thread.sleep(1000 * 1 * 60);
        /*********************************************
         *  #2.2 Attach the volume to the instance
         *********************************************/
        AttachVolumeRequest avr = new AttachVolumeRequest();
        AttachVolumeRequest avr1 = new AttachVolumeRequest();
        avr.setInstanceId(myinstanceID);
        avr1.setInstanceId(myinstanceID1);
        avr.setVolumeId(createdVolumeId);
        avr1.setVolumeId(createdVolumeId1);
        avr.setDevice("/dev/sda2");
        avr1.setDevice("/dev/sda2");
        //avr.setVolumeId(createdVolumeId);
        //avr.setInstanceId(createdInstanceId);
        //avr.setDevice("/dev/sdf");
        ec2.attachVolume(avr);
        ec2.attachVolume(avr1);
        System.out.println("\n#2.2 Attach the volume");
        System.out.println("EBS volume has been attached and the volume ID is: " + createdVolumeId);
        System.out.println("EBS volume has been attached and the volume ID is: " + createdVolumeId1);

        Thread.sleep(1000 * 2 * 60);
        /***********************************
        *   #2.3 Monitoring (CloudWatch)
        *********************************/

        //create CloudWatch client
        AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials);

        //create request message
        GetMetricStatisticsRequest statRequest = new GetMetricStatisticsRequest();

        //set up request message
        statRequest.setNamespace("AWS/EC2"); //namespace
        statRequest.setPeriod(60); //period of data
        ArrayList<String> stats = new ArrayList<String>();

        //Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum 
        stats.add("Average");
        stats.add("Sum");
        statRequest.setStatistics(stats);

        //Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations  
        statRequest.setMetricName("CPUUtilization");

        // set time
        GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
        calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago
        Date endTime = calendar.getTime();
        calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago
        Date startTime = calendar.getTime();
        statRequest.setStartTime(startTime);
        statRequest.setEndTime(endTime);

        //specify an instance
        ArrayList<Dimension> dimensions = new ArrayList<Dimension>();

        String monitorInstanceId = null;
        int i = 0;
        String[] idleInstance = new String[2];

        for (Instance ins : resultInstance) {
            monitorInstanceId = ins.getInstanceId();
            dimensions.add(new Dimension().withName("InstanceId").withValue(monitorInstanceId));
            statRequest.setDimensions(dimensions);

            Thread.sleep(1000 * 3 * 60);
            //get statistics
            GetMetricStatisticsResult statResult = cloudWatch.getMetricStatistics(statRequest);

            //display
            System.out.println(statResult.toString());
            List<Datapoint> dataList = statResult.getDatapoints();
            Double averageCPU = null;
            Date timeStamp = null;
            for (Datapoint data : dataList) {
                averageCPU = data.getAverage();
                timeStamp = data.getTimestamp();
                System.out.println("Average CPU utlilization for last 1 minutes: " + averageCPU);
                //System.out.println("Total CPU utlilization for last 1 minutes: "+data.getSum());

                //Calendar vmTime=GregorianCalendar.getInstance();
                //vmTime.setTime(timeStamp);
                //vmTime.get(Calendar.HOUR_OF_DAY);
                if (averageCPU < 50 && i < 2) {
                    idleInstance[i] = monitorInstanceId;
                    i++;
                }
            }

        }
        System.out.println("\n" + i + " instance(s) idling.");
        /*********************************************
         *  #2.4 Detach the volume from the instance 
         *********************************************/

        DetachVolumeRequest dvr = new DetachVolumeRequest();
        DetachVolumeRequest dvr1 = new DetachVolumeRequest();
        dvr.setVolumeId(createdVolumeId);
        dvr1.setVolumeId(createdVolumeId1);
        dvr.setInstanceId(myinstanceID);
        dvr1.setInstanceId(myinstanceID1);
        dvr.setDevice("/dev/sda2");
        dvr1.setDevice("/dev/sda2");
        ec2.detachVolume(dvr);
        ec2.detachVolume(dvr1);
        System.out.println("\n#2.4 Detach the volume");

        Thread.sleep(1000 * 1 * 60);

        /*********************************************
          *  #2.5 Create new AMI for idle instance
          *********************************************/
        String[] idleAMIID = new String[2];
        int j = 0;
        for (j = 0; j < idleInstance.length; j++) {
            CreateImageRequest Im = new CreateImageRequest(idleInstance[j], "image" + j);

            //CreateImageRequest Im1=new CreateImageRequest(myinstanceID1, "image1");
            Im.setInstanceId(idleInstance[j]);
            //Im1.setInstanceId(myinstanceID1);

            CreateImageResult myAMI = ec2.createImage(Im);
            idleAMIID[j] = myAMI.getImageId();

            //CreateImageResult myAMI1= ec2.createImage(Im1); 
            System.out.println("\n#2.5 Create new AMI");
        }
        Thread.sleep(1000 * 1 * 60);
        /*********************************************
          * 
          *  # Terminate an Instance
          *  
          *********************************************/
        //System.out.println("#8 Terminate the Instance");

        // TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds);

        //ec2.terminateInstances(tir);
        /*********************************************
          *  #2.6 Create new VMs
          *********************************************/
        RunInstancesRequest runNewInstancesRequest = new RunInstancesRequest();
        int m;
        String[] newCreatedInstanceId = new String[2];
        for (m = 0; m < j; m++)//j is the number of AMI created
        {
            runNewInstancesRequest.withImageId(idleAMIID[m]).withInstanceType("t1.micro").withMinCount(1)
                    .withMaxCount(1).withKeyName("E3instance_key").withSecurityGroups("mini");
            RunInstancesResult runNewInstancesResult = ec2.runInstances(runNewInstancesRequest);
            List<Instance> newResultInstance = runNewInstancesResult.getReservation().getInstances();

            String newInstanceId = null;

            for (Instance ins : newResultInstance) {
                newInstanceId = ins.getInstanceId();
            }
            newCreatedInstanceId[m] = newInstanceId;
            System.out.println("Using AMI, a new instance has been created: " + newCreatedInstanceId[m]);

        }
        Thread.sleep(1000 * 1 * 60);
        //System.out.println("\n#2.6 Create "+ m + " instance using AMI");

        /*********************************************
          *  #2.7 Attach the volume to the new instance
          *********************************************/
        int n;
        for (n = 0; n < idleInstance.length; n++) {
            AttachVolumeRequest new_avr = new AttachVolumeRequest();
            //AttachVolumeRequest new_avr1 = new AttachVolumeRequest();
            new_avr.setInstanceId(newCreatedInstanceId[n]);
            //avr1.setInstanceId(myinstanceID1);
            new_avr.setVolumeId(volumeID[n]);
            //avr1.setVolumeId(createdVolumeId1);
            new_avr.setDevice("/dev/sda2");
            //avr1.setDevice("/dev/sda2");
            //avr.setVolumeId(createdVolumeId);
            //avr.setInstanceId(createdInstanceId);
            //avr.setDevice("/dev/sdf");
            ec2.attachVolume(new_avr);
            //ec2.attachVolume(avr1);
            System.out.println("\n#2.7 Re-attach the volume");
            System.out.println("EBS volume has been attached and the volume ID is: " + volumeID[n]);
            //System.out.println("EBS volume has been attached and the volume ID is: "+createdVolumeId1);

            Thread.sleep(1000 * 1 * 60);
        }
        /************************************************
        *    #3 S3 bucket and object
        ***************************************************/
        s3 = new AmazonS3Client(credentials);

        //create bucket
        String bucketName = "lucinda.duan";
        s3.createBucket(bucketName);

        //set key
        String key = "object-name.txt";

        //set value
        File file = File.createTempFile("temp", ".txt");
        file.deleteOnExit();
        Writer writer = new OutputStreamWriter(new FileOutputStream(file));
        writer.write("This is a sample sentence.\r\nYes!");
        writer.close();

        //put object - bucket, key, value(file)
        s3.putObject(new PutObjectRequest(bucketName, key, file));

        //get object
        S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
        BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent()));
        String data = null;
        while ((data = reader.readLine()) != null) {
            System.out.println(data);
        }

        /*********************************************
         *  #4 shutdown client object
         *********************************************/
        // ec2.shutdown();
        // s3.shutdown();

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:agentcoordinator.AgentCoordinator.java

private void launchAdditionalInstances(int numberOfInstance) {
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

    runInstancesRequest.withImageId("ami-84c36bf3").withInstanceType("t2.micro").withMinCount(numberOfInstance)
            .withMaxCount(numberOfInstance).withSubnetId("subnet-a020fac5")
            .withKeyName("14 _LP1_KEY_ D7001D_CHASAT-4").withSecurityGroupIds("sg-cbc665ae")
            .withMonitoring(true);/*  w w  w .  j a  va 2s .c om*/
    RunInstancesResult runInstancesResult = amazonEC2Client.runInstances(runInstancesRequest);

    Reservation myReservation = runInstancesResult.getReservation();
    List<Instance> instanceList = myReservation.getInstances();
    for (int i = 0; i < instanceList.size(); i++) {
        Instance instance = instanceList.get(i);
        instanceIDList.add(instance.getInstanceId()); //add to our list of instances ID
        //then tag them for easy finding
        CreateTagsRequest createTagsRequest = new CreateTagsRequest();
        createTagsRequest.withResources(instance.getInstanceId())
                .withTags(new Tag("Name", "SCAgent-TeamAsia-" + i));
        amazonEC2Client.createTags(createTagsRequest);
    }

}

From source file:com.hazelcast.simulator.provisioner.AwsProvisioner.java

License:Open Source License

private List<Instance> createInstances(int instanceCount) {
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.withImageId(awsAmi).withInstanceType(awsBoxId).withMinCount(instanceCount)
            .withMaxCount(instanceCount).withKeyName(awsKeyName);

    if (subNetId.isEmpty()) {
        runInstancesRequest.withSecurityGroups(securityGroup);
    } else {/*from w w w. jav  a2 s. c  o  m*/
        runInstancesRequest.withSubnetId(subNetId);
    }

    RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);

    List<Instance> checkedInstances = new ArrayList<Instance>();
    List<Instance> instances = runInstancesResult.getReservation().getInstances();
    for (Instance instance : instances) {
        if (waitForInstanceStatusRunning(instance)) {
            addInstanceToAgentsFile(instance);
            checkedInstances.add(instance);
            componentRegistry.addAgent(instance.getPublicIpAddress(), instance.getPrivateIpAddress());
        } else {
            LOGGER.warn("Timeout waiting for running status id=" + instance.getInstanceId());
        }
    }
    return checkedInstances;
}

From source file:com.kpbird.aws.Main.java

private void createEC2OnDemandInstance() {
    try {//from  w w  w.j a v  a 2 s  . co  m

        // request for new on demand instance
        RunInstancesRequest rir = new RunInstancesRequest();
        rir.withImageId(imageId);
        rir.withInstanceType(instanceType);
        rir.withMinCount(1);
        rir.withMaxCount(1);
        rir.withKeyName(keyName);
        rir.withMonitoring(true);
        rir.withSecurityGroups(groupName);

        RunInstancesResult riresult = ec2client.runInstances(rir);
        log.Info(riresult.getReservation().getReservationId());

        /// Find newly created instance id
        String instanceId = null;
        DescribeInstancesResult result = ec2client.describeInstances();
        Iterator<Reservation> i = result.getReservations().iterator();
        while (i.hasNext()) {
            Reservation r = i.next();
            List<Instance> instances = r.getInstances();
            for (Instance ii : instances) {
                log.Info(ii.getImageId() + "\t" + ii.getInstanceId() + "\t" + ii.getState().getName() + "\t"
                        + ii.getPrivateDnsName());
                if (ii.getState().getName().equals("pending")) {
                    instanceId = ii.getInstanceId();
                }
            }
        }

        log.Info("New Instance ID :" + instanceId);
        /// Waiting for Instance Running////
        boolean isWaiting = true;
        while (isWaiting) {
            log.Info("*** Waiting ***");
            Thread.sleep(1000);
            DescribeInstancesResult r = ec2client.describeInstances();
            Iterator<Reservation> ir = r.getReservations().iterator();
            while (ir.hasNext()) {
                Reservation rr = ir.next();
                List<Instance> instances = rr.getInstances();
                for (Instance ii : instances) {
                    log.Info(ii.getImageId() + "\t" + ii.getInstanceId() + "\t" + ii.getState().getName() + "\t"
                            + ii.getPrivateDnsName());
                    if (ii.getState().getName().equals("running") && ii.getInstanceId().equals(instanceId)) {
                        log.Info(ii.getPublicDnsName());
                        isWaiting = false;
                    }
                }
            }
        }

        /// Creating Tag for New Instance ////
        log.Info("Creating Tags for New Instance");
        CreateTagsRequest crt = new CreateTagsRequest();
        ArrayList<Tag> arrTag = new ArrayList<Tag>();
        arrTag.add(new Tag().withKey("Name").withValue(instanceName));
        crt.setTags(arrTag);

        ArrayList<String> arrInstances = new ArrayList<String>();
        arrInstances.add(instanceId);
        crt.setResources(arrInstances);
        ec2client.createTags(crt);

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(0);
    }
}