Example usage for com.amazonaws.auth.profile ProfilesConfigFile getCredentials

List of usage examples for com.amazonaws.auth.profile ProfilesConfigFile getCredentials

Introduction

In this page you can find the example usage for com.amazonaws.auth.profile ProfilesConfigFile getCredentials.

Prototype

public AWSCredentials getCredentials(String profileName) 

Source Link

Document

Returns the AWS credentials for the specified profile.

Usage

From source file:com.okta.tools.awscli.java

License:Open Source License

private static String setAWSCredentials(AssumeRoleWithSAMLResult assumeResult, String credentialsProfileName)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials(
            assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());

    String awsAccessKey = temporaryCredentials.getAWSAccessKeyId();
    String awsSecretKey = temporaryCredentials.getAWSSecretKey();
    String awsSessionToken = temporaryCredentials.getSessionToken();

    //File file = new File(System.getProperty("user.home") + "/.aws/credentials");
    //file.getParentFile().mkdirs();
    //try {/*www .  j a v a  2s . c  o  m*/

    if (credentialsProfileName.startsWith("arn:aws:sts::")) {
        credentialsProfileName = credentialsProfileName.substring(13);
    }
    if (credentialsProfileName.contains(":assumed-role")) {
        credentialsProfileName = credentialsProfileName.replaceAll(":assumed-role", "");
    }

    Object[] args = { new String(credentialsProfileName) };
    //writer.println("[aws-okta]");
    MessageFormat fmt = new MessageFormat("[{0}]");
    String profileNameLine = fmt.format(args);

    ProfilesConfigFile profilesConfigFile = null;
    try {
        profilesConfigFile = new ProfilesConfigFile();
    } catch (AmazonClientException ace) {
        PopulateCredentialsFile(profileNameLine, awsAccessKey, awsSecretKey, awsSessionToken);
    }

    try {
        if (profilesConfigFile != null && profilesConfigFile.getCredentials(credentialsProfileName) != null) {

            //if we end up here, it means we were  able to find a matching profile
            PopulateCredentialsFile(profileNameLine, awsAccessKey, awsSecretKey, awsSessionToken);
        }
    } catch (IllegalArgumentException iae) {

        //if we end up here, it means we were not able to find a matching profile so we need to append one
        FileWriter fileWriter = new FileWriter(System.getProperty("user.home") + "/.aws/credentials", true); //TODO: need to be updated to work with Windows
        PrintWriter writer = new PrintWriter(fileWriter); // new PrintWriter(file, "UTF-8");
        WriteNewProfile(writer, profileNameLine, awsAccessKey, awsSecretKey, awsSessionToken);
        fileWriter.close();
    }

    return credentialsProfileName;
}