@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 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()); } }
/** * 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 FormValidation doGenerateKey(StaplerResponse rsp, URL ec2EndpointUrl, boolean useInstanceProfileForCredentials, String accessId, String secretKey) throws IOException, ServletException { try { AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey); AmazonEC2 ec2 = connect(credentialsProvider, ec2EndpointUrl); List<KeyPairInfo> existingKeys = ec2.describeKeyPairs().getKeyPairs(); int n = 0; while (true) { boolean found = false; for (KeyPairInfo k : existingKeys) { if (k.getKeyName().equals("hudson-" + n)) { found = true; } } if (!found) { break; } n++; } CreateKeyPairRequest request = new CreateKeyPairRequest("hudson-" + n); KeyPair key = ec2.createKeyPair(request).getKeyPair(); rsp.addHeader("script", "findPreviousFormItem(button,'privateKey').value='" + key.getKeyMaterial().replace("\n", "\\n") + "'"); return FormValidation.ok(Messages.EC2Cloud_Success()); } catch (AmazonClientException e) { LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e); return FormValidation.error(e.getMessage()); } }
public void load() { List<KeyPairInfo> remoteKeyPairs = AWS.ec2.ec2.describeKeyPairs(new DescribeKeyPairsRequest() .withFilters(new Filter("key-name").withValues(env.name + ":*"))).getKeyPairs(); for (KeyPairInfo remoteKeyPair : remoteKeyPairs) { String keyPairId = keyPairId(env.name, remoteKeyPair.getKeyName()); if (keyPairId != null) { KeyPair keyPair = resources.find(KeyPair.class, keyPairId) .orElseGet(() -> resources.add(new KeyPair(keyPairId, remoteKeyPair.getKeyName()))); keyPair.remoteKeyPair = remoteKeyPair; keyPair.foundInRemote(); } } }
public void createKeyPair(KeyPair keyPair) throws IOException { com.amazonaws.services.ec2.model.KeyPair remoteKeyPair = AWS.ec2.createKeyPair(keyPair.name); writeKeyFile(keyPair.name, remoteKeyPair.getKeyMaterial()); keyPair.remoteKeyPair = new KeyPairInfo() .withKeyName(remoteKeyPair.getKeyName()) .withKeyFingerprint(remoteKeyPair.getKeyFingerprint()); }
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); }
@Override public List<KeyPairInfo> getKeyPairs(Long userNo, Long platformNo) { List<KeyPairInfo> infos = new ArrayList<KeyPairInfo>(); infos.add(new KeyPairInfo().withKeyName("key01")); infos.add(new KeyPairInfo().withKeyName("key02")); infos.add(new KeyPairInfo().withKeyName("key03")); return infos; }
@Override protected KeyPairInfo convertObject(com.xerox.amazonws.ec2.KeyPairInfo from) { KeyPairInfo to = new KeyPairInfo(); to.setKeyName(from.getKeyName()); to.setKeyFingerprint(from.getKeyFingerprint()); return to; }
/** * {@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 boolean checkKeyName(Long userNo, Long platformNo, String keyName) { List<KeyPairInfo> keyPairs = awsDescribeService.getKeyPairs(userNo, platformNo); for (KeyPairInfo keyPair : keyPairs) { if (StringUtils.equals(keyName, keyPair.getKeyName())) { return true; } } return false; }
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 CloudSshKeys sshKeys(CloudCredential cloudCredential, Region region, Map<String, String> filters) { Map<String, Set<CloudSshKey>> result = new HashMap<>(); for (Region actualRegion : awsPlatformParameters.regions().types()) { // If region is provided then should filter for those region if (regionMatch(actualRegion, region)) { Set<CloudSshKey> cloudSshKeys = new HashSet<>(); AmazonEC2Client ec2Client = awsClient.createAccess(new AwsCredentialView(cloudCredential), actualRegion.value()); //create sshkey filter view PlatformResourceSshKeyFilterView filter = new PlatformResourceSshKeyFilterView(filters); DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest(); // If the filtervalue is provided then we should filter only for those securitygroups if (!Strings.isNullOrEmpty(filter.getKeyName())) { describeKeyPairsRequest.withKeyNames(filter.getKeyName()); } for (KeyPairInfo keyPairInfo : ec2Client.describeKeyPairs(describeKeyPairsRequest).getKeyPairs()) { Map<String, Object> properties = new HashMap<>(); properties.put("fingerPrint", keyPairInfo.getKeyFingerprint()); cloudSshKeys.add(new CloudSshKey(keyPairInfo.getKeyName(), properties)); } result.put(actualRegion.value(), cloudSshKeys); } } return new CloudSshKeys(result); }
public List<AbstractResource<?>> toEc2KeyPairs(List<KeyPairInfo> keyPairs, String accountId, Region region, DateTime dt) { List<AbstractResource<?>> resources = new ArrayList<>(); for (KeyPairInfo keyPairInfo : keyPairs) { Ec2KeyPair ec2KeyPair = new Ec2KeyPair(); conf(ec2KeyPair, accountId, region, dt); ec2KeyPair.setResource(keyPairInfo); resources.add(ec2KeyPair); } log.debug("{} key pairs found via api and converted to Ec2KeyPair", resources.size()); return resources; }
@Override @SuppressWarnings("rawtypes") protected boolean isEqual(AbstractResource newResource) { KeyPairInfo oldKeyPairInfo = this.getResource(); KeyPairInfo newKeyPairInfo = (KeyPairInfo) newResource.getResource(); return oldKeyPairInfo.equals(newKeyPairInfo); }
@Override protected void update(List<Event> result, Ec2KeyPair oldResource, Ec2KeyPair newResource) { KeyPairInfo oldKeyPairInfo = oldResource.getResource(); KeyPairInfo newKeyPairInfo = newResource.getResource(); if (notEqual(oldKeyPairInfo.getKeyFingerprint(), newKeyPairInfo.getKeyFingerprint())) { result.add(createEvent(oldResource, newResource, EventType.Ec2_Key_Pair_Update)); } }
@Test public void shouldCreateKeyPairWithFilename() throws IOException { String keypairName = "CfnAssist_Test"; deleteKeyPair(keypairName); String filename = "testFilenameForPem.tmp"; Path path = Paths.get(filename); Files.deleteIfExists(path); String[] args = CLIArgBuilder.createKeyPair(filename); Main main = new Main(args); int commandResult = main.parse(); List<KeyPairInfo> keys = deleteKeyPair(keypairName); // now do the asserts assertEquals(0, commandResult); assertEquals(1, keys.size()); assertEquals(keypairName, keys.get(0).getKeyName()); assertTrue(Files.exists(path)); Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(Paths.get(filename), LinkOption.NOFOLLOW_LINKS); EnvironmentSetupForTests.checkKeyPairFilePermissions(permissions); Files.deleteIfExists(path); }
private void loadData() { AwsDescribeService awsDescribeService = BeanContext.getBean(AwsDescribeService.class); Long platformNo = platform.getPlatform().getPlatformNo(); // キーペア情報を取得 List<KeyPairInfo> keyPairInfos = awsDescribeService.getKeyPairs(ViewContext.getUserNo(), platformNo); List<String> keyNames = new ArrayList<String>(); for (KeyPairInfo keyPairInfo : keyPairInfos) { keyNames.add(keyPairInfo.getKeyName()); } this.keyNames = keyNames; // セキュリティグループ情報を取得 List<String> groupNames = new ArrayList<String>(); List<SecurityGroup> securityGroups = awsDescribeService.getSecurityGroups(ViewContext.getUserNo(), platformNo); for (SecurityGroup securityGroup : securityGroups) { groupNames.add(securityGroup.getGroupName()); } this.groupNames = groupNames; // VPCの場合 if (BooleanUtils.isTrue(platform.getPlatformAws().getVpc())) { // サブネット情報の取得 List<Subnet> subnets = awsDescribeService.getSubnets(ViewContext.getUserNo(), platformNo); this.subnets = subnets; } // 非VPCの場合 else { // ゾーン情報の取得 List<AvailabilityZone> zones = awsDescribeService.getAvailabilityZones(ViewContext.getUserNo(), platformNo); if (BooleanUtils.isNotTrue(platform.getPlatformAws().getEuca())) { // EC2の場合、空行を先頭に追加してゾーンを無指定にできるようにする zones.add(0, new AvailabilityZone()); } this.zones = zones; } // ElasticIp情報の取得 List<AwsAddress> elasticIps = awsDescribeService.getAddresses(ViewContext.getUserNo(), platformNo); this.elasticIps = elasticIps; }
private void makeAwsData(Farm farm, Long instanceNo, String instanceType, PlatformAws platformAws, ImageAws imageAws) { // 引数チェック String[] instanceTypes = imageAws.getInstanceTypes().split(","); if (!ArrayUtils.contains(instanceTypes, instanceType)) { throw new AutoApplicationException("ECOMMON-000001", "instanceType"); } // AWSインスタンスの作成 AwsInstance awsInstance = new AwsInstance(); awsInstance.setInstanceNo(instanceNo); awsInstance.setInstanceType(instanceType); //KeyName AwsCertificate awsCertificate = awsCertificateDao.read(farm.getUserNo(), platformAws.getPlatformNo()); //キーペアの取得 List<KeyPairInfo> keyPairs = awsDescribeService.getKeyPairs(farm.getUserNo(), platformAws.getPlatformNo()); String keyName = null; // AWS認証情報に設定されているデフォルトキーペアを設定 for (KeyPairInfo keyPair : keyPairs) { if (StringUtils.equals(awsCertificate.getDefKeypair(), keyPair.getKeyName())) { keyName = keyPair.getKeyName(); break; } } if (keyName == null && keyPairs.size() > 0) { //デフォルトキーペアが存在しない場合は1件目 keyName = keyPairs.get(0).getKeyName(); } awsInstance.setKeyName(keyName); if (platformAws.getEuca() == false && platformAws.getVpc()) { // VPCの場合 // SubnetId & AvailabilityZone List<Subnet> subnets = awsDescribeService.getSubnets(farm.getUserNo(), platformAws.getPlatformNo()); Subnet subnet = null; for (Subnet subnet2 : subnets) { //デフォルトサブネットを設定 if (StringUtils.equals(awsCertificate.getDefSubnet(), subnet2.getSubnetId())) { subnet = subnet2; break; } } // デフォルトサブネットが指定されていない場合、1つ目のサブネットを設定する if (subnet == null && subnets.size() > 0) { subnet = subnets.get(0); } if (subnet != null) { awsInstance.setSubnetId(subnet.getSubnetId()); awsInstance.setAvailabilityZone(subnet.getAvailabilityZone()); } } else { // VPCでない場合 // AvailabilityZone String zoneName = platformAws.getAvailabilityZone(); if (StringUtils.isEmpty(zoneName) && platformAws.getEuca()) { // デフォルトのゾーン名が指定されておらず、Eucalyptusの場合のみAPIでゾーン名を取得する List<AvailabilityZone> availabilityZones = awsDescribeService.getAvailabilityZones(farm.getUserNo(), platformAws.getPlatformNo()); zoneName = availabilityZones.get(0).getZoneName(); } awsInstance.setAvailabilityZone(zoneName); } // SecurityGroup String groupName = null; List<SecurityGroup> securityGroups = awsDescribeService.getSecurityGroups(farm.getUserNo(), platformAws.getPlatformNo()); groupName = setSecurityGroupAws(securityGroups, "aws.defaultSecurityGroup"); awsInstance.setSecurityGroups(groupName); // RootSize if (imageAws.getRootSize() != null) { awsInstance.setRootSize(imageAws.getRootSize()); } awsInstanceDao.create(awsInstance); }
@Override public int compare(KeyPairInfo o1, KeyPairInfo o2) { return o1.getKeyName().compareTo(o2.getKeyName()); }
private List<KeyPairInfo> listKeyPairs(AmazonEC2Client client) { DescribeKeyPairsResult describeKeyPairsResult = client.describeKeyPairs(); return describeKeyPairsResult.getKeyPairs(); }
@Override public List<KeyPairInfo> listKeyPairs(AWSCredentials credentials) { return listKeyPairs(amazonEC2ClientFactory.createAmazonEC2Client(credentials)); }
@RequestMapping(method = RequestMethod.GET, value = {"/keypairs"}) @ResponseBody public List<KeyPairInfo> listKeyPairs(ModelMap model, @RequestParam("accessKey") String accessKey, @RequestParam("secretKey") String secretKey) { return awsec2Service.listKeyPairs(awsCredentialsFactory.createSimpleAWSCredentials(accessKey, secretKey)); }
public List<KeyPairInfo> getKeyPairs(Long userNo, Long platformNo);
List<KeyPairInfo> listKeyPairs(AWSCredentials credentials);