github.com/chalford/terraform@v0.3.7-0.20150113080010-a78c69a8c81f/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 ClientSecretsFile string 22 Project string 23 Region string 24 25 clientCompute *compute.Service 26 } 27 28 func (c *Config) loadAndValidate() error { 29 var account accountFile 30 var secrets clientSecretsFile 31 32 if err := loadJSON(&account, c.AccountFile); err != nil { 33 return fmt.Errorf( 34 "Error loading account file '%s': %s", 35 c.AccountFile, 36 err) 37 } 38 39 if err := loadJSON(&secrets, c.ClientSecretsFile); err != nil { 40 return fmt.Errorf( 41 "Error loading client secrets file '%s': %s", 42 c.ClientSecretsFile, 43 err) 44 } 45 46 // Get the token for use in our requests 47 log.Printf("[INFO] Requesting Google token...") 48 log.Printf("[INFO] -- Email: %s", account.ClientEmail) 49 log.Printf("[INFO] -- Scopes: %s", clientScopes) 50 log.Printf("[INFO] -- Private Key Length: %d", len(account.PrivateKey)) 51 log.Printf("[INFO] -- Token URL: %s", secrets.Web.TokenURI) 52 jwtTok := jwt.NewToken( 53 account.ClientEmail, 54 clientScopes, 55 []byte(account.PrivateKey)) 56 jwtTok.ClaimSet.Aud = secrets.Web.TokenURI 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 TokenURL: secrets.Web.TokenURI, 68 AuthURL: secrets.Web.AuthURI, 69 }, 70 Token: token, 71 } 72 73 log.Printf("[INFO] Instantiating GCE client...") 74 c.clientCompute, err = compute.New(transport.Client()) 75 if err != nil { 76 return err 77 } 78 79 return nil 80 } 81 82 // accountFile represents the structure of the account file JSON file. 83 type accountFile struct { 84 PrivateKeyId string `json:"private_key_id"` 85 PrivateKey string `json:"private_key"` 86 ClientEmail string `json:"client_email"` 87 ClientId string `json:"client_id"` 88 } 89 90 // clientSecretsFile represents the structure of the client secrets JSON file. 91 type clientSecretsFile struct { 92 Web struct { 93 AuthURI string `json:"auth_uri"` 94 ClientEmail string `json:"client_email"` 95 ClientId string `json:"client_id"` 96 TokenURI string `json:"token_uri"` 97 } 98 } 99 100 func loadJSON(result interface{}, path string) error { 101 f, err := os.Open(path) 102 if err != nil { 103 return err 104 } 105 defer f.Close() 106 107 dec := json.NewDecoder(f) 108 return dec.Decode(result) 109 }