diff --git a/.Makefile.swp b/.Makefile.swp new file mode 100644 index 0000000..5ee136a Binary files /dev/null and b/.Makefile.swp differ diff --git a/.travis.yml b/.travis.yml index a88d595..e3bfae0 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,10 @@ env: global: - secure: "roiMALXQRkKKlPP+cbtac795XeHHnPrKvc6M8HjVa5gzL1SZXHDn/zvcvTc//AAMBFxZXb9+V+USrU3vNyzULIoh5j7nTOutPtik4WYLIfwADVgSxpiEG9jDBYp3DLlXMAMb5uJWRuG4DSSxpUGPFujQr9+aaUa0Lz6tsPUpE2/yaQfR5GmrAVteevkEZ0h18BxiRKsf4cRIGEQpwOSAQ+x66MlaEAn/kkprS4K9imniHeDRnz4TM75SAI7VZh9Fglv6gf8HTZ73EV1sGzsbG8+k1eO53UxMYR7YneB86ihKjRFuXSXzT8K0RdoACY6Muf81kwP5JUP3SLMaNgRTrdGmzOZ+yhJzfuey0b7i2llvGHrfKCmEIUzTYC5KZgvwblqwU97u55baJpAwQJgwPOKBO2RUvyzdK00t39kj+PpGrmyrW9evQ7mGk7o7txn4K1LJfCTn/fll1Y3B1poyiflYfQ4vlj7RgKSwAgIs36+yPhYF/m1K9I+jy8BRHPCZek3JJIMnKaW3OEBzpCRBoxxmMFomN8tq2Ygde5TUVxukAbZNIrlaPPWB5ZB6ZQ1hKol0yddkqOKxivGPQJaZthlt7eHpx4rAG+ZY1e706pG3iqYcTEVJTjPPzCaKdSpbFg3oKGet3ClimF0ycNpJRFQs2eveI3AkhVCN2Z4IWX8=" #Github -install: make config-install get-deps +install: + - 'mkdir -p $HOME/.config/perun' + - 'cp defaults/main.yaml $HOME/.config/perun/main.yaml' + - make get-deps script: - make code-analysis diff --git a/Makefile b/Makefile index a82a036..8317274 100644 --- a/Makefile +++ b/Makefile @@ -1,15 +1,7 @@ -.PHONY: config-install get-deps code-analysis test all +.PHONY: get-deps code-analysis test all all: get-deps code-analysis test -config-install: - mkdir -p "$(HOME)/.config/perun/stack-policies" - cp defaults/main.yaml "$(HOME)/.config/perun/main.yaml" - cp defaults/style.yaml "$(HOME)/.config/perun/style.yaml" - cp defaults/specification_inconsistency.yaml "$(HOME)/.config/perun/specification_inconsistency.yaml" - cp defaults/blocked.json "$(HOME)/.config/perun/stack-policies/blocked.json" - cp defaults/unblocked.json "$(HOME)/.config/perun/stack-policies/unblocked.json" - get-deps: go get -t -v ./... go install ./... diff --git a/checkingrequiredfiles/checkingrequiredfiles.go b/checkingrequiredfiles/checkingrequiredfiles.go new file mode 100644 index 0000000..8e6cefe --- /dev/null +++ b/checkingrequiredfiles/checkingrequiredfiles.go @@ -0,0 +1,275 @@ +package checkingrequiredfiles + +import ( + "bufio" + "github.com/Appliscale/perun/configurator" + "github.com/Appliscale/perun/context" + "github.com/Appliscale/perun/helpers" + "github.com/Appliscale/perun/logger" + "github.com/Appliscale/perun/myuser" + "github.com/go-ini/ini" + "io" + "net/http" + "os" + "strings" +) + +//CheckingRequiredFiles looks for required and default files and if doesn't find will create these. +func CheckingRequiredFiles(ctx *context.Context) { + myLogger := logger.CreateDefaultLogger() + + mainYAMLexists, mainError := isMainYAMLPresent(&myLogger) + if mainError != nil { + myLogger.Error(mainError.Error()) + } + + configAWSExists, configError := isAWSConfigPresent(&myLogger) + if configError != nil { + myLogger.Error(configError.Error()) + } + + credentialsExists, credentialsError := isCredentialsPresent(&myLogger) + if credentialsError != nil { + myLogger.Error(credentialsError.Error()) + } + + homePath, pathError := myuser.GetUserHomeDir() + if pathError != nil { + myLogger.Error(pathError.Error()) + } + + profile := "default" + region := "us-east-1" + + if !mainYAMLexists { + if configAWSExists { + profile, *ctx = configIsPresent(profile, homePath, ctx, myLogger) + if !credentialsExists { + createCredentials(profile, homePath, ctx, &myLogger) + } + + } else { //configAWSExists == false + var answer string + myLogger.GetInput("Config doesn't exist, create default *Y* or new *N*?", &answer) + if strings.ToUpper(answer) == "N" { + profile, region, *ctx = newConfigFile(profile, region, homePath, ctx, &myLogger) + addProfileToCredentials(profile, homePath, ctx, &myLogger) + addNewProfileFromCredentialsToConfig(profile, homePath, ctx, &myLogger) + + } else if strings.ToUpper(answer) == "Y" { + configurator.CreateAWSConfigFile(ctx, profile, region) + *ctx = createNewMainYaml(profile, homePath, ctx, &myLogger) + configurator.CreateAWSCredentialsFile(ctx, profile) + } + + if credentialsExists { + createCredentials(profile, homePath, ctx, &myLogger) + } + } + } else { //mainYAMLexists == true + if configAWSExists { + if !credentialsExists { + myLogger.Always("Profile from main.yaml: " + ctx.Config.DefaultProfile) + configurator.CreateAWSCredentialsFile(ctx, ctx.Config.DefaultProfile) + } else { + isProfileInPresent := isProfileInCredentials(ctx.Config.DefaultProfile, homePath+"/.aws/credentials", &myLogger) + if !isProfileInPresent { + myLogger.Always("Profile from main.yaml: " + ctx.Config.DefaultProfile) + configurator.CreateAWSCredentialsFile(ctx, ctx.Config.DefaultProfile) + } + } + } else { //configAWSExists ==false + var answer string + myLogger.GetInput("Config doesn't exist, create default - "+ctx.Config.DefaultProfile+" *Y* or new *N*?", &answer) + if strings.ToUpper(answer) == "Y" { + configurator.CreateAWSConfigFile(ctx, ctx.Config.DefaultProfile, ctx.Config.DefaultRegion) + } else if strings.ToUpper(answer) == "N" { + profile, region, *ctx = newConfigFile(profile, region, homePath, ctx, &myLogger) + addProfileToCredentials(profile, homePath, ctx, &myLogger) + } + addNewProfileFromCredentialsToConfig(ctx.Config.DefaultProfile, homePath, ctx, &myLogger) + + if credentialsExists { + createCredentials(ctx.Config.DefaultProfile, homePath, ctx, &myLogger) + + } + } + } + downloadError := downloadDefaultFiles() + if downloadError != nil { + myLogger.Error(downloadError.Error()) + } +} + +// Looking for main.yaml. +func isMainYAMLPresent(myLogger *logger.Logger) (bool, error) { + homePath, pathError := myuser.GetUserHomeDir() + if pathError != nil { + myLogger.Error(pathError.Error()) + return false, pathError + } + _, mainError := os.Open(homePath + "/.config/perun/main.yaml") + if mainError != nil { + _, mainError = os.Open(homePath + "/etc/perun/main.yaml") + if mainError != nil { + return false, pathError + } + return true, pathError + } + return true, pathError +} + +// Looking for .aws.config. +func isAWSConfigPresent(myLogger *logger.Logger) (bool, error) { + homePath, pathError := myuser.GetUserHomeDir() + if pathError != nil { + myLogger.Error(pathError.Error()) + return false, pathError + } + _, credentialsError := os.Open(homePath + "/.aws/config") + if credentialsError != nil { + return false, credentialsError + } + return true, nil + +} + +// Looking for .aws/credentials. +func isCredentialsPresent(myLogger *logger.Logger) (bool, error) { + homePath, pathError := myuser.GetUserHomeDir() + if pathError != nil { + myLogger.Error(pathError.Error()) + return false, pathError + } + _, credentialsError := os.Open(homePath + "/.aws/credentials") + if credentialsError != nil { + return false, credentialsError + } + return true, nil +} + +// Looking for [profiles] in credentials or config and return all. +func getProfilesFromFile(path string, mylogger *logger.Logger) []string { + credentials, credentialsError := os.Open(path) + if credentialsError != nil { + mylogger.Error(credentialsError.Error()) + return []string{} + } + defer credentials.Close() + profiles := make([]string, 0) + scanner := bufio.NewScanner(credentials) + for scanner.Scan() { + if strings.Contains(scanner.Text(), "[") { + profile := strings.TrimPrefix(scanner.Text(), "[") + profile = strings.TrimSuffix(profile, "]") + if strings.Contains(profile, "profile ") { + profile = strings.TrimPrefix(profile, "profile ") + } + if strings.Contains(profile, "-long-term") { + profile = strings.TrimSuffix(profile, "-long-term") + } + profiles = append(profiles, profile) + } + } + return profiles +} + +// Looking for user's profile in credentials or config. +func isProfileInCredentials(profile string, path string, mylogger *logger.Logger) bool { + credentials, credentialsError := os.Open(path) + if credentialsError != nil { + mylogger.Error(credentialsError.Error()) + } + defer credentials.Close() + scanner := bufio.NewScanner(credentials) + for scanner.Scan() { + if strings.Contains(scanner.Text(), "["+profile+"]") || strings.Contains(scanner.Text(), "["+profile+"-long-term]") { + return true + } + } + return false + +} + +// Looking for region for profile. +func findRegionForProfile(profile string, path string, mylogger *logger.Logger) string { + configuration, loadError := ini.Load(path) + if loadError != nil { + mylogger.Error(loadError.Error()) + } + section, sectionError := configuration.GetSection(profile) + if sectionError != nil { + section, sectionError = configuration.GetSection("profile " + profile) + if sectionError != nil { + mylogger.Error(sectionError.Error()) + return "" + } + } + region := section.Key("region").Value() + return region + +} + +// Getting profiles from credentials and config, if credentials has new profile, add to config. +func findNewProfileInCredentials(credentials []string, config []string) []string { + profiles := make([]string, 0) + for i, cred := range credentials { + if strings.Contains(cred, "-long-term") { + cred = strings.TrimSuffix(cred, "-long-term") + credentials[i] = cred + } + } + for _, cred := range credentials { + isProfileHere := helpers.SliceContains(config, cred) + if !isProfileHere { + profiles = append(profiles, cred) + return profiles + } + } + return []string{} +} + +// Downloading other files. +func downloadDefaultFiles() error { + urls := make(map[string]string) + urls["blocked.json"] = "https://s3.amazonaws.com/perun-default-file/blocked.json" + urls["unblocked.json"] = "https://s3.amazonaws.com/perun-default-file/unblocked.json" + urls["style.yaml"] = "https://s3.amazonaws.com/perun-default-file/style.yaml" + urls["specification_inconsistency.yaml"] = "https://s3.amazonaws.com/perun-default-file/specification_inconsistency.yaml" + + for file, url := range urls { + homePath, _ := myuser.GetUserHomeDir() + homePath += "/.config/perun/" + + if strings.Contains(file, "blocked") { + homePath += "stack-policies/" + } + + _, err := os.Stat(homePath) + if os.IsNotExist(err) { + os.Mkdir(homePath, 0755) + } + + _, openError := os.Open(homePath + file) //checking if file exists + if openError != nil { + out, creatingFileError := os.Create(homePath + file) + + if creatingFileError != nil { + return creatingFileError + } + defer out.Close() + + resp, httpGetError := http.Get(url) + if httpGetError != nil { + return httpGetError + } + defer resp.Body.Close() + + _, copyError := io.Copy(out, resp.Body) + if copyError != nil { + return copyError + } + } + } + return nil +} diff --git a/checkingrequiredfiles/creatingfiles.go b/checkingrequiredfiles/creatingfiles.go new file mode 100644 index 0000000..9e0fc8d --- /dev/null +++ b/checkingrequiredfiles/creatingfiles.go @@ -0,0 +1,107 @@ +package checkingrequiredfiles + +import ( + "github.com/Appliscale/perun/cliparser" + "github.com/Appliscale/perun/configuration" + "github.com/Appliscale/perun/configurator" + "github.com/Appliscale/perun/context" + "github.com/Appliscale/perun/helpers" + "github.com/Appliscale/perun/logger" + "strings" +) + +// Creating main.yaml. +func createNewMainYaml(profile string, homePath string, ctx *context.Context, myLogger *logger.Logger) context.Context { + region := findRegionForProfile(profile, homePath+"/.aws/config", myLogger) + con := configurator.CreateMainYaml(ctx, profile, region) + configuration.SaveToFile(con, homePath+"/.config/perun/main.yaml", myLogger) + *ctx, _ = context.GetContext(cliparser.ParseCliArguments, configuration.GetConfiguration, configuration.ReadInconsistencyConfiguration) + return *ctx +} + +// If config exists, use profile from .aws/config. +func useProfileFromConfig(profilesInConfig []string, profile string, myLogger *logger.Logger) string { + myLogger.Always("Available profiles from config:") + for _, prof := range profilesInConfig { + myLogger.Always(prof) + } + myLogger.GetInput("Which profile should perun use as a default?", &profile) + isUserProfile := helpers.SliceContains(profilesInConfig, profile) + for !isUserProfile { + myLogger.GetInput("I cannot find this profile, try again", &profile) + isUserProfile = helpers.SliceContains(profilesInConfig, profile) + } + return profile +} + +// If profile exists in .aws/credentials, but not in aws/config, add profile. +func addNewProfileFromCredentialsToConfig(profile string, homePath string, ctx *context.Context, myLogger *logger.Logger) { + profilesInCredentials := getProfilesFromFile(homePath+"/.aws/credentials", myLogger) + profilesInConfig := getProfilesFromFile(homePath+"/.aws/config", myLogger) + profiles := findNewProfileInCredentials(profilesInCredentials, profilesInConfig) + if len(profiles) > 0 { + for _, prof := range profiles { + var answer string + myLogger.GetInput("I found profile "+prof+" in credentials, but not in config. \nCreate new profile in config? Y/N", &answer) + if strings.ToUpper(answer) == "Y" { + var region string + myLogger.GetInput("Region", ®ion) + configurator.CreateAWSConfigFile(ctx, prof, region) + } + } + } +} + +// Checking if profile is in .aws/credentials. +func addProfileToCredentials(profile string, homePath string, ctx *context.Context, myLogger *logger.Logger) { + profilesInCredentials := getProfilesFromFile(homePath+"/.aws/credentials", myLogger) + temp := helpers.SliceContains(profilesInCredentials, profile) + if !temp { + configurator.CreateAWSCredentialsFile(ctx, profile) + } else { + myLogger.Always("Profile " + profile + " has already credentials") + } +} + +// Creating main.yaml based on .aws/config or in configure mode. +func configIsPresent(profile string, homePath string, ctx *context.Context, myLogger logger.Logger) (string, context.Context) { + profilesInConfig := getProfilesFromFile(homePath+"/.aws/config", &myLogger) + isDefaultProfile := helpers.SliceContains(profilesInConfig, profile) + if isDefaultProfile { + var answer string + myLogger.GetInput("Default profile exists, do you want to use it *Y* or create your own *N*?", &answer) + if strings.ToUpper(answer) == "Y" { + *ctx = createNewMainYaml(profile, homePath, ctx, &myLogger) + } else if strings.ToUpper(answer) == "N" { + configurator.CreateRequiredFilesInConfigureMode(ctx) + + } + } else { // isDefaultProfile == false + profile = useProfileFromConfig(profilesInConfig, profile, &myLogger) + *ctx = createNewMainYaml(profile, homePath, ctx, &myLogger) + } + + return profile, *ctx +} + +// Creating new .aws/config and main.yaml for profile. +func newConfigFile(profile string, region string, homePath string, ctx *context.Context, myLogger *logger.Logger) (string, string, context.Context) { + profile, region = configurator.GetRegionAndProfile(myLogger) + configurator.CreateAWSConfigFile(ctx, profile, region) + *ctx = createNewMainYaml(profile, homePath, ctx, myLogger) + return profile, region, *ctx +} + +// Creating credentials for all present profiles. +func createCredentials(profile string, homePath string, ctx *context.Context, myLogger *logger.Logger) { + isProfileInPresent := isProfileInCredentials(profile, homePath+"/.aws/credentials", myLogger) + + if !isProfileInPresent { + var answer string + myLogger.GetInput("I found profile "+profile+" in .aws/config without credentials, add? Y/N", &answer) + if strings.ToUpper(answer) == "Y" { + configurator.CreateAWSCredentialsFile(ctx, profile) + } + } + +} diff --git a/cliparser/cliparser.go b/cliparser/cliparser.go index 3923df4..79e5ccd 100644 --- a/cliparser/cliparser.go +++ b/cliparser/cliparser.go @@ -20,7 +20,6 @@ package cliparser import ( "errors" - "github.com/Appliscale/perun/logger" "github.com/Appliscale/perun/utilities" "gopkg.in/alecthomas/kingpin.v2" diff --git a/configuration/configuration.go b/configuration/configuration.go index 7b1f539..c39d938 100644 --- a/configuration/configuration.go +++ b/configuration/configuration.go @@ -132,11 +132,11 @@ func notifyUserAboutConfigurationFile(configurationFilePath string, logger *logg logger.Info("Configuration file from the following location will be used: " + configurationFilePath) } -func SaveToFile(config Configuration, path string, logger logger.Logger) { +func SaveToFile(config Configuration, path string, logger *logger.Logger) { file, err := os.Create(path) defer file.Close() if err != nil { - logger.Error("Could not create file") + logger.Error(err.Error()) return } obj, _ := yaml.Marshal(config) diff --git a/configurator/configurator.go b/configurator/configurator.go index a228920..2d7dec5 100644 --- a/configurator/configurator.go +++ b/configurator/configurator.go @@ -1,15 +1,17 @@ package configurator import ( - "os" - "strconv" - + "github.com/Appliscale/perun/cliparser" "github.com/Appliscale/perun/configuration" "github.com/Appliscale/perun/context" + "github.com/Appliscale/perun/logger" "github.com/Appliscale/perun/myuser" + "os" + "strconv" + "strings" ) -var resourceSpecificationURL = map[string]string{ +var ResourceSpecificationURL = map[string]string{ "us-east-2": "https://dnwj8swjjbsbt.cloudfront.net", "us-east-1": "https://d1uauaxba7bl26.cloudfront.net", "us-west-1": "https://d68hl49wbnanq.cloudfront.net", @@ -26,87 +28,113 @@ var resourceSpecificationURL = map[string]string{ "sa-east-1": "https://d3c9jyj3w509b0.cloudfront.net", } -func FileName(context *context.Context) { +// Creating main.yaml and .aws/credentials in configure mode. +func CreateRequiredFilesInConfigureMode(ctx *context.Context) { homePath, pathError := myuser.GetUserHomeDir() if pathError != nil { - context.Logger.Error(pathError.Error()) + ctx.Logger.Error(pathError.Error()) } + myLogger := logger.CreateDefaultLogger() homePath += "/.config/perun" - context.Logger.Always("Configure file could be in \n " + homePath + "\n /etc/perun") + ctx.Logger.Always("Configure file could be in \n " + homePath + "\n /etc/perun") var yourPath string var yourName string - context.Logger.GetInput("Your path", &yourPath) - context.Logger.GetInput("Filename", &yourName) - findFile(yourPath+"/"+yourName, context) + ctx.Logger.GetInput("Your path", &yourPath) + ctx.Logger.GetInput("Filename", &yourName) + myProfile, myRegion := GetRegionAndProfile(&myLogger) + createConfigurationFile(yourPath+"/"+yourName, ctx, myProfile, myRegion) + *ctx, _ = context.GetContext(cliparser.ParseCliArguments, configuration.GetConfiguration, configuration.ReadInconsistencyConfiguration) + var answer string + ctx.Logger.GetInput("Do you want to create .aws/credentials for this profile? Y/N", &answer) + if strings.ToUpper(answer) == "Y" { + CreateAWSCredentialsFile(ctx, myProfile) + } } -func findFile(path string, context *context.Context) { +// Creating main.yaml in user's path. +func createConfigurationFile(path string, context *context.Context, myProfile string, myRegion string) { context.Logger.Always("File will be created in " + path) _, err := os.Stat(path) if os.IsNotExist(err) { - showRegions(context) - con := createConfig(context) - configuration.SaveToFile(con, path, *context.Logger) + con := CreateMainYaml(context, myProfile, myRegion) + configuration.SaveToFile(con, path, context.Logger) } else { - context.Logger.Always("File already exists in this path") + var answer string + context.Logger.GetInput("File already exists in this path. Do you want to overwrite this file? Y/N", &answer) + if strings.ToUpper(answer) == "Y" { + con := CreateMainYaml(context, myProfile, myRegion) + configuration.SaveToFile(con, path, context.Logger) + + } } } -func showRegions(context *context.Context) { +//List of all available regions. +func showRegions(myLogger *logger.Logger) { regions := makeArrayRegions() - context.Logger.Always("Regions:") + myLogger.Always("Regions:") for i := 0; i < len(regions); i++ { pom := strconv.Itoa(i) - context.Logger.Always("Number " + pom + " region " + regions[i]) + myLogger.Always("Number " + pom + " region " + regions[i]) } } -func setRegions(context *context.Context) (region string, err bool) { +// Choosing one region. +func setRegions(myLogger *logger.Logger) (region string, err bool) { var numberRegion int - context.Logger.GetInput("Choose region", &numberRegion) + myLogger.GetInput("Choose region", &numberRegion) regions := makeArrayRegions() if numberRegion >= 0 && numberRegion < 14 { region = regions[numberRegion] - context.Logger.Always("Your region is: " + region) + myLogger.Always("Your region is: " + region) err = true } else { - context.Logger.Error("Invalid region") + myLogger.Error("Invalid region") err = false } return } -func setProfile(context *context.Context) (profile string, err bool) { - context.Logger.GetInput("Input name of profile", &profile) +// Choosing one profile. +func setProfile(myLogger *logger.Logger) (profile string, err bool) { + myLogger.GetInput("Input name of profile", &profile) if profile != "" { - context.Logger.Always("Your profile is: " + profile) + myLogger.Always("Your profile is: " + profile) err = true } else { - context.Logger.Error("Invalid profile") + myLogger.Error("Invalid profile") err = false } return } +// Get region and profile from user. +func GetRegionAndProfile(myLogger *logger.Logger) (string, string) { + profile, err := setProfile(myLogger) + for !err { + myLogger.Always("Try again, invalid profile") + profile, err = setProfile(myLogger) + } + showRegions(myLogger) + region, err1 := setRegions(myLogger) + for !err1 { + myLogger.Always("Try again, invalid region") + region, err1 = setRegions(myLogger) + } + return profile, region +} + +// Setting directory for temporary files. func setTemporaryFilesDirectory(context *context.Context) (path string) { context.Logger.GetInput("Directory for temporary files", &path) context.Logger.Always("Your temporary files directory is: " + path) return path } -func createConfig(context *context.Context) configuration.Configuration { - myRegion, err := setRegions(context) - for !err { - context.Logger.Always("Try again, invalid region") - myRegion, err = setRegions(context) - } - myProfile, err1 := setProfile(context) - for !err1 { - context.Logger.Always("Try again, invalid profile") - myProfile, err1 = setProfile(context) - } +// Creating main.yaml +func CreateMainYaml(context *context.Context, myProfile string, myRegion string) configuration.Configuration { myTemporaryFilesDirectory := setTemporaryFilesDirectory(context) - myResourceSpecificationURL := resourceSpecificationURL + myResourceSpecificationURL := ResourceSpecificationURL myConfig := configuration.Configuration{ DefaultProfile: myProfile, @@ -121,22 +149,82 @@ func createConfig(context *context.Context) configuration.Configuration { return myConfig } -func makeArrayRegions() [14]string { - var regions [14]string - regions[0] = "us-east-1" - regions[1] = "us-east-2" - regions[2] = "us-west-1" - regions[3] = "us-west-2" - regions[4] = "ca-central-1" - regions[5] = "ca-central-1" - regions[6] = "eu-west-1" - regions[7] = "eu-west-2" - regions[8] = "ap-northeast-1" - regions[9] = "ap-northeast-2" - regions[10] = "ap-southeast-1" - regions[11] = "ap-southeast-2" - regions[12] = "ap-south-1" - regions[13] = "sa-east-1" - +// Array of regions. +func makeArrayRegions() []string { + var regions = []string{ + "us-east-1", + "us-east-2", + "us-west-1", + "us-west-2", + "ca-central-1", + "ca-central-1", + "eu-west-1", + "eu-west-2", + "ap-northeast-1", + "ap-northeast-2", + "ap-southeast-1", + "ap-southeast-2", + "ap-south-1", + "sa-east-1", + } return regions } + +// Creating .aws/credentials file. +func CreateAWSCredentialsFile(ctx *context.Context, profile string) { + if profile != "" { + ctx.Logger.Always("You haven't got .aws/credentials file for profile " + profile) + var awsAccessKeyID string + var awsSecretAccessKey string + var mfaSerial string + + ctx.Logger.GetInput("awsAccessKeyID", &awsAccessKeyID) + ctx.Logger.GetInput("awsSecretAccessKey", &awsSecretAccessKey) + ctx.Logger.GetInput("mfaSerial", &mfaSerial) + + homePath, pathError := myuser.GetUserHomeDir() + if pathError != nil { + ctx.Logger.Error(pathError.Error()) + } + path := homePath + "/.aws/credentials" + line := "[" + profile + "-long-term" + "]\n" + appendStringToFile(path, line) + line = "aws_access_key_id" + " = " + awsAccessKeyID + "\n" + appendStringToFile(path, line) + line = "aws_secret_access_key" + " = " + awsSecretAccessKey + "\n" + appendStringToFile(path, line) + line = "mfa_serial" + " = " + mfaSerial + "\n" + appendStringToFile(path, line) + } +} + +// Creating .aws/config file. +func CreateAWSConfigFile(ctx *context.Context, profile string, region string) { + var output string + ctx.Logger.GetInput("Output", &output) + homePath, pathError := myuser.GetUserHomeDir() + if pathError != nil { + ctx.Logger.Error(pathError.Error()) + } + path := homePath + "/.aws/config" + line := "[" + profile + "]\n" + appendStringToFile(path, line) + line = "region" + " = " + region + "\n" + appendStringToFile(path, line) + line = "output" + " = " + output + "\n" + appendStringToFile(path, line) +} + +func appendStringToFile(path, text string) error { + f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + return err + } + defer f.Close() + + _, err = f.WriteString(text) + if err != nil { + return err + } + return nil +} diff --git a/configurator/configurator_test.go b/configurator/configurator_test.go index 7d9b12f..b2bf0ad 100644 --- a/configurator/configurator_test.go +++ b/configurator/configurator_test.go @@ -30,7 +30,7 @@ func TestCreateConfig(t *testing.T) { myconfig := configuration.Configuration{ DefaultProfile: "profile", DefaultRegion: "region", - SpecificationURL: resourceSpecificationURL, + SpecificationURL: ResourceSpecificationURL, DefaultDecisionForMFA: false, DefaultDurationForMFA: 3600, DefaultVerbosity: "INFO"} diff --git a/context/mysession.go b/context/mysession.go index a3392e5..3785f04 100644 --- a/context/mysession.go +++ b/context/mysession.go @@ -2,11 +2,11 @@ package context import ( "errors" + "github.com/Appliscale/perun/cliparser" "os" "os/user" "time" - "github.com/Appliscale/perun/cliparser" "github.com/Appliscale/perun/utilities" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" diff --git a/defaults/main.yaml b/defaults/main.yaml index 80ddea0..697fc46 100644 --- a/defaults/main.yaml +++ b/defaults/main.yaml @@ -1,7 +1,7 @@ DefaultProfile: default DefaultRegion: us-east-1 DefaultDurationForMFA: 3600 -DefaultDecisionForMFA: true +DefaultDecisionForMFA: false DefaultVerbosity: INFO DefaultTemporaryFilesDirectory: SpecificationURL: diff --git a/main.go b/main.go index d785df1..02cfcd1 100644 --- a/main.go +++ b/main.go @@ -18,6 +18,7 @@ package main import ( + "github.com/Appliscale/perun/checkingrequiredfiles" "os" "github.com/Appliscale/perun/cliparser" @@ -34,9 +35,7 @@ import ( func main() { ctx, err := context.GetContext(cliparser.ParseCliArguments, configuration.GetConfiguration, configuration.ReadInconsistencyConfiguration) - if err != nil { - os.Exit(1) - } + checkingrequiredfiles.CheckingRequiredFiles(&ctx) if ctx.CliArguments.Lint != nil && *ctx.CliArguments.Lint { err = linter.CheckStyle(&ctx) @@ -51,7 +50,7 @@ func main() { } if *ctx.CliArguments.Mode == cliparser.ConfigureMode { - configurator.FileName(&ctx) + configurator.CreateRequiredFilesInConfigureMode(&ctx) os.Exit(0) }