Example usage for com.amazonaws.services.ec2 AmazonEC2Client describeKeyPairs

List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client describeKeyPairs

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2 AmazonEC2Client describeKeyPairs.

Prototype

@Override
public DescribeKeyPairsResult describeKeyPairs(DescribeKeyPairsRequest request) 

Source Link

Document

Describes the specified key pairs or all of your key pairs.

Usage

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

License:Apache License

/**
 * Validates the EC2 key name./*  w  w  w .j a v  a  2s . 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:n3phele.factory.ec2.VirtualServerResource.java

License:Open Source License

private boolean checkKey(String key, String id, String secret, URI location) {
    // TODO: implement with JCloud
    AmazonEC2Client client = null;
    client = getEC2Client(id, secret, location);
    boolean found = true;
    try {/*  w  w w. ja  v  a2 s.  com*/
        DescribeKeyPairsResult response = client
                .describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames("n3phele-" + key));
        if (response.getKeyPairs() == null || response.getKeyPairs().isEmpty()) {
            log.warning("No key pairs found");
            found = false;
        } else {
            log.warning("Found " + response.getKeyPairs().size() + " " + response.getKeyPairs().toString());
        }
    } catch (Exception e) {
        log.severe("Check security group exception " + e.getMessage());
        found = false;
    }
    return found;
}

From source file:org.apache.airavata.core.gfac.provider.impl.EC2Provider.java

License:Apache License

private void buildKeyPair(AmazonEC2Client ec2) throws NoSuchAlgorithmException, InvalidKeySpecException,
        AmazonServiceException, AmazonClientException, IOException {

    boolean newKey = false;

    File privateKeyFile = new File(privateKeyFilePath);
    File publicKeyFile = new File(privateKeyFilePath + ".pub");

    /*//from ww  w .  j a v  a 2s . c o  m
     * Check if Keypair already created on the server
     */
    if (!privateKeyFile.exists()) {

        // check folder and create if it does not exist
        File sshDir = new File(System.getProperty("user.home") + "/.ssh/");
        if (!sshDir.exists())
            sshDir.mkdir();

        // Generate a 1024-bit RSA key pair
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        java.security.KeyPair keypair = keyGen.genKeyPair();

        FileOutputStream fos = null;

        // Store Public Key.
        try {
            fos = new FileOutputStream(privateKeyFilePath + ".pub");
            // TODO
            //fos.write(Base64.encodeBytes(keypair.getPublic().getEncoded(), true).getBytes());
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException ioe) {
                    throw ioe;
                }
            }
        }

        // Store Private Key.
        try {
            fos = new FileOutputStream(privateKeyFilePath);
            StringWriter stringWriter = new StringWriter();

            /*
             * Write in PEM format (openssl support)
             */
            PEMWriter pemFormatWriter = new PEMWriter(stringWriter);
            pemFormatWriter.writeObject(keypair.getPrivate());
            pemFormatWriter.close();
            fos.write(stringWriter.toString().getBytes());
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException ioe) {
                    throw ioe;
                }
            }
        }

        privateKeyFile.setWritable(false, false);
        privateKeyFile.setExecutable(false, false);
        privateKeyFile.setReadable(false, false);
        privateKeyFile.setReadable(true);
        privateKeyFile.setWritable(true);

        // set that this key is just created
        newKey = true;
    }

    /*
     * Read Public Key
     */
    String encodedPublicKey = null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(publicKeyFile));
        encodedPublicKey = br.readLine();
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        if (br != null) {
            try {
                br.close();
                br = null;
            } catch (IOException ioe) {
                throw ioe;
            }
        }
    }

    /*
     * Generate key pair in Amazon if necessary
     */
    try {
        /*
         * Get current key pair in Amazon
         */
        DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
        ec2.describeKeyPairs(describeKeyPairsRequest.withKeyNames(KEY_PAIR_NAME));

        /*
         * If key exists and new key is created, delete old key and replace
         * with new one. Else, do nothing
         */

        if (newKey) {
            DeleteKeyPairRequest deleteKeyPairRequest = new DeleteKeyPairRequest(KEY_PAIR_NAME);
            ec2.deleteKeyPair(deleteKeyPairRequest);
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest(KEY_PAIR_NAME,
                    encodedPublicKey);
            ec2.importKeyPair(importKeyPairRequest);
        }

    } catch (AmazonServiceException ase) {
        /*
         * Key doesn't exists, import new key.
         */
        if (ase.getErrorCode().equals("InvalidKeyPair.NotFound")) {
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest(KEY_PAIR_NAME,
                    encodedPublicKey);
            ec2.importKeyPair(importKeyPairRequest);
        } else {
            throw ase;
        }
    }
}

From source file:org.apache.airavata.gfac.ec2.util.EC2ProviderUtil.java

License:Apache License

/**
 * Builds a key pair with the given AmazonEC2Client and the generated key will have
 * the name keyPairName./*from  w ww . j  av  a 2s.c om*/
 *
 * @param ec2 ec2client
 * @param keyPairName name for the generated key pair
 * @throws NoSuchAlgorithmException NoSuchAlgorithmException
 * @throws InvalidKeySpecException InvalidKeySpecException
 * @throws AmazonServiceException AmazonServiceException
 * @throws AmazonClientException AmazonClientException
 * @throws IOException IOException
 */
public static void buildKeyPair(AmazonEC2Client ec2, String keyPairName) throws NoSuchAlgorithmException,
        InvalidKeySpecException, AmazonServiceException, AmazonClientException, IOException {
    boolean newKey = false;

    String privateKeyFilePath = System.getProperty("user.home") + "/.ssh/" + keyPairName;
    File privateKeyFile = new File(privateKeyFilePath);
    File publicKeyFile = new File(privateKeyFilePath + ".pub");

    /* Check if Key-pair already created on the server */
    if (!privateKeyFile.exists()) {

        // check folder and create if it does not exist
        File sshDir = new File(System.getProperty("user.home") + "/.ssh/");
        if (!sshDir.exists())
            sshDir.mkdir();

        // Generate a 1024-bit RSA key pair
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair keypair = keyGen.genKeyPair();

        FileOutputStream fos = null;

        // Store Public Key.
        try {
            fos = new FileOutputStream(privateKeyFilePath + ".pub");
            fos.write(Base64.encodeBytes(keypair.getPublic().getEncoded(), true).getBytes());
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException ioe) {
                    throw ioe;
                }
            }
        }

        // Store Private Key.
        try {
            fos = new FileOutputStream(privateKeyFilePath);
            StringWriter stringWriter = new StringWriter();

            /* Write in PEM format (openssl support) */
            PEMWriter pemFormatWriter = new PEMWriter(stringWriter);
            pemFormatWriter.writeObject(keypair.getPrivate());
            pemFormatWriter.close();
            fos.write(stringWriter.toString().getBytes());
        } catch (IOException ioe) {
            throw ioe;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                    fos = null;
                } catch (IOException ioe) {
                    throw ioe;
                }
            }
        }

        privateKeyFile.setWritable(false, false);
        privateKeyFile.setExecutable(false, false);
        privateKeyFile.setReadable(false, false);
        privateKeyFile.setReadable(true);
        privateKeyFile.setWritable(true);

        // set that this key is just created
        newKey = true;
    }

    /* Read Public Key */
    String encodedPublicKey = null;
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(publicKeyFile));
        encodedPublicKey = br.readLine();
    } catch (IOException ioe) {
        throw ioe;
    } finally {
        if (br != null) {
            try {
                br.close();
                br = null;
            } catch (IOException ioe) {
                throw ioe;
            }
        }
    }

    /* Generate key pair in Amazon if necessary */
    try {
        /* Get current key pair in Amazon */
        DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
        ec2.describeKeyPairs(describeKeyPairsRequest.withKeyNames(keyPairName));

        /* If key exists and new key is created, delete old key and replace
         * with new one. Else, do nothing */
        if (newKey) {
            DeleteKeyPairRequest deleteKeyPairRequest = new DeleteKeyPairRequest(keyPairName);
            ec2.deleteKeyPair(deleteKeyPairRequest);
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest(keyPairName, encodedPublicKey);
            ec2.importKeyPair(importKeyPairRequest);
        }

    } catch (AmazonServiceException ase) {
        /* Key doesn't exists, import new key. */
        if (ase.getErrorCode().equals("InvalidKeyPair.NotFound")) {
            ImportKeyPairRequest importKeyPairRequest = new ImportKeyPairRequest(keyPairName, encodedPublicKey);
            ec2.importKeyPair(importKeyPairRequest);
        } else {
            throw ase;
        }
    }
}