@Test public void testIsKeyPairPresentTrue() { String keyName = "key-name"; when(ec2Client.describeKeyPairs( new DescribeKeyPairsRequest() .withKeyNames(keyName) ) ).thenReturn( new DescribeKeyPairsResult() .withKeyPairs( new KeyPairInfo() ) ); // invoke method under test assertTrue(ec2Service.isKeyPairPresent(keyName)); }
public KeyPair getKeyPair(String keyName) { KeyPair keyPair = null; if (!isNullOrEmpty(keyName)) { try { DescribeKeyPairsResult describeKeyPairs = ec2_.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyName)); List<KeyPairInfo> keyPairs = describeKeyPairs.getKeyPairs(); if (keyPairs != null && !keyPairs.isEmpty()) { KeyPairInfo keyPairInfo = keyPairs.get(0); keyPair = new KeyPair(keyPairInfo.getKeyName()).withKeyFingerprint(keyPairInfo.getKeyFingerprint()); } } catch (AmazonClientException exception) { LOG.debug("Error on describing keyPairs [{}] on [{}]. Error message: [{}]", keyName, credentials_.getProvider().getName(), exception.getMessage()); } } return keyPair; }
@Override public void importKeyPair(String keyName, String publicKey) throws AutoException { // キーペアがすでに登録されていたら何もしない DescribeKeyPairsRequest request = new DescribeKeyPairsRequest(); DescribeKeyPairsResult result = ec2Client.describeKeyPairs(request); List<KeyPairInfo> keyPairs = result.getKeyPairs(); for (KeyPairInfo keyPair : keyPairs) { if (keyPair.getKeyName().equals(keyName)) { log.info(platform.getPlatformName() + " の " + keyName + " はすでに登録されている為、キーのインポートをスキップします"); System.out.println("IMPORT_SKIPPED"); return; } } // インポート ImportKeyPairRequest request2 = new ImportKeyPairRequest(); request2.withKeyName(keyName); request2.withPublicKeyMaterial(publicKey); ec2Client.importKeyPair(request2); log.info(keyName + "のキーをインポートしました。"); }
private void validateExistingKeyPair(InstanceAuthentication instanceAuthentication, AwsCredentialView credentialView, String region) { String keyPairName = awsClient.getExistingKeyPairName(instanceAuthentication); if (StringUtils.isNoneEmpty(keyPairName)) { boolean keyPairIsPresentOnEC2 = false; try { AmazonEC2Client client = awsClient.createAccess(credentialView, region); DescribeKeyPairsResult describeKeyPairsResult = client.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName)); keyPairIsPresentOnEC2 = describeKeyPairsResult.getKeyPairs().stream().findFirst().isPresent(); } catch (RuntimeException e) { String errorMessage = String.format("Failed to get the key pair [name: '%s'] from EC2 [roleArn:'%s'], detailed message: %s.", keyPairName, credentialView.getRoleArn(), e.getMessage()); LOGGER.error(errorMessage, e); } if (!keyPairIsPresentOnEC2) { throw new CloudConnectorException(String.format("The key pair '%s' could not be found in the '%s' region of EC2.", keyPairName, region)); } } }
private List<KeyPairInfo> deleteKeyPair(String keypairName) { List<KeyPairInfo> keys; try { DescribeKeyPairsRequest query = new DescribeKeyPairsRequest().withKeyNames(keypairName); DescribeKeyPairsResult keysFound = ec2Client.describeKeyPairs(query); keys = keysFound.getKeyPairs(); } catch (AmazonServiceException exception) { keys = new LinkedList<>(); } if (keys.size() > 0) { DeleteKeyPairRequest deleteRequest = new DeleteKeyPairRequest().withKeyName(keypairName); ec2Client.deleteKeyPair(deleteRequest); } return keys; }
private void createKeyPair() throws IOException, FileNotFoundException { DescribeKeyPairsResult response = ec2.describeKeyPairs(); boolean check_key=false; for(KeyPairInfo key_pair : response.getKeyPairs()) { if(key_pair.getKeyName().equalsIgnoreCase(MY_KEY)) { check_key=true; break; } } if(!check_key) { File file=new File(System.getProperty("user.home")+"/.aws/"+MY_KEY+".pem"); if(!file.exists()) file.createNewFile(); else{ System.err.println("Connot create the key pair to access to the cluster!"); System.exit(1); } System.out.println("Create new key pair ~/.aws/"+MY_KEY+".pem"); CreateKeyPairRequest request = new CreateKeyPairRequest() .withKeyName(MY_KEY); CreateKeyPairResult responsetocreate = ec2.createKeyPair(request); PrintWriter print = new PrintWriter(file); print.print(responsetocreate.getKeyPair().getKeyMaterial()); print.close(); Runtime.getRuntime().exec("chmod 0400 "+System.getProperty("user.home")+"/.aws/"+MY_KEY+".pem"); } }
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()); } }
/** * Checks if a key pair is present in AWS EC2. * * @param keyName Friendly name for the key * @return If present */ 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; } }
@Test public void testIsKeyPairPresentFalse() { String keyName = "key-name"; when(ec2Client.describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyName))) .thenReturn(new DescribeKeyPairsResult()); // invoke method under test assertFalse(ec2Service.isKeyPairPresent(keyName)); }
/** * Validates the EC2 key name. * * @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); } } } }
/** * Returns the key name corresponding to the specified fingerprints, or {@code null} if it * cannot be determined. * * @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; }
public List<KeyPair> getKeyPairs() { List<KeyPair> keyPairs = new ArrayList<KeyPair>(); DescribeKeyPairsResult availableKeyPairs = ec2_.describeKeyPairs(); for (KeyPairInfo keyInfo : availableKeyPairs.getKeyPairs()) { keyPairs.add(new KeyPair(keyInfo.getKeyName()).withKeyFingerprint(keyInfo.getKeyFingerprint())); } return Collections.unmodifiableList(keyPairs); }
/** * {@inheritDoc} */ @Override public List<KeyPairInfo> getKeyPairs(Long userNo, Long platformNo) { // キーペアを取得 AwsProcessClient awsProcessClient = awsProcessClientFactory.createAwsProcessClient(userNo, platformNo); DescribeKeyPairsRequest request = new DescribeKeyPairsRequest(); DescribeKeyPairsResult result = awsProcessClient.getEc2Client().describeKeyPairs(request); List<KeyPairInfo> keyPairs = result.getKeyPairs(); // ソート Collections.sort(keyPairs, Comparators.COMPARATOR_KEY_PAIR_INFO); return keyPairs; }
private String describeKeyPairFingerPrint(AmazonEC2Client client, String keyName) { DescribeKeyPairsResult describeKeyPairsResult = client.describeKeyPairs(); for (KeyPairInfo keyPairInfo : describeKeyPairsResult.getKeyPairs()) { if (keyPairInfo.getKeyName().equals(keyName)) { return keyPairInfo.getKeyFingerprint(); } } return ""; }
/** * Load keypairs * * @return list of keypairs */ public static List<String> loadKeypairs() { List<String> resultList = new ArrayList<String>(); DescribeKeyPairsResult results = getEC2Client().describeKeyPairs(); for (KeyPairInfo key : results.getKeyPairs()) { resultList.add(key.getKeyName()); } return resultList; }
@Override public List<AbstractResource<?>> describeKeyPairs(Account account, Region region, DateTime dt, Ec2Filter... filters) { AmazonEC2 ec2 = findClient(account, region); DescribeKeyPairsRequest req = new DescribeKeyPairsRequest(); for (Ec2Filter filter : filters) { Filter f = new Filter().withName(filter.getName()).withValues(filter.getValues()); req.withFilters(f); } log.debug("start describing key pairs for account:{} in region:{} via api", account.getId() + "=>" + account.getName(), region); DescribeKeyPairsResult res = ec2.describeKeyPairs(req); return converter.toEc2KeyPairs(res.getKeyPairs(), account.getId(), region, dt); }
public void assertKeyNotFound(String keyName) { final DescribeKeyPairsRequest request = new DescribeKeyPairsRequest().withKeyNames(keyName); try { DescribeKeyPairsResult result = client.describeKeyPairs(request); fail("Found key " + result.getKeyPairs().get(0)); } catch (AmazonServiceException e) { assertThat(e.getErrorCode()).isEqualTo(ErrorCodes.KEYPAIR_NOT_FOUND); } }
private void assertKeyPairWasImportedAsExpected() { final DescribeKeyPairsRequest request = new DescribeKeyPairsRequest().withKeyNames(KEYPAIR_NAME); DescribeKeyPairsResult result = client.describeKeyPairs(request); assertThat(result.getKeyPairs()).hasSize(1); assertThat(result.getKeyPairs().get(0).getKeyFingerprint()).isEqualTo(TEST_KEY_FINGERPRINT); }
@Override public DescribeKeyPairsResult describeKeyPairs(DescribeKeyPairsRequest describeKeyPairsRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public DescribeKeyPairsResult describeKeyPairs() throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
private List<KeyPairInfo> listKeyPairs(AmazonEC2Client client) { DescribeKeyPairsResult describeKeyPairsResult = client.describeKeyPairs(); return describeKeyPairsResult.getKeyPairs(); }
@Override public boolean load(DescribeKeyPairsRequest request, ResultCapture<DescribeKeyPairsResult> extractor) { return resource.load(request, extractor); }
/** * Makes a call to the service to load this resource's attributes if they * are not loaded yet, and use a ResultCapture to retrieve the low-level * client response * The following request parameters will be populated from the data of this * <code>KeyPair</code> resource, and any conflicting parameter value set in * the request will be overridden: * <ul> * <li> * <b><code>KeyNames.0</code></b> * - mapped from the <code>Name</code> identifier. * </li> * </ul> * * <p> * * @return Returns {@code true} if the resource is not yet loaded when this * method was invoked, which indicates that a service call has been * made to retrieve the attributes. * @see DescribeKeyPairsRequest */ boolean load(DescribeKeyPairsRequest request, ResultCapture<DescribeKeyPairsResult> extractor);