Azure如何在Azure golang sdk中获取虚拟机的IP地址



能够使用此处提到的对象从azure获取有关VM的详细信息:https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2021-03-01/compute@v5.0.0+不兼容#VirtualMachine

无法获取该虚拟机的私有ip地址,或者找不到方法。为任何给定的虚拟机获取私有ip地址的方法是什么。

IP地址与Azure虚拟机的网络接口的IP配置相关联,您可以从网络包中找到该虚拟机的privateIPAddress。

您可以从类型InterfaceIPConfigurationsClientAPI或类型IPConfigurationProperties Format 获得引用

这里有一个对我有用的好例子:

参考编号: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)
}
}
}

最新更新