Example usage for com.amazonaws.services.ec2.model DescribeKeyPairsResult getKeyPairs

List of usage examples for com.amazonaws.services.ec2.model DescribeKeyPairsResult getKeyPairs

Introduction

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

Prototype


public java.util.List<KeyPairInfo> getKeyPairs() 

Source Link

Document

Information about the key pairs.

Usage

From source file:aws.example.ec2.DescribeKeyPairs.java

License:Open Source License

public static void main(String[] args) {
    final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();

    DescribeKeyPairsResult response = ec2.describeKeyPairs();

    for (KeyPairInfo key_pair : response.getKeyPairs()) {
        System.out.printf("Found key pair with name %s " + "and fingerprint %s", key_pair.getKeyName(),
                key_pair.getKeyFingerprint());
    }//from  ww  w .  j a  va  2 s  .  c  o m
}

From source file:com.cloudera.director.aws.ec2.EC2InstanceTemplateConfigurationValidator.java

License:Apache License

/**
 * Validates the EC2 key name.//from   ww w  .  j  av  a 2  s.  co m
 *
 * @param client              the EC2 client
 * @param accumulator         the exception condition accumulator
 * @param localizationContext the localization context
 */
@VisibleForTesting
void checkKeyName(AmazonEC2Client client, Configured configuration,
        PluginExceptionConditionAccumulator accumulator, LocalizationContext localizationContext) {

    String keyName = configuration.getConfigurationValue(KEY_NAME, localizationContext);

    if (keyName != null) {
        LOG.info(">> Describing key pair");
        try {
            DescribeKeyPairsResult result = client
                    .describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyName));
            // TODO Should this be REDACTED instead of NotDisplayed?
            checkCount(accumulator, KEY_NAME, localizationContext, "NotDisplayed", result.getKeyPairs());

        } catch (AmazonServiceException e) {
            if (e.getErrorCode().startsWith(INVALID_KEY_PAIR)) {
                addError(accumulator, KEY_NAME, localizationContext, null, INVALID_KEY_NAME_MSG, keyName);
            } else {
                throw Throwables.propagate(e);
            }
        }
    }
}

From source file:com.cloudera.director.aws.ec2.EC2Provider.java

License:Apache License

/**
 * Returns the key name corresponding to the specified fingerprints, or {@code null} if it
 * cannot be determined./* w ww .  j a  va 2 s.  co m*/
 *
 * @param privateKeyFingerprint the private key fingerprint
 * @param publicKeyFingerprint  the public key fingerprint
 * @return the key name corresponding to the specified fingerprints, or {@code null} if it
 * cannot be determined
 */
private String lookupKeyName(String privateKeyFingerprint, String publicKeyFingerprint) {
    DescribeKeyPairsResult keyPairsResult = client.describeKeyPairs();
    for (KeyPairInfo keyPairInfo : keyPairsResult.getKeyPairs()) {
        String knownFingerprint = keyPairInfo.getKeyFingerprint().replace(":", "");
        LOG.debug("Found fingerprint {} for keyName {}", knownFingerprint, keyPairInfo.getKeyName());
        if (privateKeyFingerprint.equals(knownFingerprint)) {
            return keyPairInfo.getKeyName();
        }
        if (publicKeyFingerprint.equals(knownFingerprint)) {
            return keyPairInfo.getKeyName();
        }
    }
    return null;
}

From source file:com.ec2box.manage.action.EC2KeyAction.java

License:Apache License

/**
 * returns keypairs as a json string//  w w w.  j  a  va 2 s. c  om
 */
@Action(value = "/manage/getKeyPairJSON")
public String getKeyPairJSON() {

    AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredId());

    //set  AWS credentials for service
    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(),
            awsCred.getSecretKey());
    AmazonEC2 service = new AmazonEC2Client(awsCredentials, AWSClientConfig.getClientConfig());

    service.setEndpoint(ec2Key.getEc2Region());

    DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();

    DescribeKeyPairsResult describeKeyPairsResult = service.describeKeyPairs(describeKeyPairsRequest);

    List<KeyPairInfo> keyPairInfoList = describeKeyPairsResult.getKeyPairs();
    String json = new Gson().toJson(keyPairInfoList);
    try {
        servletResponse.getOutputStream().write(json.getBytes());
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }
    return null;
}

