Search in sources :

Example 6 with KeyPair

use of com.amazonaws.services.ec2.model.KeyPair in project GNS by MobilityFirst.

the class AWSEC2 method createAndInitInstance.

/**
   * Creates an EC2 instance in the region given. Timeout in milleseconds can be specified.
   *
   * @param ec2
   * @param region
   * @param amiRecord
   * @param instanceName
   * @param keyName
   * @param securityGroupName
   * @param script
   * @param tags
   * @param elasticIP
   * @param timeout
   * @return a new instance instance
   */
public static Instance createAndInitInstance(AmazonEC2 ec2, RegionRecord region, AMIRecord amiRecord, String instanceName, String keyName, String securityGroupName, String script, Map<String, String> tags, String elasticIP, int timeout) {
    try {
        // set the region (AKA endpoint)
        setRegion(ec2, region);
        // create the instance
        SecurityGroup securityGroup = findOrCreateSecurityGroup(ec2, securityGroupName);
        String keyPair = findOrCreateKeyPair(ec2, keyName);
        String instanceID = createInstanceAndWait(ec2, amiRecord, keyPair, securityGroup);
        if (instanceID == null) {
            return null;
        }
        System.out.println("Instance " + instanceName + " is running in " + region.name());
        // add a name to the instance
        addInstanceTag(ec2, instanceID, "Name", instanceName);
        if (tags != null) {
            addInstanceTags(ec2, instanceID, tags);
        }
        Instance instance = findInstance(ec2, instanceID);
        if (instance == null) {
            return null;
        }
        String hostname = instance.getPublicDnsName();
        System.out.println("Waiting " + timeout / 1000 + " seconds for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable.");
        long startTime = System.currentTimeMillis();
        while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
            ThreadUtils.sleep(1000);
            System.out.print(".");
            if (System.currentTimeMillis() - startTime > timeout) {
                System.out.println(instanceName + " (" + hostname + ")" + " timed out during reachability check.");
                return null;
            }
        }
        System.out.println();
        System.out.println(instanceName + " (" + hostname + ")" + " is reachable.");
        // associate the elasticIP if one is provided
        if (elasticIP != null) {
            System.out.println("Using ElasticIP " + elasticIP + " for instance " + instanceName + " (" + instanceID + ")");
            AWSEC2.associateAddress(ec2, elasticIP, instance);
            // get a new copy cuz things have changed
            instance = findInstance(ec2, instanceID);
            if (instance == null) {
                return null;
            }
            // recheck reachability
            hostname = instance.getPublicDnsName();
            System.out.println("Waiting " + timeout / 1000 + " s for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable after Elastic IP change.");
            startTime = System.currentTimeMillis();
            while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
                ThreadUtils.sleep(1000);
                System.out.print(".");
                if (System.currentTimeMillis() - startTime > timeout) {
                    // give it a minute and ahalf
                    System.out.println(instanceName + " (" + hostname + ")" + " timed out during second (elastic IP) reachability check.");
                    return null;
                }
            }
            System.out.println();
            System.out.println(instanceName + " (" + hostname + ")" + " is still reachable.");
        }
        if (script != null) {
            File keyFile = new File(KEYHOME + FILESEPARATOR + keyName + PRIVATEKEYFILEEXTENSION);
            ExecuteBash.executeBashScript("ec2-user", hostname, keyFile, true, "installScript.sh", script);
        }
        return instance;
    } 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());
    }
    return null;
}
Also used : Instance(com.amazonaws.services.ec2.model.Instance) AmazonServiceException(com.amazonaws.AmazonServiceException) SecurityGroup(com.amazonaws.services.ec2.model.SecurityGroup) File(java.io.File)

Example 7 with KeyPair

use of com.amazonaws.services.ec2.model.KeyPair in project camel by apache.

the class AmazonEC2ClientMock method runInstances.

