List of usage examples for com.amazonaws.services.identitymanagement.model ListAccessKeysResult getAccessKeyMetadata
public java.util.List<AccessKeyMetadata> getAccessKeyMetadata()
A list of objects containing metadata about the access keys.
From source file:aws.example.iam.ListAccessKeys.java
License:Open Source License
public static void main(String[] args) { final String USAGE = "To run this example, supply an IAM username\n" + "Ex: ListAccessKeys <username>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1);/*from w w w .j av a2 s .co m*/ } String username = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); boolean done = false; while (!done) { ListAccessKeysRequest request = new ListAccessKeysRequest().withUserName(username); ListAccessKeysResult response = iam.listAccessKeys(request); for (AccessKeyMetadata metadata : response.getAccessKeyMetadata()) { System.out.format("Retrieved access key %s", metadata.getAccessKeyId()); } request.setMarker(response.getMarker()); if (!response.getIsTruncated()) { done = true; } } }
From source file:ch.cyberduck.core.iam.AmazonIdentityConfiguration.java
License:Open Source License
@Override public void delete(final String username, final LoginCallback prompt) throws BackgroundException { if (log.isInfoEnabled()) { log.info(String.format("Delete user %s", username)); }//from w w w . j av a 2 s . c o m this.authenticated(new Authenticated<Void>() { @Override public Void call() throws BackgroundException { PreferencesFactory.get().deleteProperty(String.format("%s%s", prefix, username)); // Create new IAM credentials final AmazonIdentityManagementClient client = new AmazonIdentityManagementClient( new com.amazonaws.auth.AWSCredentials() { @Override public String getAWSAccessKeyId() { return host.getCredentials().getUsername(); } @Override public String getAWSSecretKey() { return host.getCredentials().getPassword(); } }, configuration); try { final ListAccessKeysResult keys = client .listAccessKeys(new ListAccessKeysRequest().withUserName(username)); for (AccessKeyMetadata key : keys.getAccessKeyMetadata()) { if (log.isDebugEnabled()) { log.debug(String.format("Delete access key %s for user %s", key, username)); } client.deleteAccessKey(new DeleteAccessKeyRequest(username, key.getAccessKeyId())); } final ListUserPoliciesResult policies = client .listUserPolicies(new ListUserPoliciesRequest(username)); for (String policy : policies.getPolicyNames()) { if (log.isDebugEnabled()) { log.debug(String.format("Delete policy %s for user %s", policy, username)); } client.deleteUserPolicy(new DeleteUserPolicyRequest(username, policy)); } client.deleteUser(new DeleteUserRequest(username)); } catch (NoSuchEntityException e) { log.warn(String.format("User %s already removed", username)); } catch (AmazonClientException e) { throw new AmazonServiceExceptionMappingService().map("Cannot write user configuration", e); } finally { client.shutdown(); } return null; } }, prompt); }
From source file:com.denismo.aws.iam.LDAPIAMPoller.java
License:Apache License
private String getUserAccessKey(AmazonIdentityManagementClient client, User user) { ListAccessKeysResult res = client .listAccessKeys(new ListAccessKeysRequest().withUserName(user.getUserName())); for (AccessKeyMetadata meta : res.getAccessKeyMetadata()) { if ("Active".equals(meta.getStatus())) { return meta.getAccessKeyId(); }/*from w w w. j a v a2 s . c o m*/ } return null; }
From source file:com.epam.dlab.auth.aws.dao.AwsUserDAOImpl.java
License:Apache License
@Override public List<AccessKeyMetadata> getAwsAccessKeys(String username) { List<AccessKeyMetadata> data = null; try {//from w w w . j a v a 2 s . c o m ListAccessKeysRequest request = new ListAccessKeysRequest().withUserName(username); ListAccessKeysResult result = aim.listAccessKeys(request); data = result.getAccessKeyMetadata(); } catch (Exception e) { log.error("AccessKeyMetadata for {} request failed: {}", username, e.getMessage()); } return data; }
From source file:com.github.trask.sandbox.ec2.Ec2Service.java
License:Apache License
public void deleteExistingAccessKeys(String username) { ListAccessKeysRequest listAccessKeysRequest = new ListAccessKeysRequest(); listAccessKeysRequest.setUserName(username); ListAccessKeysResult result = iam.listAccessKeys(listAccessKeysRequest); for (AccessKeyMetadata accessKeyMetadata : result.getAccessKeyMetadata()) { DeleteAccessKeyRequest deleteAccessKeyRequest = new DeleteAccessKeyRequest(); deleteAccessKeyRequest.setUserName(username); deleteAccessKeyRequest.setAccessKeyId(accessKeyMetadata.getAccessKeyId()); iam.deleteAccessKey(deleteAccessKeyRequest); }//from w w w . j a va2 s.c o m }
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
License:Apache License
/** * <p>//from w w w . j a v a 2 s . 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:mail.server.storage.AWSStorageDelete.java
License:GNU General Public License
protected void deleteUser(AmazonIdentityManagement im, String group, String user, String policy, boolean force) throws Exception { try {/*from w w w . j av a 2s. com*/ log.debug("deleting user policy", user, policy); im.deleteUserPolicy(new DeleteUserPolicyRequest().withUserName(user).withPolicyName(policy)); } catch (Exception e) { if (!force) throw e; log.exception(e); } try { log.debug("deleting access keys", user); ListAccessKeysResult accessKeys = im.listAccessKeys(new ListAccessKeysRequest().withUserName(user)); for (AccessKeyMetadata i : accessKeys.getAccessKeyMetadata()) { log.debug("deleting access key", user, i.getAccessKeyId()); im.deleteAccessKey( new DeleteAccessKeyRequest().withUserName(user).withAccessKeyId(i.getAccessKeyId())); } } catch (Exception e) { if (!force) throw e; log.exception(e); } try { log.debug("removing user from group", group, user); im.removeUserFromGroup(new RemoveUserFromGroupRequest().withGroupName(group).withUserName(user)); } catch (Exception e) { if (!force) throw e; log.exception(e); } try { log.debug("deleting user", user); im.deleteUser(new DeleteUserRequest().withUserName(user)); } catch (Exception e) { if (!force) throw e; log.exception(e); } }
From source file:org.cloudfoundry.community.servicebroker.s3.service.Iam.java
License:Apache License
public void deleteUserAccessKeys(String userName) { logger.info("Deleting all access keys for user '{}'", userName); ListAccessKeysRequest accessKeysRequest = new ListAccessKeysRequest(); accessKeysRequest.setUserName(userName); ListAccessKeysResult accessKeysResult = iam.listAccessKeys(accessKeysRequest); for (AccessKeyMetadata keyMeta : accessKeysResult.getAccessKeyMetadata()) { DeleteAccessKeyRequest request = new DeleteAccessKeyRequest(userName, keyMeta.getAccessKeyId()); iam.deleteAccessKey(request);//from www .j av a2 s .c o m } // ListAccessKeysResult has truncation in it but there doesn't seem to // be a way to use it }