From source file:com.ec2box.manage.action.EC2KeyAction.java

License:Apache License

@Action(value = "/manage/importEC2Key", results = {
        @Result(name = "input", location = "/manage/view_ec2_keys.jsp"),
        @Result(name = "success", location = "/manage/viewEC2Keys.action", type = "redirect") })
public String importEC2Key() {

    String retVal = SUCCESS;//  w w w.  j a va2  s  . co  m

    try {
        //get AWS credentials from DB
        AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredId());

        //set  AWS credentials for service
        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(),
                awsCred.getSecretKey());

        //create service
        AmazonEC2 service = new AmazonEC2Client(awsCredentials, AWSClientConfig.getClientConfig());
        service.setEndpoint(ec2Key.getEc2Region());

        //describe key pair request
        DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
        describeKeyPairsRequest.setKeyNames(Arrays.asList(ec2Key.getKeyNm()));

        //call service
        DescribeKeyPairsResult describeKeyPairsResult = service.describeKeyPairs(describeKeyPairsRequest);

        if (describeKeyPairsResult != null && describeKeyPairsResult.getKeyPairs().size() > 0) {
            //add to db
            EC2KeyDB.saveEC2Key(ec2Key);
        } else {
            addActionError("Imported key does not exist on AWS");
            retVal = INPUT;
        }

    } catch (AmazonServiceException ex) {
        addActionError(ex.getMessage());
        retVal = INPUT;

    }

    return retVal;

}

From source file:com.eucalyptus.tests.awssdk.CloudCleaner.java

License:Open Source License

@Test
public void clean() throws Exception {
    testInfo(this.getClass().getSimpleName());
    getCloudInfo();// ww w .  ja v a  2  s  .co m

    //Terminate All instances
    List<String> instancesToTerminate = new ArrayList<String>();
    DescribeInstancesResult result = ec2.describeInstances();
    List<Reservation> reservations = result.getReservations();
    if (reservations.size() > 0) {
        print("Found instances to terminate");
        for (Reservation reservation : reservations) {
            List<Instance> instances = reservation.getInstances();
            for (Instance instance : instances) {
                print("Terminating: " + instance.getInstanceId());
                instancesToTerminate.add(instance.getInstanceId());
            }
        }
        TerminateInstancesRequest term = new TerminateInstancesRequest();
        term.setInstanceIds(instancesToTerminate);
        ec2.terminateInstances(term);
    } else {
        print("No instances found");
    }

    // delete all keypairs
    if (getKeyPairCount() > 0) {
        print("Found Keypairs to delete");
        DescribeKeyPairsResult describeKeyPairsResult = ec2.describeKeyPairs();
        for (KeyPairInfo keypair : describeKeyPairsResult.getKeyPairs()) {
            deleteKeyPair(keypair.getKeyName());
        }
    } else {
        print("No keypairs found");
    }

    // delete all groups except default group
    List<SecurityGroup> groups = describeSecurityGroups();
    if (groups.size() > 1) {
        print("Found security groups to delete");
        for (SecurityGroup group : groups) {
            if (!group.getGroupName().equals("default")) {
                deleteSecurityGroup(group.getGroupName());
            }
        }
    } else {
        print("No Security Groups found (other than default)");
    }

    // delete all policies
    List<ScalingPolicy> policies = describePolicies();
    if (policies.size() > 0) {
        print("Found Policies to delete");
        for (ScalingPolicy policy : policies) {
            deletePolicy(policy.getPolicyName());
        }
    } else {
        print("No auto scaling policies found");
    }

    // delete launch configs
    List<LaunchConfiguration> lcs = describeLaunchConfigs();
    if (lcs.size() > 0) {
        print("Found Launch Configs to delete");
        for (LaunchConfiguration lc : lcs) {
            deleteLaunchConfig(lc.getLaunchConfigurationName());
        }
    } else {
        print("No launch configs found");
    }

    // delete autoscaling groups
    List<AutoScalingGroup> asGroups = describeAutoScalingGroups();
    if (asGroups.size() > 0) {
        print("Found Auto Scaling Groups to delete");
        for (AutoScalingGroup asg : asGroups) {
            deleteAutoScalingGroup(asg.getAutoScalingGroupName(), true);
        }
    } else {
        print("No auto scaling groups found");
    }

    // delete volumes
    List<Volume> volumes = ec2.describeVolumes().getVolumes();
    if (volumes.size() > 0) {
        print("Found volumes to delete");
        for (Volume vol : volumes) {
            deleteVolume(vol.getVolumeId());
        }
    } else {
        print("No volumes found");
    }

    //delete snapshots
    List<Snapshot> snapshots = ec2.describeSnapshots().getSnapshots();
    if (snapshots.size() > 0) {
        print("Found snapshots to delete");
        for (Snapshot snap : snapshots) {
            deleteSnapshot(snap.getSnapshotId());
        }
    } else {
        print("No volumes found");
    }
}

