Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Call sso login if we get an error #445

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions .cspell.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"ignoreWords": [
"abspath",
"aprofile",
"awsutil",
"blang",
"bsdtar",
"buildkit",
"buildtag",
"chdir",
"chmod",
"coveo",
"coveooss",
"ctype",
"darwin",
"debugf",
"debugln",
"dockerbuild",
"envars",
"erra",
"errorln",
"fatih",
"github",
"globaldelay",
"gohcl",
"gotemplate",
"hashicorp",
"hclparse",
"hoburg",
"inconshreveable",
"infof",
"infoln",
"ldflags",
"linux",
"logrus",
"matryer",
"minio",
"moby",
"multilogger",
"oldpwd",
"openssl",
"reutils",
"rontend",
"selfupdate",
"semver's",
"sirupsen",
"somevalue",
"ssologin",
"stretchr",
"stscreds",
"terraforming",
"terragrunt",
"tflint",
"tfpath",
"tmpdir",
"truef",
"unmanaged",
"warningf",
"zclconf"
],
"language": "en,en-US,en-GB",
}
1 change: 0 additions & 1 deletion .github/workflows/pr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ name: PR
on:
pull_request:
branches:
- master
- main

jobs:
Expand Down
1 change: 0 additions & 1 deletion .github/workflows/test-install.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ name: Test Install
on:
pull_request:
branches:
- master
- main

