golang中的Azure函数,如何获取订阅id?

问题描述 投票:0回答:1

我有一个用 Go 编写的 Azure 函数,我需要获取运行该函数的订阅 ID。

如何从我的 go-coded Azure 函数中获取订阅 ID?

我查看了环境变量和 http.Request 内容,它们都不包含订阅 ID。

谢谢你, 大卫

go azure-functions
1个回答
0
投票

我们可以使用

SubscriptionsClient
包中的
armresources
。以下是使用 Azure SDK for Go 以编程方式检索订阅 ID 的代码。

要安装所需的软件包,请使用以下命令:

go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions

go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

我按照这个 link 获取 azidentity,并按照这个 link 使用 Visual Studio Code 在 Go 中创建函数。

以下 Azure 函数代码使用 Go 中的

azidentity
armsubscriptions
检索订阅 ID:

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "os"

    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armsubscriptions"
)


func helloHandler(w http.ResponseWriter, r *http.Request) {
    message := "This HTTP triggered function executed successfully. Pass a name in the query string for a personalized response.\n"
    name := r.URL.Query().Get("name")
    if name != "" {
        message = fmt.Sprintf("Hello, %s. This HTTP triggered function executed successfully.\n", name)
    }
    fmt.Fprint(w, message)
}


func printSubscriptions(ctx context.Context) {
    
    cred, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
        log.Fatalf("Failed to obtain credential: %v", err)
    }


    subClient, err := armsubscriptions.NewClient(cred, nil)
    if err != nil {
        log.Fatalf("Failed to create subscriptions client: %v", err)
    }

    pager := subClient.NewListPager(nil)

    for pager.More() {
        page, err := pager.NextPage(ctx)
        if err != nil {
            log.Fatalf("Failed to retrieve subscription page: %v", err)
        }
        for _, subscription := range page.Value {
            fmt.Printf("Subscription ID: %s\n", *subscription.SubscriptionID)
            fmt.Printf("Subscription Name: %s\n", *subscription.DisplayName)
        }
    }
}

func main() {

    ctx := context.Background()

    fmt.Println("Fetching Azure Subscriptions:")
    printSubscriptions(ctx)

    listenAddr := ":8080"
    if val, ok := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT"); ok {
        listenAddr = ":" + val
    }
    http.HandleFunc("/api/HttpExample", helloHandler)
    log.Printf("About to listen on %s. Go to http://127.0.0.1%s/", listenAddr, listenAddr)
    log.Fatal(http.ListenAndServe(listenAddr, nil))
}


输出: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.