List of usage examples for com.amazonaws.services.identitymanagement.model SigningCertificate getCertificateId
public String getCertificateId()
The ID for the signing certificate.
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
License:Apache License
/** * <p>//from w ww . j a v a2s .co m * 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.cloud.amazon.aws.tools.AmazonAwsToolsSender.java
License:Apache License
/** * <p>/*from www. j av a2 s . c o m*/ * Send the tools info by email. * </p> * * @param userName * valid email used as userName. */ public void sendEmail(@Nonnull final String userName) throws Exception { Preconditions.checkNotNull(userName, "Given userName can NOT be null"); logger.debug("Process user {}", userName); Map<String, String> templatesParams = Maps.newHashMap(); templatesParams.put("awsCredentialsHome", "~/.aws"); templatesParams.put("awsCommandLinesHome", "~/aws-tools"); templatesParams.put("awsCredentialsWindowsHome", "c:\\aws"); templatesParams.put("awsCommandLinesWindowsHome", "c:\\aws-tools"); templatesParams.put("userName", userName); User user; try { user = iam.getUser(new GetUserRequest().withUserName(userName)).getUser(); } catch (NoSuchEntityException e) { logger.debug("User {} does not exist,", userName, e); throw e; } List<BodyPart> attachments = Lists.newArrayList(); templatesParams.put("credentialsFileName", "aws-credentials.txt"); // X509 SELF SIGNED CERTIFICATE Collection<SigningCertificate> certificates = iam .listSigningCertificates(new ListSigningCertificatesRequest().withUserName(user.getUserName())) .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())); } }); SigningCertificate signingCertificate = Iterables.getFirst(certificates, null); templatesParams.put("X509CertificateFileName", "cert-" + signingCertificate.getCertificateId() + ".pem"); templatesParams.put("X509PrivateKeyFileName", "pk-" + signingCertificate.getCertificateId() + ".pem"); 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. * /*from w w w.ja v a2s .co 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 w w. j av 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); } }