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

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

Introduction

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

Prototype


public RunInstancesRequest withSecurityGroups(java.util.Collection<String> securityGroups) 

Source Link

Document

[EC2-Classic, default VPC] The names of the security groups.

Usage

From source file:AwsSample.java

License:Open Source License

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

    BasicAWSCredentials credentials = new BasicAWSCredentials("", "");

    /*********************************************
     * // ww w  .  ja v a  2 s.  co  m
     *  #1 Create Amazon Client object
     *  
     *********************************************/
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);

    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());
        }
        ///////////////////////////////////////

        String Temp_Group = "Testgroup1"; //name of the group
        CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest(Temp_Group, "temporal group");
        ec2.createSecurityGroup(r1);
        AuthorizeSecurityGroupIngressRequest r2 = new AuthorizeSecurityGroupIngressRequest();
        r2.setGroupName(Temp_Group);

        /*************the property of http*****************/
        IpPermission permission = new IpPermission();
        permission.setIpProtocol("tcp");
        permission.setFromPort(80);
        permission.setToPort(80);
        List<String> ipRanges = new ArrayList<String>();
        ipRanges.add("0.0.0.0/0");
        permission.setIpRanges(ipRanges);

        /*************the property of SSH**********************/
        IpPermission permission1 = new IpPermission();
        permission1.setIpProtocol("tcp");
        permission1.setFromPort(22);
        permission1.setToPort(22);
        List<String> ipRanges1 = new ArrayList<String>();
        ipRanges1.add("0.0.0.0/22");
        permission1.setIpRanges(ipRanges1);

        /*************the property of https**********************/
        IpPermission permission2 = new IpPermission();
        permission2.setIpProtocol("tcp");
        permission2.setFromPort(443);
        permission2.setToPort(443);
        List<String> ipRanges2 = new ArrayList<String>();
        ipRanges2.add("0.0.0.0/0");
        permission2.setIpRanges(ipRanges2);

        /*************the property of tcp**********************/
        IpPermission permission3 = new IpPermission();
        permission3.setIpProtocol("tcp");
        permission3.setFromPort(0);
        permission3.setToPort(65535);
        List<String> ipRanges3 = new ArrayList<String>();
        ipRanges3.add("0.0.0.0/0");
        permission3.setIpRanges(ipRanges3);

        /**********************add rules to the group*********************/
        List<IpPermission> permissions = new ArrayList<IpPermission>();
        permissions.add(permission);
        permissions.add(permission1);
        permissions.add(permission2);
        permissions.add(permission3);
        r2.setIpPermissions(permissions);

        ec2.authorizeSecurityGroupIngress(r2);
        List<String> groupName = new ArrayList<String>();
        groupName.add(Temp_Group);//wait to out our instance into this group

        /*********************************************
        *
        *  #6.2 Create a New Key Pair
        * 
        *********************************************/

        CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest();
        newKeyRequest.setKeyName("Test_Key2");
        CreateKeyPairResult keyresult = ec2.createKeyPair(newKeyRequest);

        /************************print the properties of this key*****************/
        KeyPair kp = new KeyPair();

        kp = keyresult.getKeyPair();
        System.out.println("The key we created is = " + kp.getKeyName() + "\nIts fingerprint is="
                + kp.getKeyFingerprint() + "\nIts material is= \n" + kp.getKeyMaterial());

        String fileName = "C:/Users/Akhil/workspace/Test_Key2.pem";
        File distFile = new File(fileName);
        BufferedReader bufferedReader = new BufferedReader(new StringReader(kp.getKeyMaterial()));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile));
        char buf[] = new char[1024];
        int len;
        while ((len = bufferedReader.read(buf)) != -1) {
            bufferedWriter.write(buf, 0, len);
        }
        bufferedWriter.flush();
        bufferedReader.close();
        bufferedWriter.close();
        //String myinstance; 
        /*********************************************
          * 
          *  #6 Create an Instance
          *  
          *********************************************/
        System.out.println("#5 Create an Instance");
        String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI
        int minInstanceCount = 1; // create 1 instance
        int maxInstanceCount = 1;
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.setKeyName("Test_Key2");
        rir.withSecurityGroups("Testgroup1");

        RunInstancesResult result = ec2.runInstances(rir);

        //get instanceId from the result
        List<Instance> resultInstance = result.getReservation().getInstances();
        String createdInstanceId = null;
        String myAvailabilityZone = null;
        for (Instance ins : resultInstance) {
            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());
            //myinstance = ins.getInstanceId();

        }

        Thread.currentThread().sleep(60000);

        /*********************************************
         * 
         * 
         * Create a New Volume and attach it
         * 
         ***********************************************/

        List<Instance> resultInstance2 = result.getReservation().getInstances();

        createdInstanceId = null;
        for (Instance ins : resultInstance2) {

            createdInstanceId = ins.getInstanceId();
            System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID

            /*********************************************
              * 
              *  #6.4 Create an Instance
              *  
              *********************************************/

            CreateVolumeRequest newVol = new CreateVolumeRequest(1, "us-east-1a");

            CreateVolumeResult volresult = ec2.createVolume(newVol);
            Volume vol1 = volresult.getVolume();
            String volId = vol1.getVolumeId();
            Thread.currentThread().sleep(30000);

            AttachVolumeRequest attachRequest = new AttachVolumeRequest().withInstanceId(createdInstanceId)
                    .withVolumeId(volId);
            attachRequest.withDevice("/dev/sda5");
            ec2.attachVolume(attachRequest);

            System.out.println("EBS volume has been attached and the volume ID is: " + volId);
        }
        /*********************************************
         * 
         *  #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("Akhil", "MyFirstInstance");

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

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

        /*********************************************
         * 
         *  #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);

        System.out.println("#8 Getting DNS, IP.");

        DescribeInstancesRequest request = new DescribeInstancesRequest();
        request.setInstanceIds(instanceIds);

        DescribeInstancesResult result1 = ec2.describeInstances(request);
        List<Reservation> reservations1 = result1.getReservations();

        List<Instance> instances1;
        for (Reservation res : reservations1) {
            instances1 = res.getInstances();
            for (Instance ins1 : instances1) {
                System.out
                        .println("The public DNS is: " + ins1.getPublicDnsName() + "\n" + ins1.getRamdiskId());
                System.out.println("The private IP is: " + ins1.getPrivateIpAddress());
                System.out.println("The public IP is: " + ins1.getPublicIpAddress());

            }

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

            /*********************************************
             *  
             *  #11 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:br.unb.cic.bionimbuz.elasticity.legacy.Ec2Commands.java

License:Open Source License

public static void createinstance() throws IOException {
    Ec2Commands.setup();//from  w w  w  .j a va2s . c o m

    try {

        System.out.println("Criando nova maquina BioninbuZ");
        String imageId;
        System.out.println("Enter the image AMI id (eg: ami-687b4f2d)");
        imageId = user_input.next();

        int minInstanceCount = 1; // 
        int maxInstanceCount = 1;
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.setInstanceType("t1.micro");

        Scanner keyscan = new Scanner(System.in);
        System.out.println("Do you want to use an existing keypair or do you want to create a new one?");
        System.out.println("#1 Use existing keypair");
        System.out.println("#2 Create a new keypair");
        int keypairoption;
        String key; //existing keypair name
        keypairoption = keyscan.nextInt();
        if (keypairoption == 1) {
            System.out.println("Enter the existing keypair name to use with the new instance");
            key = keyscan.next();
            rir.withKeyName(key);
        } else if (keypairoption == 2) {
            //count++;
            System.out.println("Enter the keypair name to create");
            String newkeyname;
            newkeyname = keyscan.next();
            CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest();
            newKeyRequest.setKeyName(newkeyname);
            CreateKeyPairResult keyresult = EC2.createKeyPair(newKeyRequest);

            keyPair = keyresult.getKeyPair();
            System.out.println("The key we created is = " + keyPair.getKeyName() + "\nIts fingerprint is="
                    + keyPair.getKeyFingerprint() + "\nIts material is= \n" + keyPair.getKeyMaterial());

            System.out.println(
                    "Enter the directory to store .pem file (eg: Windows C:\\Users\\user\\Desktop\\, Linux /user/home)");
            String dir;
            dir = keyscan.next();
            String fileName = dir + newkeyname + ".pem";
            File distFile = new File(fileName);
            BufferedReader bufferedReader = new BufferedReader(new StringReader(keyPair.getKeyMaterial()));
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile));
            char buf[] = new char[1024];
            int len;
            while ((len = bufferedReader.read(buf)) != -1) {
                bufferedWriter.write(buf, 0, len);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();

        }

        rir.withSecurityGroups("default");

        RunInstancesResult result = EC2.runInstances(rir);

        System.out.println("waiting");
        try {
            Thread.sleep(50000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("OK");

        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());//print the instance ID

        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println();
        System.out.println("Restarting the application");
        System.out.println();
        //    Ec2Commands.enteroption();   
    } 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());
        System.out.println("Give a valid input");
        System.out.println("");
        //      Ec2Commands.enteroption();
    }

}

From source file:br.unb.cic.bionimbuz.services.elasticity.Ec2Commands.java

License:Open Source License

public static void createinstance() throws IOException {
    Ec2Commands.setup();/*from  w w  w .j av  a 2s  . c o  m*/

    try {

        System.out.println("Criando nova maquina BioninbuZ");
        String imageId;
        System.out.println("Enter the image AMI id (eg: ami-687b4f2d)");
        imageId = user_input.next();

        int minInstanceCount = 1; // 
        int maxInstanceCount = 1;
        RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
        rir.setInstanceType("t1.micro");

        try (Scanner keyscan = new Scanner(System.in)) {
            System.out.println("Do you want to use an existing keypair or do you want to create a new one?");
            System.out.println("#1 Use existing keypair");
            System.out.println("#2 Create a new keypair");
            int keypairoption;
            String key; //existing keypair name
            keypairoption = keyscan.nextInt();
            if (keypairoption == 1) {
                System.out.println("Enter the existing keypair name to use with the new instance");
                key = keyscan.next();
                rir.withKeyName(key);
            } else if (keypairoption == 2) {
                //count++;
                System.out.println("Enter the keypair name to create");
                String newkeyname;
                newkeyname = keyscan.next();
                CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest();
                newKeyRequest.setKeyName(newkeyname);
                CreateKeyPairResult keyresult = EC2.createKeyPair(newKeyRequest);

                keyPair = keyresult.getKeyPair();
                System.out.println("The key we created is = " + keyPair.getKeyName() + "\nIts fingerprint is="
                        + keyPair.getKeyFingerprint() + "\nIts material is= \n" + keyPair.getKeyMaterial());

                System.out.println(
                        "Enter the directory to store .pem file (eg: Windows C:\\Users\\user\\Desktop\\, Linux /user/home)");
                String dir;
                dir = keyscan.next();
                String fileName = dir + newkeyname + ".pem";
                File distFile = new File(fileName);
                BufferedReader bufferedReader = new BufferedReader(new StringReader(keyPair.getKeyMaterial()));
                BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile));
                char buf[] = new char[1024];
                int len;
                while ((len = bufferedReader.read(buf)) != -1) {
                    bufferedWriter.write(buf, 0, len);
                }
                bufferedWriter.flush();
                bufferedReader.close();
                bufferedWriter.close();

            }
        }

        rir.withSecurityGroups("default");

        RunInstancesResult result = EC2.runInstances(rir);

        System.out.println("waiting");
        try {
            Thread.sleep(50000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("OK");

        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());//print the instance ID

        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println();
        System.out.println("Restarting the application");
        System.out.println();
        //    Ec2Commands.enteroption();   
    } 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());
        System.out.println("Give a valid input");
        System.out.println("");
        //      Ec2Commands.enteroption();
    }

}

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  . j  ava2 s. co 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   ww  w. j ava2  s . c  o  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);
    }
}

From source file:com.xebialabs.overcast.host.Ec2CloudHost.java

License:Apache License

protected String runInstance() {
    RunInstancesRequest run = new RunInstancesRequest(amiId, 1, 1);
    run.withInstanceInitiatedShutdownBehavior("terminate");
    if (amiInstanceType != null) {
        run.withInstanceType(amiInstanceType);
    }/* w  w  w  .j a va2  s  .  c  o m*/
    if (amiSecurityGroup != null) {
        run.withSecurityGroups(amiSecurityGroup);
    }
    if (amiKeyName != null) {
        run.withKeyName(amiKeyName);
    }
    if (amiAvailabilityZone != null) {
        run.withPlacement(new Placement(amiAvailabilityZone));
    }

    RunInstancesResult result = ec2.runInstances(run);

    return result.getReservation().getInstances().get(0).getInstanceId();
}

From source file:com.zotoh.cloudapi.aws.EC2Instance.java

License:Open Source License

@Override
public VirtualMachine launch(String ami, VirtualMachineProduct type, String zone, String name,
        String descOrUserData, String keypair, String vpcId, boolean monitoring, boolean asImageSandbox,
        String[] firewalls, Tag... tags) throws InternalException, CloudException {
    tstEStrArg("image-id", ami);
    tstObjArg("product-type", type);
    tstEStrArg("keypair", keypair);
    tstEStrArg("zone", zone);
    RunInstancesRequest req = new RunInstancesRequest().withInstanceType(type.getProductId()).withImageId(ami)
            .withKeyName(keypair).withMaxCount(1).withMinCount(1).withMonitoring(monitoring);
    if (!isNilArray(firewalls)) {
        req.withSecurityGroups(firewalls);
    }/*  ww w .j  a v  a 2s. c  om*/
    String[] ss = zone.split("\\|");
    _svc.getCloud().setAWSSite(ss[0]);
    if (ss.length > 1) {
        req.withPlacement(new Placement().withAvailabilityZone(trim(ss[1])));
    }
    if (!isEmpty(descOrUserData)) {
        req.withUserData(descOrUserData);
    }
    RunInstancesResult res = _svc.getCloud().getEC2().runInstances(req);
    Reservation r = res == null ? null : res.getReservation();
    VirtualMachine vm = null;
    if (r != null) {
        List<Instance> lst = r.getInstances();
        vm = toVM(r.getOwnerId(), isNil(lst) ? null : lst.get(0));
    }
    return vm;
}

