github.com/coreos/mantle@v0.13.0/auth/openstack.go (about)

     1  // Copyright 2018 Red Hat
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package auth
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  	"os"
    21  	"os/user"
    22  	"path/filepath"
    23  )
    24  
    25  const OpenStackConfigPath = ".config/openstack.json"
    26  
    27  type OpenStackProfile struct {
    28  	AuthURL    string `json:"auth_url"`
    29  	TenantID   string `json:"tenant_id"`
    30  	TenantName string `json:"tenant_name"`
    31  	Username   string `json:"username"`
    32  	Password   string `json:"password"`
    33  
    34  	//Optional
    35  	Domain         string `json:"user_domain"`
    36  	FloatingIPPool string `json:"floating_ip_pool"`
    37  	Region         string `json:"region_name"`
    38  }
    39  
    40  // ReadOpenStackConfig decodes an OpenStack config file,
    41  // which is a custom format used by Mantle to hold OpenStack
    42  // server information.
    43  //
    44  // If path is empty, $HOME/.config/openstack.json is read.
    45  func ReadOpenStackConfig(path string) (map[string]OpenStackProfile, error) {
    46  	if path == "" {
    47  		user, err := user.Current()
    48  		if err != nil {
    49  			return nil, err
    50  		}
    51  		path = filepath.Join(user.HomeDir, OpenStackConfigPath)
    52  	}
    53  
    54  	f, err := os.Open(path)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	defer f.Close()
    59  
    60  	var profiles map[string]OpenStackProfile
    61  	if err := json.NewDecoder(f).Decode(&profiles); err != nil {
    62  		return nil, err
    63  	}
    64  	if len(profiles) == 0 {
    65  		return nil, fmt.Errorf("OpenStack config %q contains no profiles", path)
    66  	}
    67  
    68  	return profiles, nil
    69  }