简体   繁体   English

AWS JAVA SDK - 我可以使用在同一 aws 帐户内运行的 aws sdk 以编程方式访问其他服务而无需硬编码凭据吗?

[英]AWS JAVA SDK - Can i programmatically access other services using aws sdk running inside same aws account without hard coding credentials?

I have java code running in fargate cluster, I need to access other aws services from within the java code using aws sdk. Right now I have hard-coded access/secret/token inside java class and it is working fine.我有 java 代码在 fargate 集群中运行,我需要使用 aws sdk 从 java 代码中访问其他 aws 服务。现在我在 java class 中有硬编码访问/秘密/令牌,它工作正常。

BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(accessKey, secretAccessKey, token);

Since I am running java code from within the same aws account, so is there a better way so that i don't have to hard code credentials?由于我从同一个 aws 帐户中运行 java 代码,所以有没有更好的方法让我不必硬编码凭据?

Yes, you can always assign task role to your task.是的,您始终可以为您的任务分配任务角色。 The SDK will then automatically figure out the credentials and use them when making requests.然后 SDK 将自动计算出凭据并在发出请求时使用它们。

The trust policy would look something like this:信任策略看起来像这样:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "ecs-tasks.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

Then you need to specify the policy document.然后你需要指定策略文件。 With this in place the SDK will figure out the reset.有了这个,SDK 将计算出重置。 You can find more information in AWS documentation here: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html您可以在此处的 AWS 文档中找到更多信息: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html

I got it working by using DefaultAWSCredentialsProviderChain.java while building target service client.我在构建目标服务客户端时通过使用 DefaultAWSCredentialsProviderChain.java 使其正常工作。 Along with that I added permissions for target service in the role attached to calling service.与此同时,我在附加到调用服务的角色中添加了目标服务的权限。 For example - If code running inside ECS tasks needs to call SSM service, add permissions to role attached to ECS tasks to perform actions on SSM and from code instead of hard coding credentials use below mentioned code:例如 - 如果在 ECS 任务中运行的代码需要调用 SSM 服务,请向附加到 ECS 任务的角色添加权限以对 SSM 执行操作,并从代码而不是硬编码凭据使用下面提到的代码:

AWSSimpleSystemsManagement awsSimpleSystemsManagement = AWSSimpleSystemsManagementClient.builder()
                .withCredentials(new DefaultAWSCredentialsProviderChain());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM