github.com/GoogleCloudPlatform/terraformer@v0.8.18/providers/alicloud/alicloud_service.go (about)

     1  // Copyright 2018 The Terraformer Authors.
     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 alicloud
    16  
    17  import (
    18  	"encoding/json"
    19  	"fmt"
    20  	"io/ioutil"
    21  	"os"
    22  	"runtime"
    23  
    24  	"github.com/GoogleCloudPlatform/terraformer/providers/alicloud/connectivity"
    25  	"github.com/GoogleCloudPlatform/terraformer/terraformutils"
    26  )
    27  
    28  // AliCloudService Service struct for AliCloud
    29  type AliCloudService struct { //nolint
    30  	terraformutils.Service
    31  }
    32  
    33  // ConfigFile go struct for ~/.aliyun/config.json
    34  type ConfigFile struct {
    35  	Current  string `json:"current"`
    36  	MetaPath string `json:"meta_path"`
    37  	Profiles []struct {
    38  		AccessKeyID     string `json:"access_key_id"`
    39  		AccessKeySecret string `json:"access_key_secret"`
    40  		ExpiredSeconds  int    `json:"expired_seconds"`
    41  		KeyPairName     string `json:"key_pair_name"`
    42  		Language        string `json:"language"`
    43  		Mode            string `json:"mode"`
    44  		Name            string `json:"name"`
    45  		OutputFormat    string `json:"output_format"`
    46  		PrivateKey      string `json:"private_key"`
    47  		RAMRoleArn      string `json:"ram_role_arn"`
    48  		RAMRoleName     string `json:"ram_role_name"`
    49  		RAMSessionName  string `json:"ram_session_name"`
    50  		RegionID        string `json:"region_id"`
    51  		RetryCount      int    `json:"retry_count"`
    52  		RetryTimeout    int    `json:"retry_timeout"`
    53  		Site            string `json:"site"`
    54  		StsToken        string `json:"sts_token"`
    55  		Verified        string `json:"verified"`
    56  	} `json:"profiles"`
    57  }
    58  
    59  // LoadClientFromProfile Loads profile from ~/.aliyun/config.json and then applies the region from cmd line
    60  func (s *AliCloudService) LoadClientFromProfile() (*connectivity.AliyunClient, error) {
    61  	args := s.GetArgs()
    62  	region := args["region"].(string)
    63  	profileName := args["profile"].(string)
    64  
    65  	config, err := LoadConfigFromProfile(profileName)
    66  	if err != nil {
    67  		return nil, err
    68  	}
    69  
    70  	config.RegionID = region
    71  	config.Region = connectivity.Region(config.RegionID)
    72  
    73  	return config.Client()
    74  }
    75  
    76  // LoadConfigFromProfile Loads profile from ~/.aliyun/config.json
    77  func LoadConfigFromProfile(profileName string) (*connectivity.Config, error) {
    78  	// Set the path depending on OS from where to pull the config.json
    79  	profilePath := ""
    80  	if runtime.GOOS == "windows" {
    81  		profilePath = fmt.Sprintf("%s/.aliyun/config.json", os.Getenv("USERPROFILE"))
    82  	} else {
    83  		profilePath = fmt.Sprintf("%s/.aliyun/config.json", os.Getenv("HOME"))
    84  	}
    85  
    86  	// Make sure the profile exists
    87  	_, err := os.Stat(profilePath)
    88  	if os.IsNotExist(err) {
    89  		return nil, err
    90  	}
    91  
    92  	// Try to parse JSON
    93  	data, err := ioutil.ReadFile(profilePath)
    94  	if err != nil {
    95  		return nil, err
    96  	}
    97  	var configFile ConfigFile
    98  	err = json.Unmarshal(data, &configFile)
    99  	if err != nil {
   100  		return nil, err
   101  	}
   102  
   103  	// If profile argument is missing then use the config file
   104  	currentProfile := profileName
   105  	if currentProfile == "" {
   106  		currentProfile = configFile.Current
   107  	}
   108  
   109  	// Default to loading the first profile
   110  	config := configFile.Profiles[0]
   111  
   112  	// Set profile as current profile
   113  	found := false
   114  	for _, profile := range configFile.Profiles {
   115  		if currentProfile == profile.Name {
   116  			config = profile
   117  			found = true
   118  		}
   119  	}
   120  
   121  	if !found {
   122  		fmt.Printf("ERROR: Profile %s not found. Using profile %s\n", profileName, config.Name)
   123  	}
   124  
   125  	conf := connectivity.Config{
   126  		AccessKey:          config.AccessKeyID,
   127  		SecretKey:          config.AccessKeySecret,
   128  		EcsRoleName:        config.Name,
   129  		Region:             connectivity.Region(config.RegionID),
   130  		RegionID:           config.RegionID,
   131  		SecurityToken:      config.StsToken,
   132  		RAMRoleArn:         config.RAMRoleArn,
   133  		RAMRoleSessionName: config.RAMSessionName,
   134  		// OtsInstanceName:    "", // TODO: Figure out what to do with this
   135  		// AccountId:          "", // TODO: Figure out what to do with this
   136  		// RamRolePolicy:      "", // TODO: Figure out what to do with this
   137  	}
   138  
   139  	return &conf, nil
   140  }