List of usage examples for com.amazonaws.services.identitymanagement.model CreateAccessKeyRequest CreateAccessKeyRequest
public CreateAccessKeyRequest()
From source file:aws.example.iam.CreateAccessKey.java
License:Open Source License
public static void main(String[] args) { final String USAGE = "To run this example, supply an IAM user\n" + "Ex: CreateAccessKey <user>\n"; if (args.length != 1) { System.out.println(USAGE); System.exit(1);//from w w w . j a va2 s . c o m } String user = args[0]; final AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder.defaultClient(); CreateAccessKeyRequest request = new CreateAccessKeyRequest().withUserName(user); CreateAccessKeyResult response = iam.createAccessKey(request); System.out.println("Created access key: " + response.getAccessKey()); }
From source file:ch.cyberduck.core.iam.AmazonIdentityConfiguration.java
License:Open Source License
@Override public void create(final String username, final String policy, final LoginCallback prompt) throws BackgroundException { if (log.isInfoEnabled()) { log.info(String.format("Create user %s with policy %s", username, policy)); }/*w w w. j a v a2 s . c om*/ this.authenticated(new Authenticated<Void>() { @Override public Void call() throws BackgroundException { // 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 { // Create new IAM credentials User user; try { user = client.createUser(new CreateUserRequest().withUserName(username)).getUser(); } catch (EntityAlreadyExistsException e) { user = client.getUser(new GetUserRequest().withUserName(username)).getUser(); } final CreateAccessKeyResult key = client .createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName())); if (log.isDebugEnabled()) { log.debug(String.format("Created access key %s for user %s", key, username)); } // Write policy document to get read access client.putUserPolicy(new PutUserPolicyRequest(user.getUserName(), "Policy", policy)); // Map virtual user name to IAM access key final String id = key.getAccessKey().getAccessKeyId(); if (log.isInfoEnabled()) { log.info(String.format("Map user %s to access key %s", String.format("%s%s", prefix, username), id)); } PreferencesFactory.get().setProperty(String.format("%s%s", prefix, username), id); // Save secret PasswordStoreFactory.get().addPassword(host.getProtocol().getScheme(), host.getPort(), host.getHostname(), id, key.getAccessKey().getSecretAccessKey()); } catch (AmazonClientException e) { throw new AmazonServiceExceptionMappingService().map("Cannot write user configuration", e); } finally { client.shutdown(); } return null; } }, prompt); }
From source file:com.github.trask.sandbox.ec2.Ec2Service.java
License:Apache License
public AccessKey createAccessKey(final String username) { CreateAccessKeyRequest request = new CreateAccessKeyRequest(); request.setUserName(username);/*w w w . j a va 2s. co m*/ CreateAccessKeyResult result = iam.createAccessKey(request); return result.getAccessKey(); }
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
License:Apache License
/** * <p>/*from w w w.j av 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:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreator.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 a 2 s . com * @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(); System.out.println("CREATED userName=" + user.getUserName() + "\tpassword=" + password + "\taccessKeyId=" + accessKey.getAccessKeyId() + "\tsecretAccessKey=" + accessKey.getSecretAccessKey()); 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 += "Access Key Id: " + accessKey.getAccessKeyId() + "\n"; body += "Secret Access Key: " + accessKey.getSecretAccessKey() + "\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, "cyrille@cyrilleleclerc.com", user.getUserName()); } catch (Exception e) { e.printStackTrace(); } }
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 ww w. jav a 2 s . 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:mail.server.storage.AWSStorageCreation.java
License:GNU General Public License
public Map<String, String> create(String email, String region) throws Exception { log.debug("I will now figure out what region to put things in", region); Region awsRegion = Region.valueOf(region); String awsRegionString = awsRegion.toString(); if (awsRegionString == null) awsRegionString = ""; String awsRegionStringEndPoint = awsRegionString.isEmpty() ? "s3.amazonaws.com" : ("s3-" + awsRegionString + ".amazonaws.com"); log.debug("I will now log in to S3 and the IdentityManagement to check these credentials."); SimpleAWSCredentials credentials = new SimpleAWSCredentials(awsAccessKeyId, awsSecretKey); AmazonS3 s3 = new AmazonS3Client(credentials); AmazonIdentityManagement im = new AmazonIdentityManagementClient(credentials); log.debug("Successfully logged into S3"); log.debug("I will now derive names for items"); deriveNames(generateBucketName(email)); log.debug("I will now try to:\n" + " 1. Create the S3 Bucket with name ", bucketName, "\n" + " 2. Create two IAM Identities for permissions -\n" + " ", writeIdentity, " to be sent to the mail server to be able to write to the mailbox.\n" + " ", writeIdentity, " to be stored in your configuration to enable the mail client to read and write mail.\n\n"); s3.setEndpoint(awsRegionStringEndPoint); s3.createBucket(bucketName, awsRegion); log.debug("Setting website configuration"); BucketWebsiteConfiguration bwc = new BucketWebsiteConfiguration("index.html"); s3.setBucketWebsiteConfiguration(bucketName, bwc); log.debug("Done"); log.debug("Enabling CORS"); CORSRule rule1 = new CORSRule().withId("CORSRule1") .withAllowedMethods(Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.GET, CORSRule.AllowedMethods.PUT, CORSRule.AllowedMethods.DELETE })) .withAllowedOrigins(Arrays.asList(new String[] { "*" })).withMaxAgeSeconds(3000) .withAllowedHeaders(Arrays.asList(new String[] { "*" })) .withExposedHeaders(Arrays.asList(new String[] { "ETag" })); BucketCrossOriginConfiguration cors = new BucketCrossOriginConfiguration(); cors.setRules(Arrays.asList(new CORSRule[] { rule1 })); s3.setBucketCrossOriginConfiguration(bucketName, cors); log.debug("Done"); log.format("Creating group %s ... ", groupName); im.createGroup(new CreateGroupRequest().withGroupName(groupName)); log.debug("Done"); log.format("Creating user %s ... ", writeIdentity); im.createUser(new CreateUserRequest().withUserName(writeIdentity)); log.debug("Done"); log.format("Adding user %s to group %s ... ", writeIdentity, groupName); im.addUserToGroup(new AddUserToGroupRequest().withGroupName(groupName).withUserName(writeIdentity)); log.debug("Done"); log.format("Creating user %s ... ", readWriteIdentity); im.createUser(new CreateUserRequest().withUserName(readWriteIdentity)); log.debug("Done"); log.format("Adding user %s to group %s ... ", readWriteIdentity, groupName); im.addUserToGroup(new AddUserToGroupRequest().withGroupName(groupName).withUserName(readWriteIdentity)); log.debug("Done"); log.format("Creating permissions for %s to write to bucket %s ... \n", writeIdentity, bucketName); String writePolicyRaw = "{ \n" + " #Statement#: [ \n" + " { \n" + " #Sid#: #SID#, \n" + " #Action#: [ \n" + " #s3:PutObject#, \n" + " #s3:PutObjectAcl# \n" + " ], \n" + " #Effect#: #Allow#, \n" + " #Resource#: [ \n" + " #arn:aws:s3:::BUCKET/*#\n" + " ] \n" + " } \n" + " ] \n" + "}\n"; String writePolicy = writePolicyRaw.replaceAll("#", "\"").replace("SID", policyWriteName).replace("BUCKET", bucketName);/* ww w . ja v a2s . c om*/ // q.println ("Policy definition: " + writePolicy); im.putUserPolicy(new PutUserPolicyRequest().withUserName(writeIdentity).withPolicyDocument(writePolicy) .withPolicyName(policyWriteName)); log.debug("Done"); log.format("Creating permissions for %s to read/write to bucket %s ... \n", writeIdentity, bucketName); String readWritePolicyRaw = "{ \n" + " #Statement#: [ \n" + " { \n" + " #Sid#: #SID#, \n" + " #Action#: [ \n" + " #s3:PutObject#, \n" + " #s3:PutObjectAcl#, \n" + " #s3:DeleteObject#, \n" + " #s3:Get*#, \n" + " #s3:List*# \n" + " ], \n" + " #Effect#: #Allow#, \n" + " #Resource#: [ \n" + " #arn:aws:s3:::BUCKET/*#,\n" + " #arn:aws:s3:::BUCKET# \n" + " ] \n" + " } \n" + " ] \n" + "}\n"; String readWritePolicy = readWritePolicyRaw.replaceAll("#", "\"").replace("SID", policyReadWriteName) .replace("BUCKET", bucketName); // q.println ("Policy definition: " + readPolicy); im.putUserPolicy(new PutUserPolicyRequest().withUserName(readWriteIdentity) .withPolicyDocument(readWritePolicy).withPolicyName(policyReadWriteName)); log.debug("Done"); log.format("Requesting access key for %s", writeIdentity); writeAccessKey = im.createAccessKey(new CreateAccessKeyRequest().withUserName(writeIdentity)) .getAccessKey(); log.format("Received [%s] [%s] Done.\n", writeAccessKey.getAccessKeyId(), writeAccessKey.getSecretAccessKey()); log.format("Requesting access key for %s", readWriteIdentity); readWriteAccessKey = im.createAccessKey(new CreateAccessKeyRequest().withUserName(readWriteIdentity)) .getAccessKey(); log.format("Received [%s] [%s] Done.\n", readWriteAccessKey.getAccessKeyId(), readWriteAccessKey.getSecretAccessKey()); log.debug(); log.debug("I have finished the creating the S3 items.\n"); return Maps.toMap("bucketName", bucketName, "bucketRegion", awsRegionString, "writeAccessKey", writeAccessKey.getAccessKeyId(), "writeSecretKey", writeAccessKey.getSecretAccessKey(), "readWriteAccessKey", readWriteAccessKey.getAccessKeyId(), "readWriteSecretKey", readWriteAccessKey.getSecretAccessKey()); }
From source file:org.akvo.flow.InstanceConfigurator.java
License:Open Source License
public static void main(String[] args) throws Exception { Options opts = getOptions();/*from w ww. java 2 s . c om*/ CommandLineParser parser = new BasicParser(); CommandLine cli = null; try { cli = parser.parse(opts, args); } catch (Exception e) { System.err.println(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(InstanceConfigurator.class.getName(), opts); System.exit(1); } String awsAccessKey = cli.getOptionValue("ak"); String awsSecret = cli.getOptionValue("as"); String bucketName = cli.getOptionValue("bn"); String gaeId = cli.getOptionValue("gae"); String outFolder = cli.getOptionValue("o"); String flowServices = cli.getOptionValue("fs"); String alias = cli.getOptionValue("a"); String emailFrom = cli.getOptionValue("ef"); String emailTo = cli.getOptionValue("et"); String orgName = cli.getOptionValue("on"); String signingKey = cli.getOptionValue("sk"); File out = new File(outFolder); if (!out.exists()) { out.mkdirs(); } Map<String, AccessKey> accessKeys = new HashMap<String, AccessKey>(); String apiKey = UUID.randomUUID().toString().replaceAll("-", ""); AWSCredentials creds = new BasicAWSCredentials(awsAccessKey, awsSecret); AmazonIdentityManagementClient iamClient = new AmazonIdentityManagementClient(creds); AmazonS3Client s3Client = new AmazonS3Client(creds); // Creating bucket System.out.println("Creating bucket: " + bucketName); try { if (s3Client.doesBucketExist(bucketName)) { System.out.println(bucketName + " already exists, skipping creation"); } else { s3Client.createBucket(bucketName, Region.EU_Ireland); } } catch (Exception e) { System.err.println("Error trying to create bucket " + bucketName + " : " + e.getMessage()); System.exit(1); } // Creating users and groups String gaeUser = bucketName + GAE_SUFFIX; String apkUser = bucketName + APK_SUFFIX; // GAE System.out.println("Creating user: " + gaeUser); GetUserRequest gaeUserRequest = new GetUserRequest(); gaeUserRequest.setUserName(gaeUser); try { iamClient.getUser(gaeUserRequest); System.out.println("User already exists, skipping creation"); } catch (NoSuchEntityException e) { iamClient.createUser(new CreateUserRequest(gaeUser)); } System.out.println("Requesting security credentials for " + gaeUser); CreateAccessKeyRequest gaeAccessRequest = new CreateAccessKeyRequest(); gaeAccessRequest.setUserName(gaeUser); CreateAccessKeyResult gaeAccessResult = iamClient.createAccessKey(gaeAccessRequest); accessKeys.put(gaeUser, gaeAccessResult.getAccessKey()); // APK System.out.println("Creating user: " + apkUser); GetUserRequest apkUserRequest = new GetUserRequest(); apkUserRequest.setUserName(apkUser); try { iamClient.getUser(apkUserRequest); System.out.println("User already exists, skipping creation"); } catch (NoSuchEntityException e) { iamClient.createUser(new CreateUserRequest(apkUser)); } System.out.println("Requesting security credentials for " + apkUser); CreateAccessKeyRequest apkAccessRequest = new CreateAccessKeyRequest(); apkAccessRequest.setUserName(apkUser); CreateAccessKeyResult apkAccessResult = iamClient.createAccessKey(apkAccessRequest); accessKeys.put(apkUser, apkAccessResult.getAccessKey()); System.out.println("Configuring security policies..."); Configuration cfg = new Configuration(); cfg.setClassForTemplateLoading(InstanceConfigurator.class, "/org/akvo/flow/templates"); cfg.setObjectWrapper(new DefaultObjectWrapper()); cfg.setDefaultEncoding("UTF-8"); Map<String, Object> data = new HashMap<String, Object>(); data.put("bucketName", bucketName); data.put("version", new SimpleDateFormat("yyyy-MM-dd").format(new Date())); data.put("accessKey", accessKeys); Template t1 = cfg.getTemplate("apk-s3-policy.ftl"); StringWriter apkPolicy = new StringWriter(); t1.process(data, apkPolicy); Template t2 = cfg.getTemplate("gae-s3-policy.ftl"); StringWriter gaePolicy = new StringWriter(); t2.process(data, gaePolicy); iamClient.putUserPolicy( new PutUserPolicyRequest(apkUser, apkUser, Policy.fromJson(apkPolicy.toString()).toJson())); iamClient.putUserPolicy( new PutUserPolicyRequest(gaeUser, gaeUser, Policy.fromJson(gaePolicy.toString()).toJson())); System.out.println("Creating configuration files..."); // survey.properties Map<String, Object> apkData = new HashMap<String, Object>(); apkData.put("awsBucket", bucketName); apkData.put("awsAccessKeyId", accessKeys.get(apkUser).getAccessKeyId()); apkData.put("awsSecretKey", accessKeys.get(apkUser).getSecretAccessKey()); apkData.put("serverBase", "https://" + gaeId + ".appspot.com"); apkData.put("restApiKey", apiKey); Template t3 = cfg.getTemplate("survey.properties.ftl"); FileWriter fw = new FileWriter(new File(out, "/survey.properties")); t3.process(apkData, fw); // appengine-web.xml Map<String, Object> webData = new HashMap<String, Object>(); webData.put("awsBucket", bucketName); webData.put("awsAccessKeyId", accessKeys.get(gaeUser).getAccessKeyId()); webData.put("awsSecretAccessKey", accessKeys.get(gaeUser).getSecretAccessKey()); webData.put("s3url", "https://" + bucketName + ".s3.amazonaws.com"); webData.put("instanceId", gaeId); webData.put("alias", alias); webData.put("flowServices", flowServices); webData.put("apiKey", apiKey); webData.put("emailFrom", emailFrom); webData.put("emailTo", emailTo); webData.put("organization", orgName); webData.put("signingKey", signingKey); Template t5 = cfg.getTemplate("appengine-web.xml.ftl"); FileWriter fw3 = new FileWriter(new File(out, "/appengine-web.xml")); t5.process(webData, fw3); System.out.println("Done"); }
From source file:org.apache.usergrid.apm.service.ApplicationServiceImpl.java
License:Apache License
public AccessKey createAuthorizedAppPrinciple(Long applicationId, String orgAppName) { CreateUserRequest createUserRequest = new CreateUserRequest(); createUserRequest.setUserName(APP_PRINCIPLE_USER_PREFIX + "_" + orgAppName); createUserRequest.setRequestCredentials(awsCredentials); try {/*from w ww. j av a 2 s.com*/ CreateUserResult createUserResult = identityManagementClient.createUser(createUserRequest); log.info("cloud user id for app with " + orgAppName + " created with " + createUserResult.getUser().getUserName()); CreateAccessKeyRequest accessKeyRequest = new CreateAccessKeyRequest(); accessKeyRequest.setUserName(createUserResult.getUser().getUserName()); CreateAccessKeyResult accessKeyResult = identityManagementClient.createAccessKey(accessKeyRequest); //Create policy of queue GetQueueAttributesRequest attributesRequest = new GetQueueAttributesRequest(); log.info("Going to secure sqs queue : " + AWSUtil.formFullQueueUrl(orgAppName)); attributesRequest.setQueueUrl(AWSUtil.formFullQueueUrl(orgAppName)); List<String> attributeNames = new ArrayList<String>(); attributeNames.add("QueueArn"); attributesRequest.setAttributeNames(attributeNames); GetQueueAttributesResult attributesResult = sqsClient.getQueueAttributes(attributesRequest); String queueArn = attributesResult.getAttributes().get("QueueArn"); String policy = POLICY_DOCUMENT_TEMPLATE.replace("QUEUE_ARN", queueArn); String formattedPolicy = String.format(POLICY_DOCUMENT_TEMPLATE, queueArn); log.info("Applying authorization for following AWS resources" + formattedPolicy); PutUserPolicyRequest policyRequest = new PutUserPolicyRequest(); policyRequest.setPolicyName(POLICY_NAME); policyRequest.setPolicyDocument(formattedPolicy); policyRequest.setUserName(createUserResult.getUser().getUserName()); identityManagementClient.putUserPolicy(policyRequest); log.info("User policy for queue " + queueArn + " was set"); return accessKeyResult.getAccessKey(); } catch (EntityAlreadyExistsException e) { log.error("This should not happen in production. Swallowing the error fow now " + e.getMessage()); log.error(e); return null; } }
From source file:org.applicationMigrator.userManagement.UserManagementWorker.java
License:Apache License
private void createUser(String ANDROID_ID) throws FileNotFoundException, IllegalArgumentException, IOException { Random randomizer = new Random(System.currentTimeMillis()); String userName = "User" + randomizer.nextDouble(); CreateUserRequest user = new CreateUserRequest(); user.setUserName(userName);//from w w w . j av a2s. c o m AWSCredentials credentials = new PropertiesCredentials( new File("C:\\AndroidMigration\\Credentials\\AwsCredentials.properties")); AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(credentials); CreateUserResult result = null; AccessKey accessKey = null; try { boolean userCreatedSuccessfully = false; while (!userCreatedSuccessfully) { try { result = client.createUser(user); userCreatedSuccessfully = true; } catch (EntityAlreadyExistsException exception) { user.setUserName(userName + randomizer.nextDouble()); userCreatedSuccessfully = false; } } CreateAccessKeyRequest accessKeyRequest = new CreateAccessKeyRequest(); accessKeyRequest.setUserName(result.getUser().getUserName()); CreateAccessKeyResult accessKeyResult = client.createAccessKey(accessKeyRequest); accessKey = accessKeyResult.getAccessKey(); grantPermissions(user, client); File userList = new File(USER_LIST_FILEPATH); BufferedWriter userListFileWriter = new BufferedWriter(new FileWriter(userList)); // Concurrency ? userListFileWriter.write(ANDROID_ID + " "); userListFileWriter.write(accessKey.getAccessKeyId() + " "); userListFileWriter.write(accessKey.getSecretAccessKey() + " "); userListFileWriter.write(user.getUserName() + " "); userListFileWriter.close(); } catch (Exception e) { if (accessKey != null) { DeleteAccessKeyRequest deleteAccessKeyRequest = new DeleteAccessKeyRequest( accessKey.getAccessKeyId()); deleteAccessKeyRequest.setUserName(user.getUserName()); client.deleteAccessKey(deleteAccessKeyRequest); DeleteUserRequest deleteUserRequest = new DeleteUserRequest(user.getUserName()); client.deleteUser(deleteUserRequest); } throw e; } }