Skip to content

Commit

Permalink
Merge pull request #30 from daidokoro/session-manager
Browse files Browse the repository at this point in the history
Session manager update & termination protection - v0.81-beta
  • Loading branch information
daidokoro authored May 11, 2018
2 parents c11b78d + f51d490 commit e172ce2
Show file tree
Hide file tree
Showing 17 changed files with 238 additions and 62 deletions.
2 changes: 1 addition & 1 deletion commands/aws_lambda.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ var invokeCmd = &cobra.Command{
return
}

sess, err := manager.GetSess(run.profile)
sess, err := GetSession()
utils.HandleError(err)

f := awsLambda{name: args[0]}
Expand Down
2 changes: 1 addition & 1 deletion commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ var (
// Get Project & AWS Region
arrow := log.ColorString("->", "magenta")
project = utils.GetInput(fmt.Sprintf("%s Enter your Project name", arrow), "qaz-project")
region = utils.GetInput(fmt.Sprintf("%s Enter AWS Region", arrow), "eu-west-1")
region := utils.GetInput(fmt.Sprintf("%s Enter AWS Region", arrow), "eu-west-1")

// set target paths
c := filepath.Join(target, "config.yml")
Expand Down
24 changes: 22 additions & 2 deletions commands/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (

yaml "gopkg.in/yaml.v2"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
stks "github.com/daidokoro/qaz/stacks"

"github.com/daidokoro/hcl"
Expand All @@ -14,7 +16,7 @@ import (
func Configure(confSource string, conf string) (err error) {

// set config session
config.Session, err = manager.GetSess(run.profile)
config.Session, err = GetSession()
if err != nil {
return
}
Expand Down Expand Up @@ -51,6 +53,7 @@ func Configure(confSource string, conf string) (err error) {
stacks.Add(s, &stks.Stack{
Name: s,
Profile: v.Profile,
Region: v.Region,
DependsOn: v.DependsOn,
Policy: v.Policy,
Source: v.Source,
Expand All @@ -68,7 +71,24 @@ func Configure(confSource string, conf string) (err error) {
stacks.MustGet(s).SetStackName()

// set session
stacks.MustGet(s).Session, err = manager.GetSess(stacks.MustGet(s).Profile)
stacks.MustGet(s).Session, err = GetSession(func(opts *session.Options) {
if stacks.MustGet(s).Profile != "" {
opts.Profile = stacks.MustGet(s).Profile
}

// use config region
if config.Region != "" {
opts.Config.Region = aws.String(config.Region)
}

// stack region trumps all other regions if-set
if stacks.MustGet(s).Region != "" {
opts.Config.Region = aws.String(stacks.MustGet(s).Region)
}

return
})

if err != nil {
return
}
Expand Down
21 changes: 14 additions & 7 deletions commands/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -184,21 +184,28 @@ var (
PreRun: initialise,
Run: func(cmd *cobra.Command, args []string) {

if len(args) < 1 {
if len(args) < 1 && !run.all {
log.Warn("No stack specified for termination")
return
}

err := Configure(run.cfgSource, "")
utils.HandleError(err)

if !run.all {
for _, s := range args {
if _, ok := stacks.Get(s); !ok {
utils.HandleError(fmt.Errorf("stacks [%s] not found in config", s))
}
stacks.MustGet(s).Actioned = true
// select actioned stacks
for _, s := range args {
if _, ok := stacks.Get(s); !ok {
utils.HandleError(fmt.Errorf("stacks [%s] not found in config", s))
}
stacks.MustGet(s).Actioned = true
}

// action stacks if all
if run.all {
stacks.Range(func(_ string, s *stks.Stack) bool {
s.Actioned = true
return true
})
}

// Terminate Stacks
Expand Down
30 changes: 18 additions & 12 deletions commands/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,15 @@ import (
"encoding/json"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/kms"
)

// Common Functions - Both Deploy/Gen
var (
kmsEncrypt = func(kid string, text string) string {
log.Debug("running template function: [kms_encrypt]")
sess, err := manager.GetSess(run.profile)
sess, err := GetSession()
utils.HandleError(err)

svc := kms.New(sess)
Expand All @@ -39,7 +40,7 @@ var (

kmsDecrypt = func(cipher string) string {
log.Debug("running template function: [kms_decrypt]")
sess, err := manager.GetSess(run.profile)
sess, err := GetSession()
utils.HandleError(err)

svc := kms.New(sess)
Expand Down Expand Up @@ -68,14 +69,15 @@ var (
s3Read = func(url string, profile ...string) string {
log.Debug("Calling Template Function [S3Read] with arguments: %s", url)

var p = run.profile
if len(profile) < 1 {
log.Warn("No Profile specified for S3read, using: %s", p)
} else {
p = profile[0]
}
sess, err := GetSession(func(opts *session.Options) {
if len(profile) < 1 {
log.Warn("No Profile specified for S3read, using: %s", run.profile)
return
}
opts.Profile = profile[0]
return
})

sess, err := manager.GetSess(p)
utils.HandleError(err)

resp, err := bucket.S3Read(url, sess)
Expand All @@ -93,7 +95,7 @@ var (
f.payload = []byte(payload)
}

sess, err := manager.GetSess(run.profile)
sess, err := GetSession()
utils.HandleError(err)

err = f.Invoke(sess)
Expand Down Expand Up @@ -190,7 +192,11 @@ var (
log.Debug("Deploy-Time function resolving: %s", target)
req := strings.Split(target, "::")

s := stacks.MustGet(req[0])
s, ok := stacks.Get(req[0])
if !ok {
utils.HandleError(fmt.Errorf("stack_output errror: stack [%s] not found", req[0]))
}

utils.HandleError(s.Outputs())

for _, i := range s.Output.Stacks {
Expand All @@ -208,7 +214,7 @@ var (
log.Debug("Deploy-Time function resolving: %s", target)
req := strings.Split(target, "::")

sess, err := manager.GetSess(run.profile)
sess, err := GetSession()
utils.HandleError(err)

s := stks.Stack{
Expand Down
18 changes: 14 additions & 4 deletions commands/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,29 +23,35 @@ func init() {
gitDeployCmd.Flags().StringVarP(&run.gitpass, "password", "", "", "git password")
gitDeployCmd.Flags().StringVarP(&run.gitrsa, "ssh-rsa", "", filepath.Join(os.Getenv("HOME"), ".ssh/id_rsa"), "path to git SSH id_rsa")

// Define Git Status Command
gitStatusCmd.Flags().StringVarP(&run.gitrsa, "ssh-rsa", "", filepath.Join(os.Getenv("HOME"), ".ssh/id_rsa"), "path to git SSH id_rsa")
gitStatusCmd.Flags().StringVarP(&run.gitpass, "password", "", "", "git password")
gitStatusCmd.Flags().StringVarP(&run.gituser, "user", "u", "", "git username")

// Define Terminate Flags
terminateCmd.Flags().BoolVarP(&run.all, "all", "A", false, "terminate all stacks")

// Define Output Flags
outputsCmd.Flags().StringVarP(&run.profile, "profile", "p", "default", "configured aws profile")

// Define Exports Flags
exportsCmd.Flags().StringVarP(&region, "region", "r", "eu-west-1", "AWS Region")

// Define Root Flags
RootCmd.Flags().BoolVarP(&run.version, "version", "", false, "print current/running version")
RootCmd.PersistentFlags().BoolVarP(&run.colors, "no-colors", "", false, "disable colors in outputs")
RootCmd.PersistentFlags().StringVarP(&run.profile, "profile", "p", "default", "configured aws profile")
RootCmd.PersistentFlags().StringVarP(&run.region, "region", "r", "", "configured aws region: if blank, the region is acquired via the profile")
RootCmd.PersistentFlags().BoolVarP(&run.debug, "debug", "", false, "Run in debug mode...")

// Define Lambda Invoke Flags
invokeCmd.Flags().StringVarP(&region, "region", "r", "eu-west-1", "AWS Region")
invokeCmd.Flags().StringVarP(&run.funcEvent, "event", "e", "", "JSON Event data for AWS Lambda invoke")
invokeCmd.Flags().BoolVarP(&run.lambdAsync, "async", "x", false, "invoke lambda function asynchronously ")

// Define Changes Command
changeCmd.AddCommand(create, rm, list, execute, desc)

// Define Protect Command
protectCmd.Flags().BoolVarP(&run.protectOff, "off", "", false, "set termination protection to off")
protectCmd.Flags().BoolVarP(&run.all, "all", "A", false, "protect all stacks")

// Add Config --config common flag
for _, cmd := range []interface{}{
checkCmd,
Expand All @@ -56,9 +62,11 @@ func init() {
generateCmd,
deployCmd,
gitDeployCmd,
gitStatusCmd,
policyCmd,
valuesCmd,
shellCmd,
protectCmd,
} {
cmd.(*cobra.Command).Flags().StringVarP(&run.cfgSource, "config", "c", defaultConfig(), "path to config file")
}
Expand Down Expand Up @@ -101,8 +109,10 @@ func init() {
changeCmd,
policyCmd,
gitDeployCmd,
gitStatusCmd,
valuesCmd,
shellCmd,
protectCmd,
)

}
2 changes: 1 addition & 1 deletion commands/outputs.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ var (
Example: "qaz exports",
PreRun: initialise,
Run: func(cmd *cobra.Command, args []string) {
sess, err := manager.GetSess(run.profile)
sess, err := GetSession()
utils.HandleError(err)
utils.HandleError(stks.Exports(sess))
},
Expand Down
44 changes: 15 additions & 29 deletions commands/sessions.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,47 +6,33 @@ import (
"github.com/aws/aws-sdk-go/aws/session"
)

// SessionManager - handles AWS Sessions
type sessionManager struct {
region string
sessions map[string]*session.Session
}

// GetSess - Returns aws session based on given profile
func (s *sessionManager) GetSess(p string) (*session.Session, error) {
// GetSession - Returns aws session based on default run.profile and run.Region
// options can be overwritten by passing a function: func(*session.Options)
func GetSession(options ...func(*session.Options)) (*session.Session, error) {

var sess *session.Session

// Set P to default or command input if stack input is empty
if p == "" {
p = run.profile
}

if v, ok := s.sessions[p]; ok {
log.Debug("Session Detected: [%s]", p)
return v, nil
}

options := session.Options{
Profile: p,
// set default config values
opts := &session.Options{
Profile: run.profile,
SharedConfigState: session.SharedConfigEnable,
AssumeRoleTokenProvider: stscreds.StdinTokenProvider,
}

if s.region != "" {
options.Config = aws.Config{Region: &s.region}
if run.region != "" {
opts.Config = aws.Config{Region: &run.region}
}

// apply external Options
for _, f := range options {
f(opts)
}

log.Debug("Creating AWS Session with options: Regioin: %s, Profile: %s ", region, run.profile)
sess, err := session.NewSessionWithOptions(options)
log.Debug("Creating AWS Session with options: %s", opts)
sess, err := session.NewSessionWithOptions(*opts)
if err != nil {
return sess, err
}

s.sessions[p] = sess
return sess, nil
}

var manager = sessionManager{
sessions: make(map[string]*session.Session),
}
Loading

0 comments on commit e172ce2

Please sign in to comment.