From source file:jp.primecloud.auto.process.aws.AwsInstanceProcess.java

License:Open Source License

public void run(AwsProcessClient awsProcessClient, Long instanceNo) {
    Instance instance = instanceDao.read(instanceNo);
    AwsInstance awsInstance = awsInstanceDao.read(instanceNo);
    ImageAws imageAws = imageAwsDao.read(instance.getImageNo());
    PlatformAws platformAws = awsProcessClient.getPlatformAws();

    // ?//from w  w  w. j  a v a2  s .  com
    RunInstancesRequest request = new RunInstancesRequest();
    request.withMinCount(1);
    request.withMaxCount(1);
    request.withImageId(imageAws.getImageId());
    request.withKernelId(StringUtils.isEmpty(imageAws.getKernelId()) ? null : imageAws.getKernelId());
    request.withRamdiskId(StringUtils.isEmpty(imageAws.getRamdiskId()) ? null : imageAws.getRamdiskId());
    request.withKeyName(awsInstance.getKeyName());
    request.withInstanceType(awsInstance.getInstanceType());

    // UserData
    Map<String, String> userData = createUserData(instanceNo);
    request.withUserData(encodeUserData(userData));

    // ?VPC??
    if (BooleanUtils.isNotTrue(platformAws.getVpc())) {
        // AvailabilityZone
        if (StringUtils.isNotEmpty(awsInstance.getAvailabilityZone())) {
            request.withPlacement(new Placement(awsInstance.getAvailabilityZone()));
        }

        // SecurityGroup
        if (StringUtils.isNotEmpty(awsInstance.getSecurityGroups())) {
            for (String groupName : StringUtils.split(awsInstance.getSecurityGroups(), ",")) {
                request.withSecurityGroups(groupName.trim());
            }
        }
    }
    // VPC??
    else {
        // Subnet
        request.withSubnetId(awsInstance.getSubnetId());

        // SecurytiGroup
        List<SecurityGroup> securityGroups = awsCommonProcess.describeSecurityGroupsByVpcId(awsProcessClient,
                platformAws.getVpcId());
        for (String groupName : StringUtils.split(awsInstance.getSecurityGroups(), ",")) {
            groupName = groupName.trim();
            for (SecurityGroup securityGroup : securityGroups) {
                if (StringUtils.equals(groupName, securityGroup.getGroupName())) {
                    request.withSecurityGroupIds(securityGroup.getGroupId());
                    break;
                }
            }
        }

        // PrivateIpAddress
        if (StringUtils.isNotEmpty(awsInstance.getPrivateIpAddress())) {
            request.withPrivateIpAddress(awsInstance.getPrivateIpAddress());
        }
    }

    // BlockDeviceMapping
    List<BlockDeviceMapping> blockDeviceMappings = createBlockDeviceMappings(awsProcessClient, imageAws,
            awsInstance);
    request.withBlockDeviceMappings(blockDeviceMappings);

    // 
    processLogger.debug(null, instance, "AwsInstanceCreate",
            new Object[] { awsProcessClient.getPlatform().getPlatformName() });

    // ??
    RunInstancesResult result = awsProcessClient.getEc2Client().runInstances(request);
    Reservation reservation = result.getReservation();

    if (reservation == null || reservation.getInstances().size() != 1) {
        // ?
        throw new AutoException("EPROCESS-000105");
    }

    com.amazonaws.services.ec2.model.Instance instance2 = reservation.getInstances().get(0);

    // 
    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100115", instance2.getInstanceId()));
    }

    // 
    awsInstance.setInstanceId(instance2.getInstanceId());
    awsInstance.setStatus(instance2.getState().getName());
    awsInstanceDao.update(awsInstance);
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

