github.com/mwhudson/juju@v0.0.0-20160512215208-90ff01f3497f/jujuclient/credentials.go (about)

     1  // Copyright 2016 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package jujuclient
     5  
     6  import (
     7  	"io/ioutil"
     8  	"os"
     9  
    10  	"github.com/juju/errors"
    11  	"github.com/juju/utils"
    12  	"gopkg.in/yaml.v2"
    13  
    14  	"github.com/juju/juju/cloud"
    15  	"github.com/juju/juju/juju/osenv"
    16  )
    17  
    18  // JujuCredentialsPath is the location where controllers information is
    19  // expected to be found.
    20  func JujuCredentialsPath() string {
    21  	return osenv.JujuXDGDataHomePath("credentials.yaml")
    22  }
    23  
    24  // ReadCredentialsFile loads all credentials defined in a given file.
    25  // If the file is not found, it is not an error.
    26  func ReadCredentialsFile(file string) (map[string]cloud.CloudCredential, error) {
    27  	data, err := ioutil.ReadFile(file)
    28  	if err != nil {
    29  		if os.IsNotExist(err) {
    30  			return nil, nil
    31  		}
    32  		return nil, err
    33  	}
    34  	credentials, err := cloud.ParseCredentials(data)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  	return credentials, nil
    39  }
    40  
    41  // WriteCredentialsFile marshals to YAML details of the given credentials
    42  // and writes it to the credentials file.
    43  func WriteCredentialsFile(credentials map[string]cloud.CloudCredential) error {
    44  	data, err := yaml.Marshal(credentialsCollection{credentials})
    45  	if err != nil {
    46  		return errors.Annotate(err, "cannot marshal yaml credentials")
    47  	}
    48  	return utils.AtomicWriteFile(JujuCredentialsPath(), data, os.FileMode(0600))
    49  }
    50  
    51  // credentialsCollection is a struct containing cloud credential information,
    52  // used marshalling and unmarshalling.
    53  type credentialsCollection struct {
    54  	// Credentials is a map of cloud credentials, keyed on cloud name.
    55  	Credentials map[string]cloud.CloudCredential `yaml:"credentials"`
    56  }