List of usage examples for com.amazonaws.services.identitymanagement.model Group getGroupName
public String getGroupName()
The friendly name that identifies the group.
From source file:com.denismo.aws.iam.LDAPIAMPoller.java
License:Apache License
private void populateGroupsFromIAM() { AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(credentials); try {//from ww w . j av a2 s. c om ListGroupsResult res = client.listGroups(); Set<String> groupNames = new HashSet<String>(); while (true) { for (Group group : res.getGroups()) { try { addGroup(group); groupNames.add(group.getGroupName()); LOG.info("Added group " + group.getGroupName() + " at " + groupsDN); } catch (Throwable e) { LOG.error("Exception processing group " + group.getGroupName(), e); } } if (res.isTruncated()) { res = client.listGroups(new ListGroupsRequest().withMarker(res.getMarker())); } else { break; } } removeDeletedGroups(groupNames); } finally { client.shutdown(); } }
From source file:com.denismo.aws.iam.LDAPIAMPoller.java
License:Apache License
private Entry addGroup(Group iamGroup) throws Exception { LOG.info("Adding group " + iamGroup.getGroupName()); Entry existingGroup = getExistingGroup(iamGroup); if (existingGroup != null) { LOG.info("Group exists: " + iamGroup.getGroupName()); return existingGroup; }/* www. j av a2s.c om*/ String gid = allocateGroupID(iamGroup.getArn()); Dn groupDn = directory.getDnFactory().create(String.format(GROUP_FMT, iamGroup.getGroupName())); LOG.info("New group dn: " + groupDn); Entry group = new DefaultEntry(directory.getSchemaManager(), groupDn); group.put(SchemaConstants.OBJECT_CLASS_AT, "posixGroup", "iamgroup", "top"); group.put("gidNumber", gid); group.put(SchemaConstants.ENTRY_CSN_AT, directory.getCSN().toString()); group.put(SchemaConstants.CN_AT, iamGroup.getGroupName()); group.put(SchemaConstants.ENTRY_UUID_AT, UUID.randomUUID().toString()); add(group); return group; }
From source file:com.denismo.aws.iam.LDAPIAMPoller.java
License:Apache License
private Entry getExistingGroup(Group iamGroup) throws Exception { Dn dn = directory.getDnFactory().create(String.format(GROUP_FMT, iamGroup.getGroupName())); LookupOperationContext lookupContext = new LookupOperationContext(directory.getAdminSession(), dn, SchemaConstants.ALL_USER_ATTRIBUTES, SchemaConstants.ALL_OPERATIONAL_ATTRIBUTES); try {//from w w w.java2 s . co m Entry groupEntry = directory.getPartitionNexus().lookup(lookupContext); if (groupEntry != null && groupEntry.hasObjectClass("iamgroup")) { return groupEntry; } } catch (LdapNoSuchObjectException e) { // Fallthrough } return null; }
From source file:com.denismo.aws.iam.LDAPIAMPoller.java
License:Apache License
private void populateUsersFromIAM() { AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(credentials); try {// w ww . j a v a2 s .c om ListUsersResult res = client.listUsers(); Set<String> allUsers = new HashSet<String>(); while (true) { for (User user : res.getUsers()) { try { Collection<Group> groups = client .listGroupsForUser(new ListGroupsForUserRequest(user.getUserName())).getGroups(); Group primaryGroup = groups.size() > 0 ? groups.iterator().next() : null; if (primaryGroup == null) { LOG.warn("Unable to determine primary group for " + user.getUserName()); continue; } Entry groupEntry = getExistingGroup(primaryGroup); if (groupEntry == null) { LOG.warn("Unable to retrieve matching group entry for group " + primaryGroup.getGroupName() + " user " + user.getUserName()); continue; } addUser(user, getUserAccessKey(client, user), groupEntry); updateGroups(groups, user); allUsers.add(user.getUserName()); LOG.info("Added user " + user.getUserName()); } catch (Throwable e) { LOG.error("Exception processing user " + user.getUserName(), e); } } if (res.isTruncated()) { res = client.listUsers(new ListUsersRequest().withMarker(res.getMarker())); } else { break; } } removeDeletedUsers(allUsers); } finally { client.shutdown(); } }
From source file:com.denismo.aws.iam.LDAPIAMPoller.java
License:Apache License
private void updateGroups(Collection<Group> groups, User user) { Set<String> groupNames = new HashSet<String>(); for (Group group : groups) { groupNames.add(group.getGroupName()); }/*from w ww. j a va 2 s. co m*/ Collection<Entry> allGroups = getAllEntries(groupsDN, "iamgroup"); String userUid = user.getUserName(); LOG.info("Updating groups for " + userUid); for (Entry group : allGroups) { LOG.info("Looking at group " + group.getDn()); try { List<Modification> modifications = new ArrayList<Modification>(); if (groupNames.contains(group.get(SchemaConstants.CN_AT).getString())) { if (!group.contains("memberUid", userUid)) { modifications.add( new DefaultModification(ModificationOperation.ADD_ATTRIBUTE, "memberUid", userUid)); } } else { if (group.contains("memberUid", userUid)) { modifications.add(new DefaultModification(ModificationOperation.REMOVE_ATTRIBUTE, "memberUid", userUid)); } } if (!modifications.isEmpty()) { LOG.info("Will modify group with " + modifications); directory.getAdminSession().modify(group.getDn(), modifications); } } catch (LdapException e) { LOG.error("Unable to update users in group " + group.getDn()); } } }
From source file:com.haskins.cloudtrailviewer.dialog.resourcedetail.detailpanels.IamGroupDetail.java
License:Open Source License
private void buildUI(GetGroupResult detail) { JTabbedPane tabs = new JTabbedPane(); tabs.add("Group", primaryScrollPane); final JTable usersTable = new JTable(usersTableModel); JScrollPane usersScrollPane = new JScrollPane(usersTable); tabs.add("Users", usersScrollPane); this.add(tabs, BorderLayout.CENTER); if (detail.getGroup() != null) { Group group = detail.getGroup(); if (group.getCreateDate() != null) { primaryTableModel.addRow(new Object[] { "Created", getDateString(group.getCreateDate()) }); }//from w w w.j a v a2 s . c om if (group.getArn() != null) { primaryTableModel.addRow(new Object[] { "Arn", group.getArn() }); } if (group.getGroupId() != null) { primaryTableModel.addRow(new Object[] { "Group ID", group.getGroupId() }); } if (group.getGroupName() != null) { primaryTableModel.addRow(new Object[] { "Group Name", group.getGroupName() }); } if (group.getPath() != null) { primaryTableModel.addRow(new Object[] { "Path", group.getPath() }); } /** * Users * */ usersTableModel.addColumn("Key"); usersTableModel.addColumn("Value"); usersTableModel.addColumn("User Previous Value"); List<User> users = detail.getUsers(); if (!users.isEmpty()) { for (User user : users) { if (user.getCreateDate() != null) { primaryTableModel.addRow(new Object[] { "Created", getDateString(user.getCreateDate()) }); } if (user.getArn() != null) { primaryTableModel.addRow(new Object[] { "Arn", user.getArn() }); } if (user.getPasswordLastUsed() != null) { primaryTableModel.addRow(new Object[] { "Password Last Used", user.getPasswordLastUsed() }); } if (user.getPath() != null) { primaryTableModel.addRow(new Object[] { "Path", user.getPath() }); } if (user.getUserId() != null) { primaryTableModel.addRow(new Object[] { "User Id", user.getUserId() }); } if (user.getUserName() != null) { primaryTableModel.addRow(new Object[] { "User Name", user.getUserName() }); } } } } }
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
License:Apache License
/** * <p>/* w ww. 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:org.dasein.prototype.iamc.AWS.java
License:Apache License
public boolean deleteUser(String username) { try {//w w w . j a va2 s. co m for (String policy : iamClient.listUserPolicies(new ListUserPoliciesRequest(username)) .getPolicyNames()) { iamClient.deleteUserPolicy(new DeleteUserPolicyRequest(username, policy)); } } catch (NoSuchEntityException ignore) { } try { for (Group group : iamClient.listGroupsForUser(new ListGroupsForUserRequest(username)).getGroups()) { iamClient.removeUserFromGroup(new RemoveUserFromGroupRequest(group.getGroupName(), username)); } } catch (NoSuchEntityException ignore) { } try { iamClient.deleteLoginProfile(new DeleteLoginProfileRequest(username)); } catch (Exception ignore) { } try { iamClient.deleteUser(new DeleteUserRequest(username)); return true; } catch (NoSuchEntityException e) { } catch (DeleteConflictException e) { e.printStackTrace(System.err); } return false; }