github.com/sneal/packer@v0.5.2/builder/openstack/access_config.go (about) 1 package openstack 2 3 import ( 4 "fmt" 5 "github.com/mitchellh/packer/packer" 6 "github.com/rackspace/gophercloud" 7 "net/http" 8 "net/url" 9 "os" 10 ) 11 12 // AccessConfig is for common configuration related to openstack access 13 type AccessConfig struct { 14 Username string `mapstructure:"username"` 15 Password string `mapstructure:"password"` 16 Project string `mapstructure:"project"` 17 Provider string `mapstructure:"provider"` 18 RawRegion string `mapstructure:"region"` 19 ProxyUrl string `mapstructure:"proxy_url"` 20 } 21 22 // Auth returns a valid Auth object for access to openstack services, or 23 // an error if the authentication couldn't be resolved. 24 func (c *AccessConfig) Auth() (gophercloud.AccessProvider, error) { 25 username := c.Username 26 password := c.Password 27 project := c.Project 28 provider := c.Provider 29 proxy := c.ProxyUrl 30 31 if username == "" { 32 username = os.Getenv("SDK_USERNAME") 33 } 34 if password == "" { 35 password = os.Getenv("SDK_PASSWORD") 36 } 37 if project == "" { 38 project = os.Getenv("SDK_PROJECT") 39 } 40 if provider == "" { 41 provider = os.Getenv("SDK_PROVIDER") 42 } 43 44 authoptions := gophercloud.AuthOptions{ 45 Username: username, 46 Password: password, 47 AllowReauth: true, 48 } 49 50 if project != "" { 51 authoptions.TenantName = project 52 } 53 54 // For corporate networks it may be the case where we want our API calls 55 // to be sent through a separate HTTP proxy than external traffic. 56 if proxy != "" { 57 url, err := url.Parse(proxy) 58 if err != nil { 59 return nil, err 60 } 61 62 // The gophercloud.Context has a UseCustomClient method which 63 // would allow us to override with a new instance of http.Client. 64 http.DefaultTransport = &http.Transport{Proxy: http.ProxyURL(url)} 65 } 66 67 return gophercloud.Authenticate(provider, authoptions) 68 } 69 70 func (c *AccessConfig) Region() string { 71 return c.RawRegion 72 } 73 74 func (c *AccessConfig) Prepare(t *packer.ConfigTemplate) []error { 75 if t == nil { 76 var err error 77 t, err = packer.NewConfigTemplate() 78 if err != nil { 79 return []error{err} 80 } 81 } 82 83 templates := map[string]*string{ 84 "username": &c.Username, 85 "password": &c.Password, 86 "provider": &c.Provider, 87 } 88 89 errs := make([]error, 0) 90 for n, ptr := range templates { 91 var err error 92 *ptr, err = t.Process(*ptr, nil) 93 if err != nil { 94 errs = append( 95 errs, fmt.Errorf("Error processing %s: %s", n, err)) 96 } 97 } 98 99 if c.RawRegion == "" { 100 errs = append(errs, fmt.Errorf("region must be specified")) 101 } 102 103 if len(errs) > 0 { 104 return errs 105 } 106 107 return nil 108 }