azure.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package metadata
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "k8s.io/klog/v2"
  6. )
  7. const (
  8. azureEndpoint = "http://169.254.169.254/metadata/instance"
  9. )
  10. type azureIp struct {
  11. Private string `json:"privateIpAddress"`
  12. Public string `json:"publicIpAddress"`
  13. }
  14. type azureInterface struct {
  15. Ipv4 struct {
  16. IpAddress []azureIp `json:"ipAddress"`
  17. }
  18. }
  19. type azureInstanceMetadata struct {
  20. Compute struct {
  21. Region string `json:"location"`
  22. Id string `json:"vmID"`
  23. Type string `json:"vmSize"`
  24. Zone string `json:"zone"`
  25. SubscriptionId string `json:"subscriptionId"`
  26. }
  27. Network struct {
  28. Interface []azureInterface `json:"interface"`
  29. }
  30. }
  31. func getAzureMetadata() *CloudMetadata {
  32. r, _ := http.NewRequest(http.MethodGet, azureEndpoint, nil)
  33. r.Header.Add("Metadata", "True")
  34. q := r.URL.Query()
  35. q.Add("format", "json")
  36. q.Add("api-version", "2021-05-01")
  37. r.URL.RawQuery = q.Encode()
  38. resp, err := httpCallWithTimeout(r)
  39. if err != nil {
  40. klog.Errorln(err)
  41. return nil
  42. }
  43. defer resp.Body.Close()
  44. instanceMd := &azureInstanceMetadata{}
  45. decoder := json.NewDecoder(resp.Body)
  46. if err := decoder.Decode(instanceMd); err != nil {
  47. klog.Errorln("failed to unmarshall response of Azure metadata service:", err)
  48. return nil
  49. }
  50. md := &CloudMetadata{
  51. Provider: CloudProviderAzure,
  52. AccountId: instanceMd.Compute.SubscriptionId,
  53. InstanceId: instanceMd.Compute.Id,
  54. InstanceType: instanceMd.Compute.Type,
  55. Region: instanceMd.Compute.Region,
  56. AvailabilityZone: instanceMd.Compute.Zone,
  57. }
  58. if len(instanceMd.Network.Interface) > 0 && len(instanceMd.Network.Interface[0].Ipv4.IpAddress) > 0 {
  59. md.LocalIPv4 = instanceMd.Network.Interface[0].Ipv4.IpAddress[0].Private
  60. md.PublicIPv4 = instanceMd.Network.Interface[0].Ipv4.IpAddress[0].Public
  61. }
  62. return md
  63. }