我的应用程序是否需要请求 ec2 实例上的角色来配置会话或将其留空?

Does my application need to ask for a role on ec2 instance to configure the session or leave it empty?

我正在尝试在我的应用程序中使用 aws-sdk-go。在 EC2 实例上是 运行。现在在文档的配置凭据中,https://docs.aws.amazon.com/sdk-for-go/api/,它说它将查找

*Environment Credentials - Set of environment variables that are useful when sub processes are created for specific roles.

* Shared Credentials file (~/.aws/credentials) - This file stores your credentials based on a profile name and is useful for local development.

*EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials to application running on an EC2 instance. This removes the need to manage credential files in production.`

最好的顺序不是相反的顺序吗?但我的主要问题是我是否需要询问实例是否有角色,然后使用它来设置凭据(如果它有角色)?这是我不确定我需要做什么以及如何做的地方。

我确实尝试了一个简单的测试来创建一个空配置,基本上只设置区域和 运行 它在具有角色的实例上,它似乎有 "worked" 但在这种情况下,我不确定是否需要明确设置角色。

awsSDK.Config{
    Region:      awsSDK.String(a.region),
    MaxRetries:  awsSDK.Int(maxRetries),
    HTTPClient:  http.DefaultClient,
}

我只是想确认这样做是否正确。我的想法是我需要做类似下面的事情

   role = use sdk call to get role on machine
   set awsSDK.Config { Credentials: credentials form of role,
            ...
       }

   issue service command with returned client.

如果再 docs/pointers 就好了!

我从未使用过 go SDK,但如果未从任何其他来源找到凭据,我使用的 AWS SDK 会自动使用 EC2 实例角色。

这里有一篇 AWS 博客 post 解释了 AWS SDK 在获取凭证时遵循的方法:https://aws.amazon.com/blogs/security/a-new-and-standardized-way-to-manage-credentials-in-the-aws-sdks/。特别是,请参阅:

If you use code like this, the SDKs look for the credentials in this order:

  1. In environment variables. (Not the .NET SDK, as noted earlier.)
  2. In the central credentials file (~/.aws/credentials or %USERPROFILE%.awscredentials).
  3. In an existing default, SDK-specific configuration file, if one exists. This would be the case if you had been using the SDK before these changes were made.
  4. For the .NET SDK, in the SDK Store, if it exists.
  5. If the code is running on an EC2 instance, via an IAM role for Amazon EC2. In that case, the code gets temporary security credentials from the instance metadata service; the credentials have the permissions derived from the role that is associated with the instance.

在我的应用程序中,当我需要连接到 AWS 资源时,我倾向于使用具有特定预定义 IAM 角色的访问密钥和秘密密钥。假设我有这两个,我用来创建会话的代码是:

awsCredentials := credentials.NewStaticCredentials(awsAccessKeyID, awsSecretAccessKey, "")
awsSession = session.Must(session.NewSession(&aws.Config{
            Credentials: awsCredentials,
            Region:      aws.String(awsRegion),
        }))

当我使用它时,这两个键通常被指定为环境变量(如果我部署到 docker 容器)。

一个完整的例子:https://github.com/retgits/flogo-components/blob/master/activity/amazons3/activity.go