/* 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;
}
}