diff --git a/README.md b/README.md index 9ea271e..51be0d9 100644 --- a/README.md +++ b/README.md @@ -27,4 +27,10 @@ Return all VM names and their IDs ### GET -Return all assigned tags and their categories for the specified vm `:vm`. \ No newline at end of file +Return all assigned tags and their categories for the specified vm `:vm`. + +## /vms/:vm/fqdn + +### GET + +Return the fqdn of the specified vm `:vm` from the VMware guest tools \ No newline at end of file diff --git a/internal/api/vms.go b/internal/api/vms.go index b04a2ea..831ee0b 100644 --- a/internal/api/vms.go +++ b/internal/api/vms.go @@ -156,3 +156,41 @@ func GetVMTags(c internal.Config, username string, password string, VMID string) } } } + +type GuestNetworkingResponseDNSValues struct { + DomainName string `json:"domain_name"` + HostName string `json:"host_name"` +} + +type GuestNetworkingResponse struct { + DNSValues GuestNetworkingResponseDNSValues `json:"dns_values"` +} + +// GetFQDN uses the VMware guest tools to get the fqdn of a VM (if possible) +func GetFQDN(c internal.Config, username string, password string, VMID string) (string, error) { + if s, err := GetSession(c, username, password); err != nil { + return "", err + } else { + logrus.Debugf("Trying to figure out the fqdn for vm %s from %s for %s", VMID, c.Resty.BaseURL, username) + + var guestNetworkingResponse GuestNetworkingResponse + if r, err := c.Resty. + R(). + SetHeader("vmware-api-session-id", s). + SetResult(&guestNetworkingResponse). + SetPathParam("vm", VMID). + Get("/api/vcenter/vm/{vm}/guest/networking"); err != nil { + logrus.Error(err) + return "", err + } else { + if r.IsError() { + return "", fmt.Errorf("can not get FQDN (%s): %s", r.Status(), r.Body()) + } + return fmt.Sprintf( + "%s.%s", + guestNetworkingResponse.DNSValues.HostName, + guestNetworkingResponse.DNSValues.DomainName, + ), nil + } + } +} diff --git a/internal/endpoints/vms.go b/internal/endpoints/vms.go index b73bae8..4243534 100644 --- a/internal/endpoints/vms.go +++ b/internal/endpoints/vms.go @@ -23,6 +23,7 @@ func (V *VMSEndpoint) Register(engine *gin.Engine, config internal.Config) { V.config = config engine.GET("/vms", V.getVMS) engine.GET("/vms/:vm/tags", V.getVMTags) + engine.GET("/vms/:vm/fqdn", V.getFQDN) } // getVMS exposes all vms of the vCenter at /vms @@ -67,3 +68,24 @@ func (V *VMSEndpoint) getVMTags(context *gin.Context) { } } } + +func (V *VMSEndpoint) getFQDN(context *gin.Context) { + if r, ok := HandleRequest(context); ok { + var vm VMBinding + if err := context.ShouldBindUri(&vm); err != nil { + context.AbortWithStatusJSON(400, gin.H{ + "error": fmt.Sprintf("Missing VM id in path: %s", err), + }) + return + } + if fqdn, err := api.GetFQDN(V.config, r.Username, r.Password, vm.ID); err != nil { + context.AbortWithStatusJSON(500, gin.H{ + "error": fmt.Sprintf("Error getting tags: %s", err), + }) + } else { + context.JSON(200, gin.H{ + "fqdn": fqdn, + }) + } + } +}