github.com/rothwerx/packer@v0.9.0/builder/amazon/common/cli_config_test.go (about) 1 package common 2 3 import ( 4 "io/ioutil" 5 "os" 6 "path" 7 "strconv" 8 "testing" 9 "time" 10 11 "github.com/aws/aws-sdk-go/aws" 12 ) 13 14 func init() { 15 os.Setenv("AWS_ACCESS_KEY_ID", "") 16 os.Setenv("AWS_ACCESS_KEY", "") 17 os.Setenv("AWS_SECRET_ACCESS_KEY", "") 18 os.Setenv("AWS_SECRET_KEY", "") 19 os.Setenv("AWS_CONFIG_FILE", "") 20 os.Setenv("AWS_SHARED_CREDENTIALS_FILE", "") 21 } 22 23 func testCLIConfig() *CLIConfig { 24 return &CLIConfig{} 25 } 26 27 func TestCLIConfigNewFromProfile(t *testing.T) { 28 tmpDir := mockConfig(t) 29 30 c, err := NewFromProfile("testing2") 31 if err != nil { 32 t.Error(err) 33 } 34 if c.AssumeRoleInput.RoleArn != nil { 35 t.Errorf("RoleArn should be nil. Instead %p", c.AssumeRoleInput.RoleArn) 36 } 37 if c.AssumeRoleInput.ExternalId != nil { 38 t.Errorf("ExternalId should be nil. Instead %p", c.AssumeRoleInput.ExternalId) 39 } 40 41 mockConfigClose(t, tmpDir) 42 } 43 44 func TestAssumeRole(t *testing.T) { 45 tmpDir := mockConfig(t) 46 47 c, err := NewFromProfile("testing1") 48 if err != nil { 49 t.Error(err) 50 } 51 // Role 52 e := "arn:aws:iam::123456789011:role/rolename" 53 a := *c.AssumeRoleInput.RoleArn 54 if e != a { 55 t.Errorf("RoleArn value should be %s. Instead %s", e, a) 56 } 57 // Session 58 a = *c.AssumeRoleInput.RoleSessionName 59 e = "testsession" 60 if e != a { 61 t.Errorf("RoleSessionName value should be %s. Instead %s", e, a) 62 } 63 64 config := aws.NewConfig() 65 _, err = c.CredentialsFromProfile(config) 66 if err == nil { 67 t.Error("Should have errored") 68 } 69 mockConfigClose(t, tmpDir) 70 } 71 72 func mockConfig(t *testing.T) string { 73 time := time.Now().UnixNano() 74 dir, err := ioutil.TempDir("", strconv.FormatInt(time, 10)) 75 if err != nil { 76 t.Error(err) 77 } 78 79 cfg := []byte(`[profile testing1] 80 region=us-west-2 81 source_profile=testingcredentials 82 role_arn = arn:aws:iam::123456789011:role/rolename 83 role_session_name = testsession 84 85 [profile testing2] 86 region=us-west-2 87 `) 88 cfgFile := path.Join(dir, "config") 89 err = ioutil.WriteFile(cfgFile, cfg, 0644) 90 if err != nil { 91 t.Error(err) 92 } 93 os.Setenv("AWS_CONFIG_FILE", cfgFile) 94 95 crd := []byte(`[testingcredentials] 96 aws_access_key_id = foo 97 aws_secret_access_key = bar 98 99 [testing2] 100 aws_access_key_id = baz 101 aws_secret_access_key = qux 102 `) 103 crdFile := path.Join(dir, "credentials") 104 err = ioutil.WriteFile(crdFile, crd, 0644) 105 if err != nil { 106 t.Error(err) 107 } 108 os.Setenv("AWS_SHARED_CREDENTIALS_FILE", crdFile) 109 110 return dir 111 } 112 113 func mockConfigClose(t *testing.T, dir string) { 114 err := os.RemoveAll(dir) 115 if err != nil { 116 t.Error(err) 117 } 118 }