List of usage examples for com.amazonaws.services.ec2.model KeyPair getKeyName
public String getKeyName()
The name of the key pair.
From source file:AwsSample.java
License:Open Source License
public static void main(String[] args) throws Exception { BasicAWSCredentials credentials = new BasicAWSCredentials("", ""); /********************************************* * /*from w w w .java 2s. c o m*/ * #1 Create Amazon Client object * *********************************************/ System.out.println("#1 Create Amazon Client object"); ec2 = new AmazonEC2Client(credentials); try { /********************************************* * * #2 Describe Availability Zones. * *********************************************/ System.out.println("#2 Describe Availability Zones."); DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones(); System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() + " Availability Zones."); /********************************************* * * #3 Describe Available Images * *********************************************/ System.out.println("#3 Describe Available Images"); DescribeImagesResult dir = ec2.describeImages(); List<Image> images = dir.getImages(); System.out.println("You have " + images.size() + " Amazon images"); /********************************************* * * #4 Describe Key Pair * *********************************************/ System.out.println("#9 Describe Key Pair"); DescribeKeyPairsResult dkr = ec2.describeKeyPairs(); System.out.println(dkr.toString()); /********************************************* * * #5 Describe Current Instances * *********************************************/ System.out.println("#4 Describe Current Instances"); DescribeInstancesResult describeInstancesRequest = ec2.describeInstances(); List<Reservation> reservations = describeInstancesRequest.getReservations(); Set<Instance> instances = new HashSet<Instance>(); // add all instances to a Set. for (Reservation reservation : reservations) { instances.addAll(reservation.getInstances()); } System.out.println("You have " + instances.size() + " Amazon EC2 instance(s)."); for (Instance ins : instances) { // instance id String instanceId = ins.getInstanceId(); // instance state InstanceState is = ins.getState(); System.out.println(instanceId + " " + is.getName()); } /////////////////////////////////////// String Temp_Group = "Testgroup1"; //name of the group CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest(Temp_Group, "temporal group"); ec2.createSecurityGroup(r1); AuthorizeSecurityGroupIngressRequest r2 = new AuthorizeSecurityGroupIngressRequest(); r2.setGroupName(Temp_Group); /*************the property of http*****************/ IpPermission permission = new IpPermission(); permission.setIpProtocol("tcp"); permission.setFromPort(80); permission.setToPort(80); List<String> ipRanges = new ArrayList<String>(); ipRanges.add("0.0.0.0/0"); permission.setIpRanges(ipRanges); /*************the property of SSH**********************/ IpPermission permission1 = new IpPermission(); permission1.setIpProtocol("tcp"); permission1.setFromPort(22); permission1.setToPort(22); List<String> ipRanges1 = new ArrayList<String>(); ipRanges1.add("0.0.0.0/22"); permission1.setIpRanges(ipRanges1); /*************the property of https**********************/ IpPermission permission2 = new IpPermission(); permission2.setIpProtocol("tcp"); permission2.setFromPort(443); permission2.setToPort(443); List<String> ipRanges2 = new ArrayList<String>(); ipRanges2.add("0.0.0.0/0"); permission2.setIpRanges(ipRanges2); /*************the property of tcp**********************/ IpPermission permission3 = new IpPermission(); permission3.setIpProtocol("tcp"); permission3.setFromPort(0); permission3.setToPort(65535); List<String> ipRanges3 = new ArrayList<String>(); ipRanges3.add("0.0.0.0/0"); permission3.setIpRanges(ipRanges3); /**********************add rules to the group*********************/ List<IpPermission> permissions = new ArrayList<IpPermission>(); permissions.add(permission); permissions.add(permission1); permissions.add(permission2); permissions.add(permission3); r2.setIpPermissions(permissions); ec2.authorizeSecurityGroupIngress(r2); List<String> groupName = new ArrayList<String>(); groupName.add(Temp_Group);//wait to out our instance into this group /********************************************* * * #6.2 Create a New Key Pair * *********************************************/ CreateKeyPairRequest newKeyRequest = new CreateKeyPairRequest(); newKeyRequest.setKeyName("Test_Key2"); CreateKeyPairResult keyresult = ec2.createKeyPair(newKeyRequest); /************************print the properties of this key*****************/ KeyPair kp = new KeyPair(); kp = keyresult.getKeyPair(); System.out.println("The key we created is = " + kp.getKeyName() + "\nIts fingerprint is=" + kp.getKeyFingerprint() + "\nIts material is= \n" + kp.getKeyMaterial()); String fileName = "C:/Users/Akhil/workspace/Test_Key2.pem"; File distFile = new File(fileName); BufferedReader bufferedReader = new BufferedReader(new StringReader(kp.getKeyMaterial())); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(distFile)); char buf[] = new char[1024]; int len; while ((len = bufferedReader.read(buf)) != -1) { bufferedWriter.write(buf, 0, len); } bufferedWriter.flush(); bufferedReader.close(); bufferedWriter.close(); //String myinstance; /********************************************* * * #6 Create an Instance * *********************************************/ System.out.println("#5 Create an Instance"); String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI int minInstanceCount = 1; // create 1 instance int maxInstanceCount = 1; RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount); rir.setKeyName("Test_Key2"); rir.withSecurityGroups("Testgroup1"); RunInstancesResult result = ec2.runInstances(rir); //get instanceId from the result List<Instance> resultInstance = result.getReservation().getInstances(); String createdInstanceId = null; String myAvailabilityZone = null; for (Instance ins : resultInstance) { createdInstanceId = ins.getInstanceId(); System.out.println("New instance has been created: " + ins.getInstanceId()); //myinstance = ins.getInstanceId(); } Thread.currentThread().sleep(60000); /********************************************* * * * Create a New Volume and attach it * ***********************************************/ List<Instance> resultInstance2 = result.getReservation().getInstances(); createdInstanceId = null; for (Instance ins : resultInstance2) { createdInstanceId = ins.getInstanceId(); System.out.println("New instance has been created: " + ins.getInstanceId());//print the instance ID /********************************************* * * #6.4 Create an Instance * *********************************************/ CreateVolumeRequest newVol = new CreateVolumeRequest(1, "us-east-1a"); CreateVolumeResult volresult = ec2.createVolume(newVol); Volume vol1 = volresult.getVolume(); String volId = vol1.getVolumeId(); Thread.currentThread().sleep(30000); AttachVolumeRequest attachRequest = new AttachVolumeRequest().withInstanceId(createdInstanceId) .withVolumeId(volId); attachRequest.withDevice("/dev/sda5"); ec2.attachVolume(attachRequest); System.out.println("EBS volume has been attached and the volume ID is: " + volId); } /********************************************* * * #7 Create a 'tag' for the new instance. * *********************************************/ System.out.println("#6 Create a 'tag' for the new instance."); List<String> resources = new LinkedList<String>(); List<Tag> tags = new LinkedList<Tag>(); Tag nameTag = new Tag("Akhil", "MyFirstInstance"); resources.add(createdInstanceId); tags.add(nameTag); CreateTagsRequest ctr = new CreateTagsRequest(resources, tags); ec2.createTags(ctr); /********************************************* * * #8 Stop/Start an Instance * *********************************************/ System.out.println("#7 Stop the Instance"); List<String> instanceIds = new LinkedList<String>(); instanceIds.add(createdInstanceId); //stop StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds); ec2.stopInstances(stopIR); //start StartInstancesRequest startIR = new StartInstancesRequest(instanceIds); ec2.startInstances(startIR); System.out.println("#8 Getting DNS, IP."); DescribeInstancesRequest request = new DescribeInstancesRequest(); request.setInstanceIds(instanceIds); DescribeInstancesResult result1 = ec2.describeInstances(request); List<Reservation> reservations1 = result1.getReservations(); List<Instance> instances1; for (Reservation res : reservations1) { instances1 = res.getInstances(); for (Instance ins1 : instances1) { System.out .println("The public DNS is: " + ins1.getPublicDnsName() + "\n" + ins1.getRamdiskId()); System.out.println("The private IP is: " + ins1.getPrivateIpAddress()); System.out.println("The public IP is: " + ins1.getPublicIpAddress()); } /********************************************* * #10 Terminate an Instance * *********************************************/ System.out.println("#8 Terminate the Instance"); TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds); //ec2.terminateInstances(tir); /********************************************* * * #11 shutdown client object * *********************************************/ ec2.shutdown(); } } catch (AmazonServiceException ase) { System.out.println("Caught Exception: " + ase.getMessage()); System.out.println("Reponse Status Code: " + ase.getStatusCode()); System.out.println("Error Code: " + ase.getErrorCode()); System.out.println("Request ID: " + ase.getRequestId()); } }
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
License:Apache License
/** * <p>/* ww w .j av a 2 s. c om*/ * Create an Amazon IAM account and send the details by email. * </p> * <p> * Created elements: * </p> * <ul> * <li>password to login to the management console if none exists,</li> * <li>accesskey if none is active,</li> * <li></li> * </ul> * * @param userName valid email used as userName of the created account. */ public void createUser(@Nonnull final String userName, GetGroupResult groupDescriptor, String keyPairName) throws Exception { Preconditions.checkNotNull(userName, "Given userName can NOT be null"); logger.info("Process user {}", userName); List<String> userAccountChanges = Lists.newArrayList(); Map<String, String> templatesParams = Maps.newHashMap(); templatesParams.put("awsCredentialsHome", "~/.aws"); templatesParams.put("awsCommandLinesHome", "/opt/amazon-aws"); User user; try { user = iam.getUser(new GetUserRequest().withUserName(userName)).getUser(); } catch (NoSuchEntityException e) { logger.debug("User {} does not exist, create it", userName, e); user = iam.createUser(new CreateUserRequest(userName)).getUser(); userAccountChanges.add("Create user"); } List<BodyPart> attachments = Lists.newArrayList(); // AWS WEB MANAGEMENT CONSOLE LOGIN & PASSWORD try { LoginProfile loginProfile = iam.getLoginProfile(new GetLoginProfileRequest(user.getUserName())) .getLoginProfile(); templatesParams.put("loginUserName", loginProfile.getUserName()); templatesParams.put("loginPassword", "#your password has already been generated and sent to you#"); logger.info("Login profile already exists {}", loginProfile); } catch (NoSuchEntityException e) { // manually add a number to ensure amazon policy is respected String password = RandomStringUtils.randomAlphanumeric(10) + random.nextInt(10); LoginProfile loginProfile = iam .createLoginProfile(new CreateLoginProfileRequest(user.getUserName(), password)) .getLoginProfile(); userAccountChanges.add("Create user.login"); templatesParams.put("loginUserName", loginProfile.getUserName()); templatesParams.put("loginPassword", password); } // ADD USER TO GROUP Group group = groupDescriptor.getGroup(); List<User> groupMembers = groupDescriptor.getUsers(); boolean isUserInGroup = Iterables.any(groupMembers, new Predicate<User>() { public boolean apply(User groupMember) { return userName.equals(groupMember.getUserName()); } ; }); if (!isUserInGroup) { logger.debug("Add user {} to group {}", user, group); iam.addUserToGroup(new AddUserToGroupRequest(group.getGroupName(), user.getUserName())); groupMembers.add(user); userAccountChanges.add("Add user to group"); } // ACCESS KEY boolean activeAccessKeyExists = false; ListAccessKeysResult listAccessKeysResult = iam .listAccessKeys(new ListAccessKeysRequest().withUserName(user.getUserName())); for (AccessKeyMetadata accessKeyMetadata : listAccessKeysResult.getAccessKeyMetadata()) { StatusType status = StatusType.fromValue(accessKeyMetadata.getStatus()); if (StatusType.Active.equals(status)) { logger.info("Access key {} ({}) is already active, don't create another one.", accessKeyMetadata.getAccessKeyId(), accessKeyMetadata.getCreateDate()); activeAccessKeyExists = true; templatesParams.put("accessKeyId", accessKeyMetadata.getAccessKeyId()); templatesParams.put("accessKeySecretId", "#accessKey has already been generated and the secretId has been sent to you#"); break; } } if (!activeAccessKeyExists) { AccessKey accessKey = iam.createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName())) .getAccessKey(); userAccountChanges.add("Create user.accessKey"); logger.debug("Created access key {}", accessKey); templatesParams.put("accessKeyId", accessKey.getAccessKeyId()); templatesParams.put("accessKeySecretId", accessKey.getSecretAccessKey()); // email attachment: aws-credentials.txt { BodyPart awsCredentialsBodyPart = new MimeBodyPart(); awsCredentialsBodyPart.setFileName("aws-credentials.txt"); templatesParams.put("attachedCredentialsFileName", awsCredentialsBodyPart.getFileName()); String awsCredentials = FreemarkerUtils.generate(templatesParams, "/fr/xebia/cloud/amazon/aws/iam/aws-credentials.txt.ftl"); awsCredentialsBodyPart.setContent(awsCredentials, "text/plain"); attachments.add(awsCredentialsBodyPart); } } // SSH KEY PAIR if (keyPairName == null) { // If keyPairName is null, generate it from the username if (userName.endsWith("@xebia.fr") || userName.endsWith("@xebia.com")) { keyPairName = userName.substring(0, userName.indexOf("@xebia.")); } else { keyPairName = userName.replace("@", "_at_").replace(".", "_dot_").replace("+", "_plus_"); } } try { List<KeyPairInfo> keyPairInfos = ec2 .describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName)).getKeyPairs(); KeyPairInfo keyPairInfo = Iterables.getOnlyElement(keyPairInfos); logger.info("SSH key {} already exists. Don't overwrite it.", keyPairInfo.getKeyName()); templatesParams.put("sshKeyName", keyPairInfo.getKeyName()); templatesParams.put("sshKeyFingerprint", keyPairInfo.getKeyFingerprint()); String sshKeyFileName = keyPairName + ".pem"; URL sshKeyFileURL = Thread.currentThread().getContextClassLoader().getResource(sshKeyFileName); if (sshKeyFileURL != null) { logger.info("SSH Key file {} found.", sshKeyFileName); BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(sshKeyFileName); templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName()); keyPairBodyPart.setContent(Resources.toString(sshKeyFileURL, Charsets.ISO_8859_1), "application/x-x509-ca-cert"); attachments.add(keyPairBodyPart); } else { logger.info("SSH Key file {} NOT found.", sshKeyFileName); } } catch (AmazonServiceException e) { if ("InvalidKeyPair.NotFound".equals(e.getErrorCode())) { // ssh key does not exist, create it KeyPair keyPair = ec2.createKeyPair(new CreateKeyPairRequest(keyPairName)).getKeyPair(); userAccountChanges.add("Create ssh key"); logger.info("Created ssh key {}", keyPair); templatesParams.put("sshKeyName", keyPair.getKeyName()); templatesParams.put("sshKeyFingerprint", keyPair.getKeyFingerprint()); BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(keyPair.getKeyName() + ".pem"); templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName()); keyPairBodyPart.setContent(keyPair.getKeyMaterial(), "application/x-x509-ca-cert"); attachments.add(keyPairBodyPart); } else { throw e; } } // X509 SELF SIGNED CERTIFICATE Collection<SigningCertificate> certificates = iam .listSigningCertificates(new ListSigningCertificatesRequest().withUserName(userName)) .getCertificates(); // filter active certificates certificates = Collections2.filter(certificates, new Predicate<SigningCertificate>() { @Override public boolean apply(SigningCertificate signingCertificate) { return StatusType.Active.equals(StatusType.fromValue(signingCertificate.getStatus())); } }); if (certificates.isEmpty()) { java.security.KeyPair x509KeyPair = keyPairGenerator.generateKeyPair(); X509Certificate x509Certificate = generateSelfSignedX509Certificate(userName, x509KeyPair); String x509CertificatePem = Pems.pem(x509Certificate); UploadSigningCertificateResult uploadSigningCertificateResult = iam.uploadSigningCertificate( // new UploadSigningCertificateRequest(x509CertificatePem).withUserName(user.getUserName())); SigningCertificate signingCertificate = uploadSigningCertificateResult.getCertificate(); templatesParams.put("x509CertificateId", signingCertificate.getCertificateId()); userAccountChanges.add("Create x509 certificate"); logger.info("Created x509 certificate {}", signingCertificate); // email attachment: x509 private key { BodyPart x509PrivateKeyBodyPart = new MimeBodyPart(); x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem"); templatesParams.put("attachedX509PrivateKeyFileName", x509PrivateKeyBodyPart.getFileName()); String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate()); x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/x-x509-ca-cert"); attachments.add(x509PrivateKeyBodyPart); } // email attachment: x509 certifiate pem { BodyPart x509CertificateBodyPart = new MimeBodyPart(); x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem"); templatesParams.put("attachedX509CertificateFileName", x509CertificateBodyPart.getFileName()); x509CertificateBodyPart.setContent(x509CertificatePem, "application/x-x509-ca-cert"); attachments.add(x509CertificateBodyPart); } } else { SigningCertificate signingCertificate = Iterables.getFirst(certificates, null); logger.info("X509 certificate {} already exists", signingCertificate.getCertificateId()); templatesParams.put("x509CertificateId", signingCertificate.getCertificateId()); } sendEmail(templatesParams, attachments, userName); }
From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java
License:Apache License
/** * Create an Amazon IAM account with a password, a secret key and member of * "Admins". The password, access key and secret key are sent by email. * // w w w. java2 s. c o m * @param userName * valid email used as userName of the created account. */ public void createUsers(String userName) { CreateUserRequest createUserRequest = new CreateUserRequest(userName); CreateUserResult createUserResult = iam.createUser(createUserRequest); User user = createUserResult.getUser(); String password = RandomStringUtils.randomAlphanumeric(8); iam.createLoginProfile(new CreateLoginProfileRequest(user.getUserName(), password)); iam.addUserToGroup(new AddUserToGroupRequest("Admins", user.getUserName())); CreateAccessKeyResult createAccessKeyResult = iam .createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName())); AccessKey accessKey = createAccessKeyResult.getAccessKey(); // SSH KeyPair sshKeyPair = createOrOverWriteSshKeyPair(userName); // X509 java.security.KeyPair x509KeyPair = createRsaKeyPair(); X509Certificate x509Certificate = createX509Certificate(userName, x509KeyPair); SigningCertificate signingCertificate; try { UploadSigningCertificateResult uploadSigningCertificateResult = iam .uploadSigningCertificate(new UploadSigningCertificateRequest(Pems.pem(x509Certificate)) .withUserName(user.getUserName())); signingCertificate = uploadSigningCertificateResult.getCertificate(); } catch (CertificateEncodingException e) { throw Throwables.propagate(e); } System.out.println("CREATED userName=" + user.getUserName() + "\tpassword=" + password + "\taccessKeyId=" + accessKey.getAccessKeyId() + "\tsecretAccessKey=" + accessKey.getSecretAccessKey() + "\tsshKeyPair=" + sshKeyPair.getKeyName() + "\tx509Certificate=" + signingCertificate.getCertificateId()); String subject = "Xebia France Amazon EC2 Credentials"; String body = "Hello,\n"; body += "\n"; body += "Here are the credentials to connect to Xebia Amazon AWS/EC2 training infrastructure:\n"; body += "\n"; body += "User Name: " + user.getUserName() + "\n"; body += "Password: " + password + "\n"; body += "\n"; body += "Access Key Id: " + accessKey.getAccessKeyId() + "\n"; body += "Secret Access Key: " + accessKey.getSecretAccessKey() + "\n"; body += "\n"; body += "SSH private key pair '" + sshKeyPair.getKeyName() + "' attached, rename it as '" + sshKeyPair.getKeyName() + ".pem" + "'n"; body += "\n"; body += "The authentication page is https://xebia-france.signin.aws.amazon.com/console"; body += "\n"; body += "Don't hesitate to connect to Amazon AWS, to play with it but please DO NOT FORGET TO STOP INSTANCES OR IF POSSIBLE TERMINATE THEM AFTER USING THEM.\n"; body += "Letting instances started would cost unnecessary money to Xebia.\n"; body += "\n"; body += "\n"; body += "Thanks,\n"; body += "\n"; body += "Cyrille"; try { sendEmail(subject, body, accessKey, sshKeyPair, x509KeyPair, x509Certificate, signingCertificate, "cyrille@cyrilleleclerc.com", user.getUserName()); } catch (Exception e) { e.printStackTrace(); } }
From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java
License:Apache License
/** * Send email with Amazon Simple Email Service. * <p/>//from w ww . j a v a2 s.c o m * * Please note that the sender (ie 'from') must be a verified address (see * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)} * ). * <p/> * * Please note that the sender is a CC of the meail to ease support. * <p/> * * @param subject * @param body * @param from * @param toAddresses * @throws MessagingException * @throws AddressException */ public void sendEmail(String subject, String body, AccessKey accessKey, KeyPair sshKeyPair, java.security.KeyPair x509KeyPair, X509Certificate x509Certificate, SigningCertificate signingCertificate, String from, String toAddress) { try { Session s = Session.getInstance(new Properties(), null); MimeMessage msg = new MimeMessage(s); msg.setFrom(new InternetAddress(from)); msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress)); msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(from)); msg.setSubject(subject); MimeMultipart mimeMultiPart = new MimeMultipart(); msg.setContent(mimeMultiPart); // body BodyPart plainTextBodyPart = new MimeBodyPart(); mimeMultiPart.addBodyPart(plainTextBodyPart); plainTextBodyPart.setContent(body, "text/plain"); // aws-credentials.txt / accessKey { BodyPart awsCredentialsBodyPart = new MimeBodyPart(); awsCredentialsBodyPart.setFileName("aws-credentials.txt"); StringWriter awsCredentialsStringWriter = new StringWriter(); PrintWriter awsCredentials = new PrintWriter(awsCredentialsStringWriter); awsCredentials .println("#Insert your AWS Credentials from http://aws.amazon.com/security-credentials"); awsCredentials.println("#" + new DateTime()); awsCredentials.println(); awsCredentials.println("# ec2, rds & elb tools use accessKey and secretKey"); awsCredentials.println("accessKey=" + accessKey.getAccessKeyId()); awsCredentials.println("secretKey=" + accessKey.getSecretAccessKey()); awsCredentials.println(); awsCredentials.println("# iam tools use AWSAccessKeyId and AWSSecretKey"); awsCredentials.println("AWSAccessKeyId=" + accessKey.getAccessKeyId()); awsCredentials.println("AWSSecretKey=" + accessKey.getSecretAccessKey()); awsCredentialsBodyPart.setContent(awsCredentialsStringWriter.toString(), "text/plain"); mimeMultiPart.addBodyPart(awsCredentialsBodyPart); } // private ssh key { BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(sshKeyPair.getKeyName() + ".pem.txt"); keyPairBodyPart.setContent(sshKeyPair.getKeyMaterial(), "application/octet-stream"); mimeMultiPart.addBodyPart(keyPairBodyPart); } // x509 private key { BodyPart x509PrivateKeyBodyPart = new MimeBodyPart(); x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate()); x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509PrivateKeyBodyPart); } // x509 private key { BodyPart x509CertificateBodyPart = new MimeBodyPart(); x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509CertificatePem = Pems.pem(x509Certificate); x509CertificateBodyPart.setContent(x509CertificatePem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509CertificateBodyPart); } // Convert to raw message ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); RawMessage rawMessage = new RawMessage(); rawMessage.setData(ByteBuffer.wrap(out.toString().getBytes())); ses.sendRawEmail(new SendRawEmailRequest().withRawMessage(rawMessage)); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:hudson.plugins.ec2.SlaveTemplate.java
License:Open Source License
/** * Provisions an On-demand EC2 slave by launching a new instance or * starting a previously-stopped instance. *///w ww. j a v a 2s . c o m private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { String msg = "Launching " + ami + " for template " + description; logger.println(msg); LOGGER.info(msg); KeyPair keyPair = getKeyPair(ec2); RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1); InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); if (useEphemeralDevices) { setupEphemeralDeviceMapping(riRequest); } else { setupCustomDeviceMapping(riRequest); } List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); if (getUseDedicatedTenancy()) { placement.setTenancy("dedicated"); } riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } if (StringUtils.isNotBlank(getSubnetId())) { if (getAssociatePublicIp()) { net.setSubnetId(getSubnetId()); } else { riRequest.setSubnetId(getSubnetId()); } diFilters.add(new Filter("subnet-id").withValues(getSubnetId())); /* If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> group_ids = getEc2SecurityGroups(ec2); if (!group_ids.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(group_ids); } else { riRequest.setSecurityGroupIds(group_ids); } diFilters.add(new Filter("instance.group-id").withValues(group_ids)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (securityGroupSet.size() > 0) diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet)); } String userDataString = Base64.encodeBase64String(userData.getBytes()); riRequest.setUserData(userDataString); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); riRequest.setInstanceType(type.toString()); diFilters.add(new Filter("instance-type").withValues(type.toString())); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); riRequest.withNetworkInterfaces(net); } boolean hasCustomTypeTag = false; HashSet<Tag> inst_tags = null; if (tags != null && !tags.isEmpty()) { inst_tags = new HashSet<Tag>(); for (EC2Tag t : tags) { inst_tags.add(new Tag(t.getName(), t.getValue())); diFilters.add(new Filter("tag:" + t.getName()).withValues(t.getValue())); if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } } } if (!hasCustomTypeTag) { if (inst_tags == null) { inst_tags = new HashSet<Tag>(); } inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "demand")); } DescribeInstancesRequest diRequest = new DescribeInstancesRequest(); diFilters.add(new Filter("instance-state-name").withValues(InstanceStateName.Stopped.toString(), InstanceStateName.Stopping.toString())); diRequest.setFilters(diFilters); msg = "Looking for existing instances with describe-instance: " + diRequest; logger.println(msg); LOGGER.fine(msg); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); Instance existingInstance = null; if (StringUtils.isNotBlank(getIamInstanceProfile())) { riRequest.setIamInstanceProfile( new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); // cannot filter on IAM Instance Profile, so search in result reservationLoop: for (Reservation reservation : diResult.getReservations()) { for (Instance instance : reservation.getInstances()) { if (instance.getIamInstanceProfile() != null && instance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())) { existingInstance = instance; break reservationLoop; } } } } else if (diResult.getReservations().size() > 0) { existingInstance = diResult.getReservations().get(0).getInstances().get(0); } if (existingInstance == null) { // Have to create a new instance Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0); /* Now that we have our instance, we can set tags on it */ if (inst_tags != null) { for (int i = 0; i < 5; i++) { try { updateRemoteTags(ec2, inst_tags, inst.getInstanceId()); break; } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidInstanceRequestID.NotFound")) { Thread.sleep(5000); continue; } throw e; } } // That was a remote request - we should also update our local instance data. inst.setTags(inst_tags); } msg = "No existing instance found - created: " + inst; logger.println(msg); LOGGER.info(msg); return newOndemandSlave(inst); } msg = "Found existing stopped instance: " + existingInstance; logger.println(msg); LOGGER.info(msg); List<String> instances = new ArrayList<String>(); instances.add(existingInstance.getInstanceId()); StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); msg = "Starting existing instance: " + existingInstance + " result:" + siResult; logger.println(msg); LOGGER.fine(msg); for (EC2AbstractSlave ec2Node : NodeIterator.nodes(EC2AbstractSlave.class)) { if (ec2Node.getInstanceId().equals(existingInstance.getInstanceId())) { msg = "Found existing corresponding Jenkins slave: " + ec2Node; logger.println(msg); LOGGER.finer(msg); return ec2Node; } } // Existing slave not found msg = "Creating new Jenkins slave for existing instance: " + existingInstance; logger.println(msg); LOGGER.info(msg); return newOndemandSlave(existingInstance); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:hudson.plugins.ec2.SlaveTemplate.java
License:Open Source License
/** * Provision a new slave for an EC2 spot instance to call back to Jenkins *//*from www . jav a 2 s . co m*/ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { logger.println("Launching " + ami + " for template " + description); KeyPair keyPair = getKeyPair(ec2); RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest(); // Validate spot bid before making the request if (getSpotMaxBidPrice() == null) { // throw new FormException("Invalid Spot price specified: " + getSpotMaxBidPrice(), "spotMaxBidPrice"); throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice()); } spotRequest.setSpotPrice(getSpotMaxBidPrice()); spotRequest.setInstanceCount(Integer.valueOf(1)); spotRequest.setType(getBidType()); LaunchSpecification launchSpecification = new LaunchSpecification(); InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); launchSpecification.setImageId(ami); launchSpecification.setInstanceType(type); if (StringUtils.isNotBlank(getZone())) { SpotPlacement placement = new SpotPlacement(getZone()); launchSpecification.setPlacement(placement); } if (StringUtils.isNotBlank(getSubnetId())) { if (getAssociatePublicIp()) { net.setSubnetId(getSubnetId()); } else { launchSpecification.setSubnetId(getSubnetId()); } /* If we have a subnet ID then we can only use VPC security groups */ if (!securityGroupSet.isEmpty()) { List<String> group_ids = getEc2SecurityGroups(ec2); if (!group_ids.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(group_ids); } else { ArrayList<GroupIdentifier> groups = new ArrayList<GroupIdentifier>(); for (String group_id : group_ids) { GroupIdentifier group = new GroupIdentifier(); group.setGroupId(group_id); groups.add(group); } if (!groups.isEmpty()) launchSpecification.setAllSecurityGroups(groups); } } } } else { /* No subnet: we can use standard security groups by name */ if (securityGroupSet.size() > 0) launchSpecification.setSecurityGroups(securityGroupSet); } // The slave must know the Jenkins server to register with as well // as the name of the node in Jenkins it should register as. The only // way to give information to the Spot slaves is through the ec2 user data String jenkinsUrl = Hudson.getInstance().getRootUrl(); // We must provide a unique node name for the slave to connect to Jenkins. // We don't have the EC2 generated instance ID, or the Spot request ID // until after the instance is requested, which is then too late to set the // user-data for the request. Instead we generate a unique name from UUID // so that the slave has a unique name within Jenkins to register to. String slaveName = UUID.randomUUID().toString(); String newUserData = ""; // We want to allow node configuration with cloud-init and user-data, // while maintaining backward compatibility with old ami's // The 'new' way is triggered by the presence of '${SLAVE_NAME}'' in the user data // (which is not too much to ask) if (userData.contains("${SLAVE_NAME}")) { // The cloud-init compatible way newUserData = new String(userData); newUserData = newUserData.replace("${SLAVE_NAME}", slaveName); newUserData = newUserData.replace("${JENKINS_URL}", jenkinsUrl); } else { // The 'old' way - maitain full backward compatibility newUserData = "JENKINS_URL=" + jenkinsUrl + "&SLAVE_NAME=" + slaveName + "&USER_DATA=" + Base64.encodeBase64String(userData.getBytes()); } String userDataString = Base64.encodeBase64String(newUserData.getBytes()); launchSpecification.setUserData(userDataString); launchSpecification.setKeyName(keyPair.getKeyName()); launchSpecification.setInstanceType(type.toString()); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); launchSpecification.withNetworkInterfaces(net); } boolean hasCustomTypeTag = false; HashSet<Tag> inst_tags = null; if (tags != null && !tags.isEmpty()) { inst_tags = new HashSet<Tag>(); for (EC2Tag t : tags) { inst_tags.add(new Tag(t.getName(), t.getValue())); if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) { hasCustomTypeTag = true; } } } if (!hasCustomTypeTag) { inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "spot")); } if (StringUtils.isNotBlank(getIamInstanceProfile())) { launchSpecification.setIamInstanceProfile( new IamInstanceProfileSpecification().withArn(getIamInstanceProfile())); } spotRequest.setLaunchSpecification(launchSpecification); // Make the request for a new Spot instance RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest); List<SpotInstanceRequest> reqInstances = reqResult.getSpotInstanceRequests(); if (reqInstances.size() <= 0) { throw new AmazonClientException("No spot instances found"); } SpotInstanceRequest spotInstReq = reqInstances.get(0); if (spotInstReq == null) { throw new AmazonClientException("Spot instance request is null"); } /* Now that we have our Spot request, we can set tags on it */ if (inst_tags != null) { for (int i = 0; i < 5; i++) { try { updateRemoteTags(ec2, inst_tags, spotInstReq.getSpotInstanceRequestId()); break; } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidSpotInstanceRequestID.NotFound")) { Thread.sleep(5000); continue; } throw e; } } // That was a remote request - we should also update our local instance data. spotInstReq.setTags(inst_tags); } logger.println("Spot instance id in provision: " + spotInstReq.getSpotInstanceRequestId()); return newSpotSlave(spotInstReq, slaveName); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:hudson.plugins.ec2.ssh.EC2SpotUnixLauncher.java
License:Open Source License
private int bootstrap(final Connection bootstrapConn, final EC2Computer computer, final PrintStream logger) throws IOException, InterruptedException, AmazonClientException { logger.println("bootstrap()"); boolean closeBootstrap = true; try {/*from w w w. j ava2s . c o m*/ int tries = 20; boolean isAuthenticated = false; logger.println("Getting keypair..."); final KeyPair key = computer.getCloud().getKeyPair(); logger.println("Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n" + key.getKeyMaterial().substring(0, 160)); while (tries-- > 0) { logger.println("Authenticating as " + computer.getRemoteAdmin()); isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), ""); if (isAuthenticated) { break; } logger.println("Authentication failed. Trying again..."); Thread.sleep(10000); } if (!isAuthenticated) { logger.println("Authentication failed"); return FAILED; } closeBootstrap = false; return SAMEUSER; } finally { if (closeBootstrap) bootstrapConn.close(); } }
From source file:hudson.plugins.ec2.ssh.EC2UnixLauncher.java
License:Open Source License
private int bootstrap(Connection bootstrapConn, EC2Computer computer, PrintStream logger) throws IOException, InterruptedException, AmazonClientException { logger.println("bootstrap()"); boolean closeBootstrap = true; try {//from www .j a v a2 s . c o m int tries = 20; boolean isAuthenticated = false; logger.println("Getting keypair..."); KeyPair key = computer.getCloud().getKeyPair(); logger.println("Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n" + key.getKeyMaterial().substring(0, 160)); while (tries-- > 0) { logger.println("Authenticating as " + computer.getRemoteAdmin()); isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), ""); if (isAuthenticated) { break; } logger.println("Authentication failed. Trying again..."); Thread.sleep(10000); } if (!isAuthenticated) { logger.println("Authentication failed"); return FAILED; } closeBootstrap = false; return SAMEUSER; } finally { if (closeBootstrap) bootstrapConn.close(); } }
From source file:n3phele.factory.ec2.VirtualServerResource.java
License:Open Source License
public void sendNotificationEmail(KeyPair keyPair, String to, String firstName, String lastName, URI location) { try {//from w ww . j av a 2s. c o m StringBuilder subject = new StringBuilder(); StringBuilder body = new StringBuilder(); subject.append("Auto-generated keyPair \""); subject.append(keyPair.getKeyName()); subject.append("\""); body.append(firstName); body.append(",\n\nA keypair named \""); body.append(keyPair.getKeyName()); body.append("\" has been generated for you. \n\n"); body.append("Please keep this information secure as it allows access to the virtual machines"); body.append(" run on your behalf by n3phele on the cloud at "); body.append(location.toString()); body.append(". To access the machines using ssh copy all of the lines"); body.append(" including -----BEGIN RSA PRIVATE KEY----- and -----END RSA PRIVATE KEY-----"); body.append(" into a file named "); body.append(keyPair.getKeyName()); body.append(".pem\n\n"); body.append(keyPair.getKeyMaterial()); body.append("\n\nn3phele\n--\nhttps://n3phele.appspot.com\n\n"); Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("n3phele@gmail.com", "n3phele")); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to, firstName + " " + lastName)); msg.setSubject(subject.toString()); msg.setText(body.toString()); Transport.send(msg); } catch (AddressException e) { log.log(Level.SEVERE, "Email to " + to, e); } catch (MessagingException e) { log.log(Level.SEVERE, "Email to " + to, e); } catch (UnsupportedEncodingException e) { log.log(Level.SEVERE, "Email to " + to, e); } catch (Exception e) { log.log(Level.SEVERE, "Email to " + to, e); } }
From source file:net.firejack.aws.web.controller.AWSController.java
License:Apache License
@ResponseBody @RequestMapping(value = "install", method = RequestMethod.POST) public Status startInstance(@RequestBody Auth auth) { if (!auth.isValid()) throw new AmazonServiceException("Access or Secret Key is empty"); if (amazonEC2 != null) { amazonEC2.shutdown();/*from w w w .j a v a 2s . c om*/ } amazonEC2 = new AmazonEC2Client(new BasicAWSCredentials(auth.getAccessKey(), auth.getSecretKey())); amazonEC2.setRegion(RegionUtils.getRegion(instanceRegion)); RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.setInstanceType(InstanceType.fromValue(instanceType)); runInstancesRequest.setImageId(instanceAmi); runInstancesRequest.setMinCount(1); runInstancesRequest.setMaxCount(1); KeyPair keyPair = createKeyPair(); String privateKey = keyPair.getKeyMaterial(); String fileName; try { fileName = saveKeyFile(keyPair.getKeyName(), privateKey); } catch (FileNotFoundException e) { throw new AmazonServiceException("Could not create the key file"); } catch (UnsupportedEncodingException e) { throw new AmazonServiceException("Could not create the key file"); } runInstancesRequest.setKeyName(keyPair.getKeyName()); CreateSecurityGroupResult securityGroupResult = createSecurityGroupWithRules(); Collection securityGroupIds = new ArrayList(); securityGroupIds.add(securityGroupResult.getGroupId()); runInstancesRequest.setSecurityGroupIds(securityGroupIds); amazonEC2.runInstances(runInstancesRequest); return new Status("Server has been started", fileName); }