Skip to content

Instantly share code, notes, and snippets.

@vicly
Last active July 20, 2018 04:35
Show Gist options
  • Save vicly/473e357554e6126115c7d3b54174a0e2 to your computer and use it in GitHub Desktop.
Save vicly/473e357554e6126115c7d3b54174a0e2 to your computer and use it in GitHub Desktop.
[AWS init client] #AWS

credential from AWS profile

# ~/.aws/credentials
[a-profile]
aws_access_key_id = ...
aws_secret_access_key = ...
AWSCredentialsProvider awsCredentialsProvider = new ProfileCredentialsProvider("a-profile");
AmazonS3 s3 = AmazonS3ClientBuilder.standard()
    .withCredentials(awsCredentialsProvider)
    ...
    .build();

set HTTP Proxy

ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setProxyHost("<HOST_NAME>");
clientConfiguration.setProxyPort(<PORT>);

AmazonS3 s3 = AmazonS3ClientBuilder.standard()
    .withClientConfiguration(clientConfiguration)
    .withRegion(Regions.AP_SOUTHEAST_2)
    .withCredentials(awsCredentialsProvider)
    .build();

Assume role

You have an AWS user in company account, and want to manage resources in product account by assume role AWSAdmin.

step1: in product account, create role AWSAdmin can be assumed by user from company account

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::COMPANY-ACCOUNT-ID-WITHOUT-HYPHENS:root"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

step2: in company account, create user and allow it to assume the role in product account

{
  "Version": "2012-10-17",
  "Statement": {
    "Effect": "Allow",
    "Action": "sts:AssumeRole",
    "Resource": "arn:aws:iam::PRODUCT-ACCOUNT-ID-WITHOUT-HYPHENS:role/AWSAdmin"
  }
}

step3: assume role using Java

// init STS client
AWSCredentialsProvider awsCredentialsProvider = ..get the user credentials..;
AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder
    .standard()
    .withRegion(Regions.AP_SOUTHEAST_2)
    .withCredentials(awsCredentialsProvider)
    .build();

// assume role credential provider
String roleSessionName = "session-name";
String roleArn = "arn:aws:iam::<PRODUCT-ACCOUNT-ID-WITHOUT-HYPHENS>:role/AWSAdmin";
AWSSessionCredentialsProvider awsSessionCredentialsProvider =
    new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, roleSessionName)
        .withStsClient(sts)
        .withRoleSessionDurationSeconds(1800)
        .build();

// create client
AmazonS3 s3 = AmazonS3ClientBuilder.standard()
    .withClientConfiguration(clientConfiguration)
    .withRegion(Regions.AP_SOUTHEAST_2)
    .withCredentials(awsSessionCredentialsProvider)
    .build();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment