List of usage examples for com.amazonaws.services.ec2.model ImportKeyPairRequest ImportKeyPairRequest
public ImportKeyPairRequest(String keyName, String publicKeyMaterial)
From source file:com.github.trask.sandbox.ec2.Ec2Service.java
License:Apache License
private void createKeyPair(String keyName, String privateKeyPath) throws FileNotFoundException, JSchException, IOException { if (!new File(privateKeyPath).exists()) { generateKey(privateKeyPath, keyName); }// w w w .j a va 2 s .c o m Reader r = new BufferedReader(new StringReader(FileUtils.readFileToString(new File(privateKeyPath)))); PEMReader pem = new PEMReader(r, new PasswordFinder() { public char[] getPassword() { // this will get called if the private key is password protected // TODO deal with this here/elsewhere? throw new PasswordNotSupportedException(); } }); java.security.KeyPair pair = (java.security.KeyPair) pem.readObject(); String publicKey = StringUtils.newStringIso8859_1(Base64.encodeBase64(pair.getPublic().getEncoded())); deleteKeyPairIfExists(keyName); ImportKeyPairRequest request = new ImportKeyPairRequest(keyName, publicKey); ec2.importKeyPair(request); }
From source file:com.nike.cerberus.service.Ec2Service.java
License:Apache License
/** * Import a key pair to AWS EC2.// ww w .j a va 2 s . c o m * * @param keyName Friendly name for the key * @param publicKeyMaterial Public key * @return Key name */ public String importKey(final String keyName, final String publicKeyMaterial) { final ImportKeyPairRequest request = new ImportKeyPairRequest(keyName, publicKeyMaterial); final ImportKeyPairResult result = ec2Client.importKeyPair(request); return result.getKeyName(); }
From source file:edu.umass.cs.aws.support.AWSEC2.java
License:Apache License
/** * * @param ec2// w w w . j av a 2 s. c o m * @param name * @param publicKeyMaterial */ public static void importKeyPair(AmazonEC2 ec2, String name, String publicKeyMaterial) { ImportKeyPairRequest newKeyRequest = new ImportKeyPairRequest(name, publicKeyMaterial); ec2.importKeyPair(newKeyRequest); }
From source file:integratedtoolkit.connectors.amazon.EC2.java
License:Apache License
public EC2(String name, HashMap<String, String> h) { this.providerName = name; // Connector parameters accessKeyId = h.get("Access Key Id"); secretKeyId = h.get("Secret key Id"); keyPairName = h.get("KeyPair name"); keyLocation = h.get("Key host location"); securityGroupName = h.get("SecurityGroup Name"); placementCode = h.get("Placement"); placement = getPlacement(placementCode); //Connector data init activeRequests = 0;/*from www . j a v a 2s.c o m*/ IPToName = new HashMap<String, String>(); IPToType = new HashMap<String, String>(); IPToStart = new HashMap<String, Long>(); check = false; terminate = false; smallCount = 0; largeCount = 0; xlargeCount = 0; accumulatedCost = 0.0f; known_hosts = new Integer(0); stats = new Integer(0); //Prepare Amazon for first use client = new AmazonEC2Client(new BasicAWSCredentials(accessKeyId, secretKeyId)); boolean found = false; DescribeKeyPairsResult dkpr = client.describeKeyPairs(); for (KeyPairInfo kp : dkpr.getKeyPairs()) { if (kp.getKeyName().compareTo(keyPairName) == 0) { found = true; break; } } if (!found) { try { ImportKeyPairRequest ikpReq = new ImportKeyPairRequest(keyPairName, getPublicKey()); client.importKeyPair(ikpReq); } catch (Exception e) { e.printStackTrace(); } } found = false; DescribeSecurityGroupsResult dsgr = client.describeSecurityGroups(); for (SecurityGroup sg : dsgr.getSecurityGroups()) { if (sg.getGroupName().compareTo(securityGroupName) == 0) { found = true; break; } } if (!found) { try { CreateSecurityGroupRequest sg = new CreateSecurityGroupRequest(securityGroupName, "description"); client.createSecurityGroup(sg); IpPermission ipp = new IpPermission(); ipp.setToPort(22); ipp.setFromPort(22); ipp.setIpProtocol("tcp"); ArrayList<String> ipranges = new ArrayList<String>(); ipranges.add("0.0.0.0/0"); ipp.setIpRanges(ipranges); ArrayList<IpPermission> list_ipp = new ArrayList<IpPermission>(); list_ipp.add(ipp); AuthorizeSecurityGroupIngressRequest asgi = new AuthorizeSecurityGroupIngressRequest( securityGroupName, list_ipp); client.authorizeSecurityGroupIngress(asgi); } catch (Exception e) { e.printStackTrace(); } } }
From source file:integratedtoolkit.connectors.amazon.EC2_2.java
License:Apache License
public EC2_2(String providerName, HashMap<String, String> props) { this.providerName = providerName; // Connector parameters accessKeyId = props.get("Access Key Id"); secretKeyId = props.get("Secret key Id"); keyPairName = props.get("KeyPair name"); keyLocation = props.get("Key host location"); securityGroupName = props.get("SecurityGroup Name"); placementCode = props.get("Placement"); placement = VM.translatePlacement(placementCode); ipToVmId = new HashMap<String, String>(); //totalCost = 0.0f; currentCostPerHour = 0.0f;/*from ww w. j a va 2 s . co m*/ deletedMachinesCost = 0.0f; vmIdToInfo = new HashMap<String, VM>(); terminate = false; check = false; vmsToDelete = new TreeSet<VM>(); vmsAlive = new LinkedList<VM>(); ipToConnection = Collections.synchronizedMap(new HashMap<String, Connection>()); client = new AmazonEC2Client(new BasicAWSCredentials(accessKeyId, secretKeyId)); // TODO: Only for EU (Ireland) client.setEndpoint("https://ec2.eu-west-1.amazonaws.com"); if (props.get("MaxVMCreationTime") != null) { MAX_VM_CREATION_TIME = props.get("MaxVMCreationTime"); } dead = new DeadlineThread(); dead.start(); boolean found = false; DescribeKeyPairsResult dkpr = client.describeKeyPairs(); for (KeyPairInfo kp : dkpr.getKeyPairs()) { if (kp.getKeyName().compareTo(keyPairName) == 0) { found = true; break; } } if (!found) { try { ImportKeyPairRequest ikpReq = new ImportKeyPairRequest(keyPairName, KeyManager.getPublicKey(keyLocation)); client.importKeyPair(ikpReq); } catch (Exception e) { e.printStackTrace(); } } found = false; DescribeSecurityGroupsResult dsgr = client.describeSecurityGroups(); for (SecurityGroup sg : dsgr.getSecurityGroups()) { if (sg.getGroupName().compareTo(securityGroupName) == 0) { found = true; break; } } if (!found) { try { CreateSecurityGroupRequest sg = new CreateSecurityGroupRequest(securityGroupName, "description"); client.createSecurityGroup(sg); IpPermission ipp = new IpPermission(); ipp.setToPort(22); ipp.setFromPort(22); ipp.setIpProtocol("tcp"); ArrayList<String> ipranges = new ArrayList<String>(); ipranges.add("0.0.0.0/0"); ipp.setIpRanges(ipranges); ArrayList<IpPermission> list_ipp = new ArrayList<IpPermission>(); list_ipp.add(ipp); AuthorizeSecurityGroupIngressRequest asgi = new AuthorizeSecurityGroupIngressRequest( securityGroupName, list_ipp); client.authorizeSecurityGroupIngress(asgi); } catch (Exception e) { e.printStackTrace(); } } }
From source file:jp.classmethod.aws.gradle.ec2.AmazonEC2ImportKeyTask.java
License:Apache License
@TaskAction public void importKey() { // to enable conventionMappings feature String keyName = getKeyName(); String publicKeyMaterial = getPublicKeyMaterial(); if (keyName == null) { throw new GradleException("keyName is required"); }// w ww. j a va 2s . c o m AmazonEC2PluginExtension ext = getProject().getExtensions().getByType(AmazonEC2PluginExtension.class); AmazonEC2 ec2 = ext.getClient(); if (isIfNotExists() == false || exists(ec2) == false) { importKeyPairResult = ec2.importKeyPair(new ImportKeyPairRequest(keyName, publicKeyMaterial)); getLogger().info("KeyPair imported: {}", importKeyPairResult.getKeyFingerprint()); } }
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"); /*/* ww w.j a va 2 s .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 a2s.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; } } }
From source file:org.excalibur.service.aws.ec2.EC2.java
License:Open Source License
@Override public String importKeyPair(final KeyPair keyPair) { synchronized (lock_) { String fingerprint;/*from w ww . ja v a 2s .c om*/ checkState(!isNullOrEmpty(keyPair.getKeyName())); checkState(!isNullOrEmpty(keyPair.getKeyMaterial())); KeyPair keyPair2 = getKeyPair(keyPair.getKeyName()); if (keyPair2 == null) { fingerprint = new AmazonEC2Client(awsCredentials_) .importKeyPair(new ImportKeyPairRequest(keyPair.getKeyName(), keyPair.getKeyMaterial())) .getKeyFingerprint(); } else { fingerprint = keyPair2.getKeyFingerprint(); } return fingerprint; } }
From source file:org.occiware.clouddriver.IAM.KeyPairOperation.java
License:Apache License
/** * Import key pair to AWS.//from w w w.j av a 2s . c o m * @param keyPair a keypair data object with a public key and a name set.. * @throws KeyPairOperationException Exception when aws exception when importing a new key pair. */ public void importKeyPair(KeyPairDO keyPair) throws KeyPairOperationException { String keyPairName = keyPair.getKeyPairName(); String encodedPublicKey = keyPair.getPublicKey(); // Base 64 encoded, DER if (keyPairName == null) { throw new KeyPairOperationException("The keyPair name must be provided for operation import KeyPair."); } if (encodedPublicKey == null) { throw new KeyPairOperationException( "The keyPair public key encoded base 64, DER must be provided for operation importKeyPair."); } try { ImportKeyPairResult result = ec2Client.getClientInstance() .importKeyPair(new ImportKeyPairRequest(keyPairName, encodedPublicKey)); keyPair.setKeyPairName(result.getKeyName()); keyPair.setFingerPrintPublicKey(result.getKeyFingerprint()); ec2Client.getClientInstance().shutdown(); } catch (AmazonServiceException ase) { logger.error("Exception thrown from aws : " + ase.getErrorCode() + " --> " + ase.getErrorMessage()); throw new KeyPairOperationException(ase); } catch (AmazonClientException ace) { logger.error("Exception thrown from aws : " + ace.getMessage()); throw new KeyPairOperationException(ace); } finally { ec2Client.getClientInstance().shutdown(); } }