Skip to content

Commit

Permalink
Merge pull request #208 from kubefirst/add_iam_role_to_aws_client_merge
Browse files Browse the repository at this point in the history
Add iam role to aws client merge
  • Loading branch information
João Paulo Vanzuita authored Aug 11, 2022
2 parents 89a33eb + 7a670d3 commit a299216
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 14 deletions.
5 changes: 1 addition & 4 deletions cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ to quickly create a Cobra application.`,
}

//!--

if !skipVault {
progressPrinter.AddTracker("step-vault-be", "Configure Vault Backend", 1)
log.Println("configuring vault backend")
Expand All @@ -378,9 +378,6 @@ to quickly create a Cobra application.`,
progressPrinter.IncrementTracker("step-vault-be", 1)
}




sendCompleteInstallTelemetry(dryRun, useTelemetry)
time.Sleep(time.Millisecond * 100)

Expand Down
10 changes: 4 additions & 6 deletions cmd/destroy.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,16 @@ package cmd
import (
"bytes"
"fmt"
"log"
"os/exec"
"syscall"
"time"

"github.com/kubefirst/kubefirst/configs"
"github.com/kubefirst/kubefirst/internal/gitlab"
"github.com/kubefirst/kubefirst/internal/k8s"
"github.com/kubefirst/kubefirst/internal/progressPrinter"
"github.com/kubefirst/kubefirst/internal/terraform"
"github.com/spf13/cobra"
"log"
"os/exec"
"syscall"
"time"
)

// destroyCmd represents the destroy command
Expand Down Expand Up @@ -141,6 +140,5 @@ func init() {
destroyCmd.Flags().Bool("skip-gitlab-terraform", false, "whether to skip the terraform destroy against gitlab - note: if you already deleted registry it doesnt exist")
destroyCmd.Flags().Bool("skip-delete-register", false, "whether to skip deletion of register application ")
destroyCmd.Flags().Bool("skip-base-terraform", false, "whether to skip the terraform destroy against base install - note: if you already deleted registry it doesnt exist")
destroyCmd.Flags().Bool("destroy-buckets", false, "remove created aws buckets, not empty buckets are not cleaned")
destroyCmd.Flags().Bool("dry-run", false, "set to dry-run mode, no changes done on cloud provider selected")
}
26 changes: 23 additions & 3 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,22 @@ to quickly create a Cobra application.`,

log.Println("dry run enabled:", dryRun)

arnRole, err := cmd.Flags().GetString("aws-assume-role")
if err != nil {
log.Println("unable to use the provided AWS IAM role for AssumeRole feature")
return
}

if len(arnRole) > 0 {
log.Println("calling assume role")
err := aws.AssumeRole(arnRole)
if err != nil {
log.Println(err)
return
}
log.Printf("assuming new AWS credentials based on role %q", arnRole)
}

pkg.SetupProgress(10)
trackers := pkg.GetTrackers()
trackers[pkg.DownloadDependencies] = &pkg.ActionTracker{Tracker: pkg.CreateTracker(pkg.DownloadDependencies, 3)}
Expand Down Expand Up @@ -98,10 +114,10 @@ to quickly create a Cobra application.`,
log.Println("adminEmail:", adminEmail)
viper.Set("adminemail", adminEmail)

// profile
// set region
region, err := cmd.Flags().GetString("region")
if err != nil {
log.Println(err)
log.Panicf("unable to get region values from viper")
}
viper.Set("aws.region", region)
// propagate it to local environment
Expand All @@ -111,9 +127,10 @@ to quickly create a Cobra application.`,
}
log.Println("region:", region)

// set profile
profile, err := cmd.Flags().GetString("profile")
if err != nil {
log.Println(err)
log.Panicf("unable to get region values from viper")
}
viper.Set("aws.profile", profile)
// propagate it to local environment
Expand Down Expand Up @@ -270,5 +287,8 @@ func init() {
initCmd.Flags().String("cluster-name", "kubefirst", "the cluster name, used to identify resources on cloud provider")
initCmd.Flags().String("s3-suffix", "", "unique identifier for s3 buckets")
initCmd.Flags().String("version-gitops", "main", "version/branch used on git clone")

// AWS assume role
initCmd.Flags().String("aws-assume-role", "", "instead of using AWS IAM user credentials, AWS AssumeRole feature generate role based credentials, more at https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html")
initCmd.Flags().Bool("use-telemetry", true, "installer will not send telemetry about this installation")
}
8 changes: 8 additions & 0 deletions configs/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,13 @@ func ReadConfig() *Config {

config.InstallerEmail = "[email protected]"

// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value the shared config file (~/.aws/config)
// will also be loaded in addition to the shared credentials file (~/.aws/credentials).
// AWS SDK client will take it in advance
err = os.Setenv("AWS_SDK_LOAD_CONFIG", "1")
if err != nil {
log.Panicf("unable to set AWS_SDK_LOAD_CONFIG enviroment value, error is: %v", err)
}

return &config
}
52 changes: 51 additions & 1 deletion internal/aws/aws.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package aws

// todo: refactor is necessary to use AWS SDK v2 only

import (
"context"
"fmt"
Expand All @@ -21,8 +23,10 @@ import (
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
stsV1 "github.com/aws/aws-sdk-go/service/sts"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/cip8/autoname"
"github.com/google/uuid"
"github.com/kubefirst/kubefirst/pkg"
"github.com/spf13/viper"
)
Expand Down Expand Up @@ -316,8 +320,9 @@ func GetAWSSession() *session.Session {
Profile: viper.GetString("aws.profile"),
})
if err != nil {
log.Panicf("failed to get session ", err.Error())
log.Panicf("failed to get session %s", err.Error())
}

return sess
}

Expand All @@ -336,6 +341,51 @@ func DestroyBucketsInUse(destroyBuckets bool) {
}
}

// AssumeRole receives a AWS IAM Role, and instead of using regular AWS credentials, it generates new AWS credentials
// based on the provided role. New AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN are provided. The
// new AWS credentials has expiration time set.
func AssumeRole(roleArn string) error {

sess := GetAWSSession()

svc := stsV1.New(sess)

// Use the role session name to uniquely identify a session when the same role is assumed by different principals
// or for different reasons.
roleSessionName, err := uuid.NewUUID()
if err != nil {
log.Println(err)
return err
}

assumeRoleInput := stsV1.AssumeRoleInput{
RoleArn: aws.String(roleArn),
RoleSessionName: aws.String(roleSessionName.String()),
DurationSeconds: aws.Int64(60 * 60 * 1),
}

result, err := svc.AssumeRole(&assumeRoleInput)
if err != nil {
fmt.Printf("unable to assume role, %v\n", err)
return err
}

// update AWS keys
if err := os.Setenv("AWS_ACCESS_KEY_ID", *result.Credentials.AccessKeyId); err != nil {
fmt.Printf("unable to set AWS_ACCESS_KEY_ID environment variable. Err: %v", err)
}

if err := os.Setenv("AWS_SECRET_ACCESS_KEY", *result.Credentials.SecretAccessKey); err != nil {
fmt.Printf("unable to set AWS_SECRET_ACCESS_KEY environment variable. Err: %v", err)
}

if err := os.Setenv("AWS_SESSION_TOKEN", *result.Credentials.SessionToken); err != nil {
fmt.Printf("unable to set AWS_SESSION_TOKEN environment variable. Err: %v", err)
}

return nil
}

func CreateBucket(dryRun bool, name string) {
log.Println("createBucketCalled")

Expand Down

0 comments on commit a299216

Please sign in to comment.