我有2个帐户
账户A和账户B
在账户 A 中,我已部署 (Amazon S3) 我的 Lambda 函数。
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler<Request, Response> {
public Response handleRequest(Request request, Context context) {
String greetingString = String.format("Hello %s %s.",
request.firstName, request.lastName);
//Here I need to get the Account B's bucket info
return new Response(greetingString);
}
}
在账户 A 中,我正在创建 IAM 角色“my-lambda”,并将其映射到用户 X
在账户 B 中,我创建了策略来授予角色“my-lambda”的用户权限如何利用用户X的IAM角色获取账户B的bucket信息???
注意:如果我直接提供凭据,我可以获取帐户 B 的存储桶信息
AWSCredentials longTermCredentials_ = new PropertiesCredentials(LambdaFunctionHandler .class.getResourceAsStream("/resources/"+"AwsCredentials.properties"));
AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(longTermCredentials_);
GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest();
GetSessionTokenResult sessionTokenResult = stsClient.getSessionToken(getSessionTokenRequest);
Credentials sessionCredentials = sessionTokenResult.getCredentials();
BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(sessionCredentials.getAccessKeyId(),sessionCredentials.getSecretAccessKey(),sessionCredentials.getSessionToken());
AmazonS3Client s3Client = new AmazonS3Client(basicSessionCredentials);
ListObjectsRequest listObjectsRequest = new ListObjectsRequest().withBucketName("bucketName");
ObjectListing objectListing;
do {
objectListing = s3.listObjects(listObjectsRequest);
for (S3ObjectSummary objectSummary : objectListing
.getObjectSummaries()) {
String key = objectSummary.getKey();
}
listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());
您可以使用STSAssumeRoleSessionCredentialsProvider类来帮助根据您的长期凭据承担角色并获取 S3 客户端的临时凭据。
AWSCredentials longTermCredentials_ = ...
STSAssumeRoleSessionCredentialsProvider roleCredsProvider =
new STSAssumeRoleSessionCredentialsProvider(
longTermCredentials_,
"my_lambda",
"BucketListSession");
AmazonS3Client s3Client = new AmazonS3Client(roleCredsProvider);
我是一名优秀的程序员,十分优秀!