blob: 1d09d9eba071910ef081998c6d997ae13ca81015 [file] [log] [blame]
Jamie Hannaford2aaf1a62014-10-16 12:55:50 +02001// Package utils contains utilities which eases working with Gophercloud's OpenStack APIs.
2package utils
3
4import (
5 "fmt"
6 "os"
7
8 "github.com/rackspace/gophercloud"
9)
10
11var nilOptions = gophercloud.AuthOptions{}
12
13// ErrNoAuthUrl, ErrNoUsername, and ErrNoPassword errors indicate of the required OS_AUTH_URL, OS_USERNAME, or OS_PASSWORD
14// environment variables, respectively, remain undefined. See the AuthOptions() function for more details.
15var (
16 ErrNoAuthURL = fmt.Errorf("Environment variable OS_AUTH_URL needs to be set.")
17 ErrNoUsername = fmt.Errorf("Environment variable OS_USERNAME needs to be set.")
18 ErrNoPassword = fmt.Errorf("Environment variable OS_PASSWORD needs to be set.")
19)
20
21// AuthOptions fills out an identity.AuthOptions structure with the settings found on the various OpenStack
22// OS_* environment variables. The following variables provide sources of truth: OS_AUTH_URL, OS_USERNAME,
23// OS_PASSWORD, OS_TENANT_ID, and OS_TENANT_NAME. Of these, OS_USERNAME, OS_PASSWORD, and OS_AUTH_URL must
24// have settings, or an error will result. OS_TENANT_ID and OS_TENANT_NAME are optional.
25func AuthOptions() (gophercloud.AuthOptions, error) {
26 authURL := os.Getenv("OS_AUTH_URL")
27 username := os.Getenv("OS_USERNAME")
28 userID := os.Getenv("OS_USERID")
29 password := os.Getenv("OS_PASSWORD")
30 tenantID := os.Getenv("OS_TENANT_ID")
31 tenantName := os.Getenv("OS_TENANT_NAME")
32 domainID := os.Getenv("OS_DOMAIN_ID")
33 domainName := os.Getenv("OS_DOMAIN_NAME")
34
35 if authURL == "" {
36 return nilOptions, ErrNoAuthURL
37 }
38
39 if username == "" && userID == "" {
40 return nilOptions, ErrNoUsername
41 }
42
43 if password == "" {
44 return nilOptions, ErrNoPassword
45 }
46
47 ao := gophercloud.AuthOptions{
48 IdentityEndpoint: authURL,
49 UserID: userID,
50 Username: username,
51 Password: password,
52 TenantID: tenantID,
53 TenantName: tenantName,
54 DomainID: domainID,
55 DomainName: domainName,
56 }
57
58 return ao, nil
59}
60
61// BuildQuery constructs the query section of a URI from a map.
62func BuildQuery(params map[string]string) string {
63 if len(params) == 0 {
64 return ""
65 }
66
67 query := "?"
68 for k, v := range params {
69 query += k + "=" + v + "&"
70 }
71 query = query[:len(query)-1]
72 return query
73}