jobs:
Expand Down
5 changes: 0 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@ SOURCES = $(wildcard **/*.go)
install:
go install

coveralls:
wget https://raw.githubusercontent.com/coveo/terragrunt/master/scripts/coverage.sh
@sh ./coverage.sh --coveralls
rm coverage.sh

.PHONY: test
test:
go test ./...
Expand Down
171 changes: 85 additions & 86 deletions README.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion aws_logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ func (log *AwsLogger) Logf(classification logging.Classification, format string,
case logging.Debug:
log.Debugf(format, v...)
case logging.Warn:
log.Warnf(format, v...)
log.Warningf(format, v...)
}
}
34 changes: 21 additions & 13 deletions cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ import (

"github.com/coveooss/gotemplate/v3/hcl"
"github.com/coveooss/gotemplate/v3/template"
"github.com/coveooss/kingpin/v2"
"github.com/coveooss/multilogger/errors"
"github.com/coveord/kingpin/v2"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
)

const description = `@color("underline", "DESCRIPTION:")
const description = `
@color("underline", "DESCRIPTION:")

TGF (@terragrunt) is a Docker frontend for terragrunt/terraform. It automatically maps your current folder,
your HOME folder, your TEMP folder as well of most environment variables to the docker process. You can add -D to
your command to get the exact docker command that is generated.
Expand All @@ -28,6 +30,7 @@ Configurable values are:
- @autoIndent(options)

Full documentation can be found at @(readme)

Check for new version at @(latest).

Any docker image could be used, but TGF specialized images could be found at: @(tgfImages).
Expand All @@ -36,21 +39,16 @@ Terragrunt documentation could be found at @terragruntCoveo (Coveo fork)

Terraform documentation could be found at @(terraform).

@color("underline", "ENVIRONMENT VARIABLES:")
Most of the arguments can be set through environment variables using the format TGF_ARG_NAME.

Ex:
TGF_LOCAL_IMAGE=1 ==> --local-image
TGF_IMAGE_VERSION=2.0 ==> --image-version=2.0

@color("underline", "SHORTCUTS:")

You can also use shortcuts instead of using the long argument names (first letter of each word).

Ex:
--li ==> --local-image
--iv=2.0 ==> --image-version=2.0

@color("underline", "IMPORTANT:")

Most of the tgf command line arguments are in uppercase to avoid potential conflict with the underlying command.
If any of the tgf arguments conflicts with an argument of the desired entry point, you must place that argument
after -- to ensure that they are not interpreted by tgf and are passed to the entry point. Any non conflicting
Expand Down Expand Up @@ -128,7 +126,7 @@ func NewTGFApplication(args []string) *TGFApplication {
var tempLocationIsSetByUser bool
app := TGFApplication{Application: base}
swFlagON := func(name, description string) *kingpin.FlagClause {
return app.Flag(name, fmt.Sprintf("ON by default: %s, use --no-%s to disable", description, name)).Default(true)
return app.Flag(name, fmt.Sprintf("ON by default: %s", description)).Default(true)
}
app.Flag("help-tgf", "Show context-sensitive help (also try --help-man)").Short('H').Action(app.ShowHelp).Bool()
app.Flag("image", "Use the specified image instead of the default one").PlaceHolder("coveo/tgf").NoAutoShortcut().StringVar(&app.Image)
Expand Down Expand Up @@ -173,6 +171,7 @@ func NewTGFApplication(args []string) *TGFApplication {
kingpin.HelpFlag = app.GetFlag("help-tgf")

_, _ = app.Parse(args)

if *debug {
_ = log.SetDefaultConsoleHookLevel(logrus.DebugLevel)
}
Expand Down Expand Up @@ -217,9 +216,9 @@ func formatDescription() string {
"parameterStoreKey": defaultSSMParameterFolder,
"config": configFile,
"options": getTgfConfigFields(),
"readme": link(gitSource + "/blob/master/README.md"),
"readme": link(gitSource + "/blob/main/README.md"),
"latest": link(gitSource + "/releases/latest"),
"terragruntCoveo": link("https://github.com/coveo/terragrunt/blob/master/README.md"),
"terragruntCoveo": link("https://github.com/coveooss/terragrunt/blob/main/README.md"),
"terraform": link("https://www.terraform.io/docs/index.html"),
"tgfImages": link("https://hub.docker.com/r/coveo/tgf/tags"),
"terragrunt": bold("t") + "erra" + bold("g") + "runt " + bold("f") + "rontend",
Expand All @@ -230,7 +229,7 @@ func formatDescription() string {
options := template.DefaultOptions()
options[template.Extension] = false
t, _ := template.NewTemplate("", context, "", options)
return must(t.ProcessContent(description, "")).(string)
return strings.TrimSpace(must(t.ProcessContent(description, "")).(string))
}

// Parse overrides the base Parse method
Expand Down Expand Up @@ -274,5 +273,14 @@ func (app *TGFApplication) ShowHelp(c *kingpin.ParseContext) error {

// Run execute the application
func (app *TGFApplication) Run() int {
if app.GetCurrentVersion && !app.AutoUpdateSet {
if version == locallyBuilt {
fmt.Println("tgf (built from source)")
} else {
fmt.Printf("tgf v%s\n", version)
}
return 0
}

return RunWithUpdateCheck(InitConfig(app))
}
37 changes: 29 additions & 8 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
Expand Down Expand Up @@ -200,7 +199,29 @@ func (tgfConfig *TGFConfig) getAwsConfig(assumeRoleDuration time.Duration) (aws.
log.Debug("Fetching credentials for current AWS config")
creds, err := config.Credentials.Retrieve(context.TODO())
if err != nil {
return config, err
if strings.Contains(err.Error(), "SSO") {
// This code is not working as expected, so we use the AWS CLI to perform the SSO login.
// The problem is that the library does not handle the default profile correctly.
// out, err_sso := ssologin.Login(context.TODO(), &ssologin.LoginInput{
// ProfileName: tgfConfig.tgf.AwsProfile,
// Headed: true,
// })
// log.Warning("You need to login to AWS SSO")
// x := sso.NewFromConfig(config)
// x.Logout(context.TODO(), &sso.LogoutInput{})
// log.Debug(out)
// if err_sso != nil {
// return config, err_sso
// }

cmd := exec.Command("aws", "sso", "login")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
} else {
return config, err
}
}

expiresIn := time.Until(creds.Expires)
Expand Down Expand Up @@ -364,7 +385,7 @@ func (config *TGFConfig) setDefaultValues() {
// Fetch file configs
for _, configFile := range config.findConfigFiles(must(os.Getwd()).(string)) {
log.Debugln("Reading configuration from", configFile)
bytes, err := ioutil.ReadFile(configFile)
bytes, err := os.ReadFile(configFile)

if err != nil {
log.Errorf("Error while loading configuration file %s\n%v", configFile, err)
Expand Down Expand Up @@ -573,7 +594,7 @@ func (config *TGFConfig) findRemoteConfigFiles(location, files string) []string
}
configPaths := strings.Split(files, ":")

tempDir := must(ioutil.TempDir("", "tgf-config-files")).(string)
tempDir := must(os.MkdirTemp("", "tgf-config-files")).(string)
defer os.RemoveAll(tempDir)

configs := []string{}
Expand All @@ -596,7 +617,7 @@ func (config *TGFConfig) findRemoteConfigFiles(location, files string) []string
continue
}

if content, err := ioutil.ReadFile(destConfigPath); err != nil {
if content, err := os.ReadFile(destConfigPath); err != nil {
log.Warningf("Error reading fetched config file %s: %v", configPath, err)
} else {
contentString := string(content)
Expand Down Expand Up @@ -810,7 +831,7 @@ func (config *TGFConfig) getTgfFile(url string) (tgfFile io.ReadCloser, err erro
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return
}
Expand All @@ -830,7 +851,7 @@ func (config *TGFConfig) getTgfFile(url string) (tgfFile io.ReadCloser, err erro

// DoUpdate fetch the executable from the link, unzip it and replace it with the current
func (config *TGFConfig) DoUpdate(url string) (err error) {
savePath, err := ioutil.TempFile("", "tgf.previous-version")
savePath, err := os.MkdirTemp("", "tgf.previous-version")
if err != nil {
return
}
Expand All @@ -840,7 +861,7 @@ func (config *TGFConfig) DoUpdate(url string) (err error) {
return
}

if err = selfupdate.Apply(tgfFile, selfupdate.Options{OldSavePath: savePath.Name()}); err != nil {
if err = selfupdate.Apply(tgfFile, selfupdate.Options{OldSavePath: savePath}); err != nil {
if err := selfupdate.RollbackError(err); err != nil {
log.Errorln("Failed to rollback from bad update:", err)
}
Expand Down
9 changes: 0 additions & 9 deletions config_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,6 @@ func (config *TGFConfig) Run() int {
return 1
}

if app.GetCurrentVersion {
if version == locallyBuilt {
fmt.Println("tgf (built from source)")
} else {
fmt.Printf("tgf v%s\n", version)
}
return 0
}

if app.ConfigDump {
fmt.Println(config.String())
return 0
Expand Down
8 changes: 4 additions & 4 deletions config_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package main
import (
"bytes"
"fmt"
"io/ioutil"
"io"
"os"
"path/filepath"
"strings"
Expand All @@ -27,14 +27,14 @@ func setup(t *testing.T, testFunction func()) (string, string) {
}()

// Create temp dir and config file
tempDir, _ := filepath.EvalSymlinks(must(ioutil.TempDir("", "TestGoMain")).(string))
tempDir, _ := filepath.EvalSymlinks(must(os.MkdirTemp("", "TestGoMain")).(string))
testTgfUserConfigFile := fmt.Sprintf("%s/tgf.user.config", tempDir)
defer func() { assert.NoError(t, os.RemoveAll(tempDir)) }()
tgfConfig := []byte(String(`
docker-image: coveo/stuff
docker-image-version: x
`).UnIndent().TrimSpace())
ioutil.WriteFile(testTgfUserConfigFile, tgfConfig, 0644)
os.WriteFile(testTgfUserConfigFile, tgfConfig, 0644)

// Capture the outputs
var logBuffer bytes.Buffer
Expand All @@ -47,7 +47,7 @@ func setup(t *testing.T, testFunction func()) (string, string) {
// Run the actual test
testFunction()
w.Close()
out, _ := ioutil.ReadAll(r)
out, _ := io.ReadAll(r)
return string(out), logBuffer.String()
}

Expand Down
Loading