github.com/arvindram03/terraform@v0.3.7-0.20150212015210-408f838db36d/builtin/providers/google/config.go (about) 1 package google 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "log" 7 "net/http" 8 "os" 9 10 "code.google.com/p/goauth2/oauth" 11 "code.google.com/p/goauth2/oauth/jwt" 12 "code.google.com/p/google-api-go-client/compute/v1" 13 ) 14 15 const clientScopes string = "https://www.googleapis.com/auth/compute" 16 17 // Config is the configuration structure used to instantiate the Google 18 // provider. 19 type Config struct { 20 AccountFile string 21 Project string 22 Region string 23 24 clientCompute *compute.Service 25 } 26 27 func (c *Config) loadAndValidate() error { 28 var account accountFile 29 30 // TODO: validation that it isn't blank 31 if c.AccountFile == "" { 32 c.AccountFile = os.Getenv("GOOGLE_ACCOUNT_FILE") 33 } 34 if c.Project == "" { 35 c.Project = os.Getenv("GOOGLE_PROJECT") 36 } 37 if c.Region == "" { 38 c.Region = os.Getenv("GOOGLE_REGION") 39 } 40 41 if err := loadJSON(&account, c.AccountFile); err != nil { 42 return fmt.Errorf( 43 "Error loading account file '%s': %s", 44 c.AccountFile, 45 err) 46 } 47 48 // Get the token for use in our requests 49 log.Printf("[INFO] Requesting Google token...") 50 log.Printf("[INFO] -- Email: %s", account.ClientEmail) 51 log.Printf("[INFO] -- Scopes: %s", clientScopes) 52 log.Printf("[INFO] -- Private Key Length: %d", len(account.PrivateKey)) 53 jwtTok := jwt.NewToken( 54 account.ClientEmail, 55 clientScopes, 56 []byte(account.PrivateKey)) 57 token, err := jwtTok.Assert(new(http.Client)) 58 if err != nil { 59 return fmt.Errorf("Error retrieving auth token: %s", err) 60 } 61 62 // Instantiate the transport to communicate to Google 63 transport := &oauth.Transport{ 64 Config: &oauth.Config{ 65 ClientId: account.ClientId, 66 Scope: clientScopes, 67 }, 68 Token: token, 69 } 70 71 log.Printf("[INFO] Instantiating GCE client...") 72 c.clientCompute, err = compute.New(transport.Client()) 73 if err != nil { 74 return err 75 } 76 77 return nil 78 } 79 80 // accountFile represents the structure of the account file JSON file. 81 type accountFile struct { 82 PrivateKeyId string `json:"private_key_id"` 83 PrivateKey string `json:"private_key"` 84 ClientEmail string `json:"client_email"` 85 ClientId string `json:"client_id"` 86 } 87 88 func loadJSON(result interface{}, path string) error { 89 f, err := os.Open(path) 90 if err != nil { 91 return err 92 } 93 defer f.Close() 94 95 dec := json.NewDecoder(f) 96 return dec.Decode(result) 97 }