簡體   English   中英

Azure 如何在 azure golang sdk 中獲取虛擬機的 IP 地址

[英]Azure How to get IP Address for a VM in azure golang sdk

能夠使用此處提到的 object 從 azure 獲取有關 VM 的詳細信息: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-03-01/compute @v55.0.0+不兼容#VirtualMachine

無法獲取該 VM 的 privateIPAddress 或找不到執行此操作的方法。 為任何給定的虛擬機獲取私有 ip 地址的方法是什么。

The IP address is associated with IP configurations of the network interface for the Azure VM, you could find the privateIPAddress for that VM from the network Package.

您可以從InterfaceIPConfigurationsClientAPI 類型或 IPConfigurationPropertiesFormat類型中獲取參考

這是一個對我有用的好例子:

參考: https://github.com/Azure/azure-sdk-for-go/issues/18705#issuecomment-1196930026

ctx := context.Background()
// assumes you authenicated on the command line with `az login`
cred, err := azidentity.NewDefaultAzureCredential(&azidentity.DefaultAzureCredentialOptions{})
if err != nil {
    fmt.Println(err)
}

vmClient, err := armcompute.NewVirtualMachinesClient(subscriptionID, cred, nil)
if err != nil {
    fmt.Println(err)
}
nicClient, err := armnetwork.NewInterfacesClient(subscriptionID, cred, nil)
if err != nil {
    fmt.Println(err)
}

vm, err := vmClient.Get(ctx, "yourResourceGrp", "yourVmName", nil)
if err != nil {
    fmt.Println(err)
}

for _, nicRef := range vm.Properties.NetworkProfile.NetworkInterfaces {
    nicID, err := arm.ParseResourceID(*nicRef.ID)
    if err != nil {
        fmt.Println(err)
    }
    nic, err := nicClient.Get(ctx, nicID.ResourceGroupName, nicID.Name, nil)
    if err != nil {
        fmt.Println(err)
    }

    for _, ipCfg := range nic.Properties.IPConfigurations {
        if ipCfg.Properties.PublicIPAddress != nil &&
            ipCfg.Properties.PublicIPAddress.Properties != nil {
            publicIP := *ipCfg.Properties.PublicIPAddress.Properties.IPAddress
            fmt.Println("publicIP:", publicIP)
        }
        if ipCfg.Properties.PrivateIPAddress != nil {
            privateIP := *ipCfg.Properties.PrivateIPAddress
            log.Println("privateIP:", privateIP)
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM