【问题标题】:How to get a list of AWS regions programmatically in Go SDK V2如何在 Go SDK V2 中以编程方式获取 AWS 区域列表
【发布时间】:2021-04-26 20:10:49
【问题描述】:

AWS 从Go SDK V2 中删除了endpoints 包。有没有办法使用 Go SDK V2 获取 AWS 区域列表?

在 V1 中你可以这样写:

    import "github.com/aws/aws-sdk-go/aws/endpoints"
    ...
    ...
    
        partitions := endpoints.DefaultPartitions()
        for _, p := range partitions {
            for region := range p.Regions() {
                validRegions[region] = struct{}{}
            }
        }
    
    ...
    ...

但是,这似乎不再可能。我确实注意到了一个自动生成的json,它似乎包含所有分区,但是我似乎无法弄清楚如何在代码中获取可用区域的列表。

有没有办法在 Go SDK V2 中做到这一点?

【问题讨论】:

  • 你有其他选择吗?

标签: amazon-web-services aws-sdk aws-sdk-go


【解决方案1】:

没有办法。新的 SDK 被设计破坏,不应使用。

【讨论】:

    【解决方案2】:

    一种选择是获取您提到的 JSON,例如:

    // endpoints holds the aws generated endpoints.json
    type endpoints struct {
        Partitions []Partition `json:"partitions"`
    }
    
    type Partition struct {
        PartitionName string                 `json:"partitionName"`
        Regions       map[string]interface{} `json:"regions"`
        Services      map[string]Service     `json:"services"`
    }
    
    type Service struct {
        Endpoints map[string]interface{} `json:"endpoints"`
    }
    
    func main() {
    
        fmt.Println("Generating AWS regions")
    
        resp, err := http.Get("https://raw.githubusercontent.com/aws/aws-sdk-go-v2/master/codegen/smithy-aws-go-codegen/src/main/resources/software/amazon/smithy/aws/go/codegen/endpoints.json")
        if err != nil {
            fmt.Fprintln(os.Stderr, err.Error())
        }
    
        defer resp.Body.Close()
    
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
            fmt.Fprintln(os.Stderr, err.Error())
        }
    
        e := endpoints{}
        err = json.Unmarshal(body, &e)
        if err != nil {
            fmt.Fprintln(os.Stderr, err.Error())
        }
    
        // do something with e
    }
    

    【讨论】:

      【解决方案3】:

      EC2客户端中有DescribeRegions方法:https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/ec2#Client.DescribeRegions

      您可以请求所有区域,或根据选择加入状态进行过滤。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-23
        • 2012-05-22
        • 1970-01-01
        • 2018-03-16
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        • 2018-10-26
        相关资源
        最近更新 更多