使用Go SDK v2获取AWS EC2实例元数据。

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

Get aws ec2 instance metadata using go sdk v2

问题

我尝试了这个例子:
https://aws.github.io/aws-sdk-go-v2/docs/sdk-utilities/ec2-imds/

并且 go.mod 使用的是:
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.15

但是 localip 打印的结果是:
&{{0xc0002d1680} {map[{}:{[{<nil> false false {map[]}}]}]}}

有人成功运行过吗?

英文:

I try this example:
https://aws.github.io/aws-sdk-go-v2/docs/sdk-utilities/ec2-imds/

and go.mod is using:
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.15

but the localip prints as:
&{{0xc0002d1680} {map[{}:{[{<nil> false false {map[]}}]}]}}

Anyone have this working?

答案1

得分: 1

这是解决问题的方法,如果有人感兴趣,可以参考这个链接:https://github.com/natemarks/ec2metadata

英文:

This solves the problem if anyone is interested:
https://github.com/natemarks/ec2metadata

答案2

得分: 0

client.GetMetadata函数返回一个GetMetadataOutput对象,其中包含一个Content元素,该元素是类型为io.Reader的HTTP resp.Body。该元素还需要进一步转换为字符串,例如通过以下函数:

func copyToString(r io.Reader) (res string, err error) {
    var sb strings.Builder
    if _, err = io.Copy(&sb, r); err == nil {
        res = sb.String()
    }
    return
}

因此,AWS示例的正确版本应该返回:

localip_str, err := copyToString(localip.Content)
英文:

The client.GetMetadata function returns a GetMetadataOutput object with a Content element which is the HTTP resp.Body of type io.Reader. That element needs to be additionally converted to a string, e.g., via a function like this

func copyToString(r io.Reader) (res string, err error) {
    var sb strings.Builder
    if _, err = io.Copy(&amp;sb, r); err == nil {
	    res = sb.String()
    }
	return
}

So, a correct version of the AWS sample should return

localip_str, err := copyToString(localip.Content)

huangapple
  • 本文由 发表于 2022年9月8日 00:47:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/73639078.html
匿名

发表评论

匿名网友

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

确定