azure.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package metadata
  2. import (
  3. "encoding/json"
  4. "k8s.io/klog/v2"
  5. "net/http"
  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. req, err := http.NewRequest(http.MethodGet, azureEndpoint, nil)
  33. if err != nil {
  34. klog.Errorln(err)
  35. return nil
  36. }
  37. req.Header.Add("Metadata", "True")
  38. q := req.URL.Query()
  39. q.Add("format", "json")
  40. q.Add("api-version", "2021-05-01")
  41. req.URL.RawQuery = q.Encode()
  42. client := http.DefaultClient
  43. client.Timeout = metadataServiceTimeout
  44. resp, err := client.Do(req)
  45. if err != nil {
  46. klog.Errorln(err)
  47. return nil
  48. }
  49. if resp.StatusCode != 200 {
  50. klog.Errorln("metadata service response:", resp.Status)
  51. return nil
  52. }
  53. defer resp.Body.Close()
  54. instanceMd := &azureInstanceMetadata{}
  55. decoder := json.NewDecoder(resp.Body)
  56. if err := decoder.Decode(instanceMd); err != nil {
  57. klog.Errorln("failed to unmarshall response of Azure metadata service:", err)
  58. return nil
  59. }
  60. md := &CloudMetadata{
  61. Provider: CloudProviderAzure,
  62. AccountId: instanceMd.Compute.SubscriptionId,
  63. InstanceId: instanceMd.Compute.Id,
  64. InstanceType: instanceMd.Compute.Type,
  65. Region: instanceMd.Compute.Region,
  66. AvailabilityZone: instanceMd.Compute.Zone,
  67. }
  68. if len(instanceMd.Network.Interface) > 0 && len(instanceMd.Network.Interface[0].Ipv4.IpAddress) > 0 {
  69. md.LocalIPv4 = instanceMd.Network.Interface[0].Ipv4.IpAddress[0].Private
  70. md.PublicIPv4 = instanceMd.Network.Interface[0].Ipv4.IpAddress[0].Public
  71. }
  72. return md
  73. }