Rufus Deponian 6 gadi atpakaļ
revīzija
7c52c61c70
3 mainītis faili ar 102 papildinājumiem un 0 dzēšanām
  1. 1 0
      .gitignore
  2. 13 0
      identity_template.conf
  3. 88 0
      main.go

+ 1 - 0
.gitignore

@@ -0,0 +1 @@
+identity.conf

+ 13 - 0
identity_template.conf

@@ -0,0 +1,13 @@
+[openstack]
+identity_endpoint = http://controller-IP:5000/v3
+
+# Данные о пользователе, от лица которого будут выполняться запросы
+# Пользователь должен иметь роль облачного администратора
+domain_name = internal
+project_name = admin
+username = GeraltFromRivia
+password = Plotva
+
+# Данные о регионе, который будет использоваться при создание compute-клиента
+region = Moscow
+

+ 88 - 0
main.go

@@ -0,0 +1,88 @@
+package main
+
+import (
+	"fmt"
+	"os"
+
+	"github.com/alyu/configparser"
+	"github.com/gophercloud/gophercloud"
+	"github.com/gophercloud/gophercloud/openstack"
+	"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
+)
+
+func main() {
+	config, err := configparser.Read("./identity.conf")
+	checkErr(err)
+	section, err := config.Section("openstack")
+	checkErr(err)
+	region := section.ValueOf("region")
+
+	provider := createProvider(config)
+
+	computeClient, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
+		Region: region,
+	})
+	checkErr(err)
+
+	file, err := os.Create("./instance_list.csv")
+	checkErr(err)
+	defer file.Close()
+
+	_, err = file.WriteString("InstanceID, InstanceIP, InstanceName\n")
+	checkErr(err)
+
+	allServers := getAllServers(computeClient)
+	for _, server := range allServers {
+		addresses := server.Addresses["VM network"].([]interface{})
+		addressDetails := addresses[0].(map[string]interface{})
+		serverIP := addressDetails["addr"]
+
+		str := fmt.Sprintf("%v,%v,%v\n", server.ID, serverIP, server.Name)
+		_, err := file.WriteString(str)
+		checkErr(err)
+	}
+}
+
+func createProvider(config *configparser.Configuration) *gophercloud.ProviderClient {
+	section, err := config.Section("openstack")
+	checkErr(err)
+
+	opts := gophercloud.AuthOptions{
+		IdentityEndpoint: section.ValueOf("identity_endpoint"),
+		DomainName:       section.ValueOf("domain_name"),
+		TenantName:       section.ValueOf("project_name"),
+		Username:         section.ValueOf("username"),
+		Password:         section.ValueOf("password"),
+	}
+
+	provider, err := openstack.AuthenticatedClient(opts)
+	checkErr(err)
+
+	return provider
+}
+
+func getAllServers(client *gophercloud.ServiceClient) []servers.Server {
+	listOpts := servers.ListOpts{
+		AllTenants: true,
+	}
+
+	allPages, err := servers.List(client, listOpts).AllPages()
+	checkErr(err)
+
+	allServers, err := servers.ExtractServers(allPages)
+	checkErr(err)
+
+	return allServers
+}
+
+// H E L P E R S
+
+func checkErr(err error) {
+	if err != nil {
+		panic(err)
+	}
+}
+
+func pointerFromBool(b bool) *bool {
+	return &b
+}