License:Open Source License

private Instance createEC2Instance(final PrivateEc2Template cfnTemplate, final ProvisioningContextImpl ctx,
        final boolean management, final String machineName, final long duration, final TimeUnit unit)
        throws CloudProvisioningException, TimeoutException {

    final InstanceProperties properties = cfnTemplate.getEC2Instance().getProperties();

    final String availabilityZone = properties.getAvailabilityZone() == null ? null
            : properties.getAvailabilityZone().getValue();
    final Placement placement = availabilityZone == null ? null : new Placement(availabilityZone);

    final String imageId = properties.getImageId() == null ? null : properties.getImageId().getValue();
    final String instanceType = properties.getInstanceType() == null ? null
            : properties.getInstanceType().getValue();
    final String keyName = properties.getKeyName() == null ? null : properties.getKeyName().getValue();
    final String privateIpAddress = properties.getPrivateIpAddress() == null ? null
            : properties.getPrivateIpAddress().getValue();
    final List<String> securityGroupIds = properties.getSecurityGroupIdsAsString();
    final List<String> securityGroups = properties.getSecurityGroupsAsString();

    S3Object s3Object = null;
    try {/*  w  ww. j a va 2  s.  c o m*/

        String userData = null;
        if (properties.getUserData() != null) {
            // Generate ENV script for the provisioned machine
            final StringBuilder sb = new StringBuilder();
            final String script = management ? this.generateManagementCloudifyEnv(ctx)
                    : this.generateCloudifyEnv(ctx);

            s3Object = this.uploadCloudDir(ctx, script, management);
            final String cloudFileS3 = this.amazonS3Uploader.generatePresignedURL(s3Object);

            ComputeTemplate template = this.getManagerComputeTemplate();
            String cloudFileDir = (String) template.getRemoteDirectory();
            // Remove '/' from the path if it's the last char.
            if (cloudFileDir.length() > 1 && cloudFileDir.endsWith("/")) {
                cloudFileDir = cloudFileDir.substring(0, cloudFileDir.length() - 1);
            }
            final String endOfLine = " >> /tmp/cloud.txt\n";
            sb.append("#!/bin/bash\n");
            sb.append("export TMP_DIRECTORY=/tmp").append(endOfLine);
            sb.append("export S3_ARCHIVE_FILE='" + cloudFileS3 + "'").append(endOfLine);
            sb.append("wget -q -O $TMP_DIRECTORY/cloudArchive.tar.gz $S3_ARCHIVE_FILE").append(endOfLine);
            sb.append("mkdir -p " + cloudFileDir).append(endOfLine);
            sb.append("tar zxvf $TMP_DIRECTORY/cloudArchive.tar.gz -C " + cloudFileDir).append(endOfLine);
            sb.append("rm -f $TMP_DIRECTORY/cloudArchive.tar.gz").append(endOfLine);
            sb.append("echo ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT).append(endOfLine);
            sb.append("chmod 755 ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT)
                    .append(endOfLine);
            sb.append("source ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT).append(endOfLine);

            sb.append(properties.getUserData().getValue());
            userData = sb.toString();
            logger.fine("Instanciate ec2 with user data:\n" + userData);
            userData = StringUtils.newStringUtf8(Base64.encodeBase64(userData.getBytes()));
        }

        List<BlockDeviceMapping> blockDeviceMappings = null;
        AWSEC2Volume volumeConfig = null;
        if (properties.getVolumes() != null) {
            blockDeviceMappings = new ArrayList<BlockDeviceMapping>(properties.getVolumes().size());
            for (final VolumeMapping volMapping : properties.getVolumes()) {
                volumeConfig = cfnTemplate.getEC2Volume(volMapping.getVolumeId().getValue());
                blockDeviceMappings
                        .add(this.createBlockDeviceMapping(volMapping.getDevice().getValue(), volumeConfig));
            }
        }

        final RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
        runInstancesRequest.withPlacement(placement);
        runInstancesRequest.withImageId(imageId);
        runInstancesRequest.withInstanceType(instanceType);
        runInstancesRequest.withKeyName(keyName);
        runInstancesRequest.withPrivateIpAddress(privateIpAddress);
        runInstancesRequest.withSecurityGroupIds(securityGroupIds);
        runInstancesRequest.withSecurityGroups(securityGroups);
        runInstancesRequest.withMinCount(1);
        runInstancesRequest.withMaxCount(1);
        runInstancesRequest.withBlockDeviceMappings(blockDeviceMappings);
        runInstancesRequest.withUserData(userData);

        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("EC2::Instance request=" + runInstancesRequest);
        }

        final RunInstancesResult runInstances = this.ec2.runInstances(runInstancesRequest);
        if (runInstances.getReservation().getInstances().size() != 1) {
            throw new CloudProvisioningException(
                    "Request runInstace fails (request=" + runInstancesRequest + ").");
        }

        Instance ec2Instance = runInstances.getReservation().getInstances().get(0);
        ec2Instance = this.waitRunningInstance(ec2Instance, duration, unit);
        this.tagEC2Instance(ec2Instance, machineName, cfnTemplate.getEC2Instance());
        this.tagEC2Volumes(ec2Instance.getInstanceId(), cfnTemplate);
        this.waitRunningAgent(ec2Instance.getPublicIpAddress(), duration, unit);

        return ec2Instance;
    } finally {
        if (s3Object != null) {
            this.amazonS3Uploader.deleteS3Object(s3Object.getBucketName(), s3Object.getKey());
        }
    }
}