func readPrivateKey(pk string) (ssh.AuthMethod, error) { key, _, err := pathorcontents.Read(pk) if err != nil { return nil, fmt.Errorf("Failed to read private key %q: %s", pk, err) } // We parse the private key on our own first so that we can // show a nicer error if the private key has a password. block, _ := pem.Decode([]byte(key)) if block == nil { return nil, fmt.Errorf("Failed to read key %q: no key found", pk) } if block.Headers["Proc-Type"] == "4,ENCRYPTED" { return nil, fmt.Errorf( "Failed to read key %q: password protected keys are\n"+ "not supported. Please decrypt the key prior to use.", pk) } signer, err := ssh.ParsePrivateKey([]byte(key)) if err != nil { return nil, fmt.Errorf("Failed to parse key file %q: %s", pk, err) } return ssh.PublicKeys(signer), nil }
func validateAccountFile(v interface{}, k string) (warnings []string, errors []error) { if v == nil { return } value := v.(string) if value == "" { return } contents, wasPath, err := pathorcontents.Read(value) if err != nil { errors = append(errors, fmt.Errorf("Error loading Account File: %s", err)) } if wasPath { warnings = append(warnings, `account_file was provided as a path instead of as file contents. This support will be removed in the future. Please update your configuration to use ${file("filename.json")} instead.`) } var account accountFile if err := json.Unmarshal([]byte(contents), &account); err != nil { errors = append(errors, fmt.Errorf("account_file not valid JSON '%s': %s", contents, err)) } return }
func readSettings(pathOrContents string) (s []byte, ws []string, es []error) { contents, wasPath, err := pathorcontents.Read(pathOrContents) if err != nil { es = append(es, fmt.Errorf("error reading settings_file: %s", err)) } if wasPath { ws = append(ws, settingsPathWarnMsg) } var settings settingsData if err := xml.Unmarshal([]byte(contents), &settings); err != nil { es = append(es, fmt.Errorf("error parsing settings_file as XML: %s", err)) } s = []byte(contents) return }
func renderFile(d *schema.ResourceData) (string, error) { template := d.Get("template").(string) filename := d.Get("filename").(string) vars := d.Get("vars").(map[string]interface{}) if template == "" && filename != "" { template = filename } contents, _, err := pathorcontents.Read(template) if err != nil { return "", err } rendered, err := execute(contents, vars) if err != nil { return "", templateRenderError( fmt.Errorf("failed to render %v: %v", filename, err), ) } return rendered, nil }
func (c *Config) loadAndValidate() error { var account accountFile clientScopes := []string{ "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/ndev.clouddns.readwrite", "https://www.googleapis.com/auth/devstorage.full_control", } var client *http.Client if c.Credentials != "" { contents, _, err := pathorcontents.Read(c.Credentials) if err != nil { return fmt.Errorf("Error loading credentials: %s", err) } // Assume account_file is a JSON string if err := parseJSON(&account, contents); err != nil { return fmt.Errorf("Error parsing credentials '%s': %s", contents, err) } // Get the token for use in our requests log.Printf("[INFO] Requesting Google token...") log.Printf("[INFO] -- Email: %s", account.ClientEmail) log.Printf("[INFO] -- Scopes: %s", clientScopes) log.Printf("[INFO] -- Private Key Length: %d", len(account.PrivateKey)) conf := jwt.Config{ Email: account.ClientEmail, PrivateKey: []byte(account.PrivateKey), Scopes: clientScopes, TokenURL: "https://accounts.google.com/o/oauth2/token", } // Initiate an http.Client. The following GET request will be // authorized and authenticated on the behalf of // your service account. client = conf.Client(oauth2.NoContext) } else { log.Printf("[INFO] Authenticating using DefaultClient") err := error(nil) client, err = google.DefaultClient(oauth2.NoContext, clientScopes...) if err != nil { return err } } versionString := terraform.Version prerelease := terraform.VersionPrerelease if len(prerelease) > 0 { versionString = fmt.Sprintf("%s-%s", versionString, prerelease) } userAgent := fmt.Sprintf( "(%s %s) Terraform/%s", runtime.GOOS, runtime.GOARCH, versionString) var err error log.Printf("[INFO] Instantiating GCE client...") c.clientCompute, err = compute.New(client) if err != nil { return err } c.clientCompute.UserAgent = userAgent log.Printf("[INFO] Instantiating GKE client...") c.clientContainer, err = container.New(client) if err != nil { return err } c.clientContainer.UserAgent = userAgent log.Printf("[INFO] Instantiating Google Cloud DNS client...") c.clientDns, err = dns.New(client) if err != nil { return err } c.clientDns.UserAgent = userAgent log.Printf("[INFO] Instantiating Google Storage Client...") c.clientStorage, err = storage.New(client) if err != nil { return err } c.clientStorage.UserAgent = userAgent log.Printf("[INFO] Instantiating Google SqlAdmin Client...") c.clientSqlAdmin, err = sqladmin.New(client) if err != nil { return err } c.clientSqlAdmin.UserAgent = userAgent log.Printf("[INFO] Instatiating Google Pubsub Client...") c.clientPubsub, err = pubsub.New(client) if err != nil { return err } c.clientPubsub.UserAgent = userAgent return nil }
func (p *Provisioner) deployConfigFiles( o terraform.UIOutput, comm communicator.Communicator, confDir string) error { contents, _, err := pathorcontents.Read(p.ValidationKey) if err != nil { return err } f := strings.NewReader(contents) // Copy the validation key to the new instance if err := comm.Upload(path.Join(confDir, validationKey), f); err != nil { return fmt.Errorf("Uploading %s failed: %v", validationKey, err) } if p.SecretKey != "" { contents, _, err := pathorcontents.Read(p.SecretKey) if err != nil { return err } s := strings.NewReader(contents) // Copy the secret key to the new instance if err := comm.Upload(path.Join(confDir, secretKey), s); err != nil { return fmt.Errorf("Uploading %s failed: %v", secretKey, err) } } // Make strings.Join available for use within the template funcMap := template.FuncMap{ "join": strings.Join, } // Create a new template and parse the client config into it t := template.Must(template.New(clienrb).Funcs(funcMap).Parse(clientConf)) var buf bytes.Buffer err = t.Execute(&buf, p) if err != nil { return fmt.Errorf("Error executing %s template: %s", clienrb, err) } // Copy the client config to the new instance if err := comm.Upload(path.Join(confDir, clienrb), &buf); err != nil { return fmt.Errorf("Uploading %s failed: %v", clienrb, err) } // Create a map with first boot settings fb := make(map[string]interface{}) if p.Attributes != nil { fb = p.Attributes.(map[string]interface{}) } // Check if the run_list was also in the attributes and if so log a warning // that it will be overwritten with the value of the run_list argument. if _, found := fb["run_list"]; found { log.Printf("[WARNING] Found a 'run_list' specified in the configured attributes! " + "This value will be overwritten by the value of the `run_list` argument!") } // Add the initial runlist to the first boot settings if !p.UsePolicyfile { fb["run_list"] = p.RunList } // Marshal the first boot settings to JSON d, err := json.Marshal(fb) if err != nil { return fmt.Errorf("Failed to create %s data: %s", firstBoot, err) } // Copy the first-boot.json to the new instance if err := comm.Upload(path.Join(confDir, firstBoot), bytes.NewReader(d)); err != nil { return fmt.Errorf("Uploading %s failed: %v", firstBoot, err) } return nil }