在Go语言中从EC2元数据服务获取AWS凭证。

huangapple go评论84阅读模式
英文:

get aws credentials from ec2 metadata services in Go

问题

如何让GO SDK从由AWS提供的实例元数据服务(169.254.169.254)中获取AWS的访问密钥?

我查看了官方的GO AWS SDK文档,似乎只有通过环境变量获取访问密钥的方法,没有从IMS中检索凭据的方法。

在GO中如何实现这个功能?

英文:

How can I make the GO SDK fetch the access keys for AWS from the Instance Metadata Service (169.254.169.254) provided by AWS.

I checked the official AWS SDK for go documentation and there seems to be only ways of fetching the access keys from environment variables, but no credentials retriever from IMS.

How is this done in go?

答案1

得分: 3

我查看了官方的 AWS SDK for Go 文档,似乎只有从环境变量中获取访问密钥的方法,但没有从 IMS 检索凭据的方法。

你刚刚错过了。Go SDK 支持实例元数据服务以及其他常见的凭据提供程序。

根据 https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html

如果你已经配置了 IAM 角色来使用你的实例,SDK 会自动使用这些凭据进行应用程序。

你不需要进行任何配置。它应该可以正常工作。如果你遇到问题,请确保你没有手动配置其他凭据来源。

通常,你只需要像这样做:

sess := session.Must(
  session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
  }),
)

无论是否有 CLI 配置、元数据服务或环境变量,它都应该可以在任何地方正常工作。

英文:

> I checked the official AWS SDK for go documentation and there seems to be only ways of fetching the access keys from environment variables, but no credentials retriever from IMS.

You just missed it. The Go SDK supports the instance metadata service as well as every other common credentials provider.

From https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html:

> If you have configured your instance to use IAM roles, the SDK uses these credentials for your application automatically.

You don't have to do anything to configure this. It should just work. If you're having problems, make sure that you're not manually configuring some other credentials source.

Usually you don't have to do anything more than something like:

  sess := session.Must(
    session.NewSessionWithOptions(session.Options{
      SharedConfigState: session.SharedConfigEnable,
    }),
  )

And with or without CLI configuration, metadata service, or environment variables, it should just work wherever you run it.

huangapple
  • 本文由 发表于 2021年12月11日 06:24:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/70311009.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定