@Override
public RunInstancesResult runInstances(RunInstancesRequest runInstancesRequest) {
    RunInstancesResult result = new RunInstancesResult();
    if (runInstancesRequest.getImageId().equals("test-1")) {
        Reservation res = new Reservation();
        res.setOwnerId("1");
        res.setRequesterId("user-test");
        res.setReservationId("res-1");
        Collection<Instance> instances = new ArrayList();
        Instance ins = new Instance();
        ins.setImageId(runInstancesRequest.getImageId());
        ins.setInstanceType(runInstancesRequest.getInstanceType());
        ins.setInstanceId("instance-1");
        if (runInstancesRequest.getSecurityGroups() != null) {
            if (runInstancesRequest.getSecurityGroups().contains("secgroup-1") && runInstancesRequest.getSecurityGroups().contains("secgroup-2")) {
                GroupIdentifier id1 = new GroupIdentifier();
                id1.setGroupId("id-1");
                id1.setGroupName("secgroup-1");
                GroupIdentifier id2 = new GroupIdentifier();
                id2.setGroupId("id-2");
                id2.setGroupName("secgroup-2");
                Collection secGroups = new ArrayList<GroupIdentifier>();
                secGroups.add(id1);
                secGroups.add(id2);
                ins.setSecurityGroups(secGroups);
            } else if (ObjectHelper.isNotEmpty(runInstancesRequest.getKeyName())) {
                if (ObjectHelper.isNotEmpty(runInstancesRequest.getKeyName().contains("keypair-1"))) {
                    GroupIdentifier id1 = new GroupIdentifier();
                    id1.setGroupId("id-3");
                    id1.setGroupName("secgroup-3");
                    GroupIdentifier id2 = new GroupIdentifier();
                    id2.setGroupId("id-4");
                    id2.setGroupName("secgroup-4");
                    Collection secGroups = new ArrayList<GroupIdentifier>();
                    secGroups.add(id1);
                    secGroups.add(id2);
                    ins.setSecurityGroups(secGroups);
                }
            }
        }
        instances.add(ins);
        res.setInstances(instances);
        result.setReservation(res);
    } else {
        throw new AmazonServiceException("The image-id doesn't exists");
    }
    return result;
}
Also used : Reservation(com.amazonaws.services.ec2.model.Reservation) Instance(com.amazonaws.services.ec2.model.Instance) RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) ArrayList(java.util.ArrayList) AmazonServiceException(com.amazonaws.AmazonServiceException) Collection(java.util.Collection) GroupIdentifier(com.amazonaws.services.ec2.model.GroupIdentifier)

Example 8 with KeyPair

use of com.amazonaws.services.ec2.model.KeyPair in project camel by apache.

the class EC2ComponentSpringTest method ec2CreateAndRunTestWithKeyPair.

@Test
public void ec2CreateAndRunTestWithKeyPair() throws Exception {
    Exchange exchange = template.request("direct:createAndRun", new Processor() {

        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setHeader(EC2Constants.OPERATION, EC2Operations.createAndRunInstances);
            exchange.getIn().setHeader(EC2Constants.IMAGE_ID, "test-1");
            exchange.getIn().setHeader(EC2Constants.INSTANCE_TYPE, InstanceType.T2Micro);
            exchange.getIn().setHeader(EC2Constants.INSTANCE_MIN_COUNT, 1);
            exchange.getIn().setHeader(EC2Constants.INSTANCE_MAX_COUNT, 1);
            exchange.getIn().setHeader(EC2Constants.INSTANCES_KEY_PAIR, "keypair-1");
        }
    });
    RunInstancesResult resultGet = (RunInstancesResult) exchange.getOut().getBody();
    assertEquals(resultGet.getReservation().getInstances().get(0).getImageId(), "test-1");
    assertEquals(resultGet.getReservation().getInstances().get(0).getInstanceType(), InstanceType.T2Micro.toString());
    assertEquals(resultGet.getReservation().getInstances().get(0).getInstanceId(), "instance-1");
    assertEquals(resultGet.getReservation().getInstances().get(0).getSecurityGroups().size(), 2);
    assertEquals(resultGet.getReservation().getInstances().get(0).getSecurityGroups().get(0).getGroupId(), "id-3");
    assertEquals(resultGet.getReservation().getInstances().get(0).getSecurityGroups().get(1).getGroupId(), "id-4");
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) RunInstancesResult(com.amazonaws.services.ec2.model.RunInstancesResult) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)4 KeyPair (com.amazonaws.services.ec2.model.KeyPair)3 RunInstancesResult (com.amazonaws.services.ec2.model.RunInstancesResult)3 AmazonServiceException (com.amazonaws.AmazonServiceException)2 Parameter (com.amazonaws.services.cloudformation.model.Parameter)2 Instance (com.amazonaws.services.ec2.model.Instance)2 ACloudFormationTest (de.widdix.awscftemplates.ACloudFormationTest)2 File (java.io.File)2 Exchange (org.apache.camel.Exchange)2 Processor (org.apache.camel.Processor)2 AmazonEC2 (com.amazonaws.services.ec2.AmazonEC2)1 CreateKeyPairRequest (com.amazonaws.services.ec2.model.CreateKeyPairRequest)1 CreateKeyPairResult (com.amazonaws.services.ec2.model.CreateKeyPairResult)1 GroupIdentifier (com.amazonaws.services.ec2.model.GroupIdentifier)1 Reservation (com.amazonaws.services.ec2.model.Reservation)1 SecurityGroup (com.amazonaws.services.ec2.model.SecurityGroup)1 BufferedReader (java.io.BufferedReader)1 BufferedWriter (java.io.BufferedWriter)1 FileWriter (java.io.FileWriter)1 IOException (java.io.IOException)1