main.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "github.com/alyu/configparser"
  6. "github.com/gophercloud/gophercloud"
  7. "github.com/gophercloud/gophercloud/openstack"
  8. "github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
  9. )
  10. func main() {
  11. config, err := configparser.Read("./identity.conf")
  12. checkErr(err)
  13. section, err := config.Section("openstack")
  14. checkErr(err)
  15. region := section.ValueOf("region")
  16. provider := createProvider(config)
  17. computeClient, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
  18. Region: region,
  19. })
  20. checkErr(err)
  21. allServers := getAllServers(computeClient)
  22. for _, server := range allServers {
  23. addresses, ok := server.Addresses[section.ValueOf("network_name")].([]interface{})
  24. if !ok {
  25. continue
  26. }
  27. addressDetails := addresses[0].(map[string]interface{})
  28. serverIP := addressDetails["addr"]
  29. str := fmt.Sprintf("%v,%v,%v\n", server.ID, serverIP, server.Name)
  30. _, err := os.Stdout.WriteString(str)
  31. checkErr(err)
  32. }
  33. }
  34. func createProvider(config *configparser.Configuration) *gophercloud.ProviderClient {
  35. section, err := config.Section("openstack")
  36. checkErr(err)
  37. opts := gophercloud.AuthOptions{
  38. IdentityEndpoint: section.ValueOf("identity_endpoint"),
  39. DomainName: section.ValueOf("domain_name"),
  40. TenantName: section.ValueOf("project_name"),
  41. Username: section.ValueOf("username"),
  42. Password: section.ValueOf("password"),
  43. }
  44. provider, err := openstack.AuthenticatedClient(opts)
  45. checkErr(err)
  46. return provider
  47. }
  48. func getAllServers(client *gophercloud.ServiceClient) []servers.Server {
  49. listOpts := servers.ListOpts{
  50. AllTenants: true,
  51. }
  52. allPages, err := servers.List(client, listOpts).AllPages()
  53. checkErr(err)
  54. allServers, err := servers.ExtractServers(allPages)
  55. checkErr(err)
  56. return allServers
  57. }
  58. // H E L P E R S
  59. func checkErr(err error) {
  60. if err != nil {
  61. panic(err)
  62. }
  63. }
  64. func pointerFromBool(b bool) *bool {
  65. return &b
  66. }