From source file:com.hpcloud.daas.ec2.AwsConsoleApp.java

License:Open Source License

public static void describeKeyPairs() {
    DescribeKeyPairsResult result = ec2.describeKeyPairs();
    List<KeyPairInfo> keyPairInfos = result.getKeyPairs();
    for (KeyPairInfo info : keyPairInfos) {
        System.out.println(info);
    }// w  w  w  . j a va  2s  . c  o  m
}

From source file:com.keybox.manage.action.ApplicationKeysAction.java

License:Apache License

/**
  * returns keypairs as a json string/* www  . j  a  v  a 2s . co m*/
  */
@Action(value = "/manage/getKeyPairJSON")
public String getKeyPairJSON() {

    AWSCred awsCred = AWSCredDB.getAWSCred(ec2Key.getAwsCredentials().getId());

    //set  AWS credentials for service
    BasicAWSCredentials awsCredentials = new BasicAWSCredentials(awsCred.getAccessKey(),
            awsCred.getSecretKey());
    AmazonEC2 service = new AmazonEC2Client(awsCredentials, AWSClientConfig.getClientConfig());

    service.setEndpoint(ec2Key.getEc2Region());

    DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();

    DescribeKeyPairsResult describeKeyPairsResult = service.describeKeyPairs(describeKeyPairsRequest);

    List<KeyPairInfo> keyPairInfoList = describeKeyPairsResult.getKeyPairs();
    String json = new Gson().toJson(keyPairInfoList);
    try {
        servletResponse.getOutputStream().write(json.getBytes());
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:com.nike.cerberus.service.Ec2Service.java

License:Apache License

/**
 * Checks if a key pair is present in AWS EC2.
 *
 * @param keyName Friendly name for the key
 * @return If present//from  w ww.j  a  v a2s.co  m
 */
public boolean isKeyPairPresent(final String keyName) {
    final DescribeKeyPairsRequest request = new DescribeKeyPairsRequest().withKeyNames(keyName);

    try {
        final DescribeKeyPairsResult result = ec2Client.describeKeyPairs(request);
        return result.getKeyPairs().size() > 0;
    } catch (final AmazonServiceException ase) {
        if (ase.getErrorCode() == "InvalidKeyPair.NotFound") {
            return false;
        }

        throw ase;
    }
}

From source file:com.norbl.cbp.ppe.Ec2Wrangler.java

License:Open Source License

public List<String> getKeypairNames() {
    List<String> names = new ArrayList<String>();
    DescribeKeyPairsResult r = ec2Client.describeKeyPairs();
    for (KeyPairInfo kpi : r.getKeyPairs()) {
        String nm = kpi.getKeyName();
        if (nm != null)
            names.add(nm);//  w  ww  .j  a  va 2  s . c  o  m
    }
    return (names);
}