github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/amazon/common/ssh_test.go (about) 1 package common 2 3 import ( 4 "testing" 5 6 "github.com/aws/aws-sdk-go/aws" 7 "github.com/aws/aws-sdk-go/service/ec2" 8 "github.com/mitchellh/multistep" 9 ) 10 11 const ( 12 privateIP = "10.0.0.1" 13 publicIP = "192.168.1.1" 14 publicDNS = "public.dns.test" 15 ) 16 17 func TestSSHHost(t *testing.T) { 18 origSshHostSleepDuration := sshHostSleepDuration 19 defer func() { sshHostSleepDuration = origSshHostSleepDuration }() 20 sshHostSleepDuration = 0 21 22 var cases = []struct { 23 allowTries int 24 vpcId string 25 private bool 26 27 ok bool 28 wantHost string 29 }{ 30 {1, "", false, true, publicDNS}, 31 {1, "", true, true, privateIP}, 32 {1, "vpc-id", false, true, publicIP}, 33 {1, "vpc-id", true, true, privateIP}, 34 {2, "", false, true, publicDNS}, 35 {2, "", true, true, privateIP}, 36 {2, "vpc-id", false, true, publicIP}, 37 {2, "vpc-id", true, true, privateIP}, 38 {3, "", false, false, ""}, 39 {3, "", true, false, ""}, 40 {3, "vpc-id", false, false, ""}, 41 {3, "vpc-id", true, false, ""}, 42 } 43 44 for _, c := range cases { 45 testSSHHost(t, c.allowTries, c.vpcId, c.private, c.ok, c.wantHost) 46 } 47 } 48 49 func testSSHHost(t *testing.T, allowTries int, vpcId string, private, ok bool, wantHost string) { 50 t.Logf("allowTries=%d vpcId=%s private=%t ok=%t wantHost=%q", allowTries, vpcId, private, ok, wantHost) 51 52 e := &fakeEC2Describer{ 53 allowTries: allowTries, 54 vpcId: vpcId, 55 privateIP: privateIP, 56 publicIP: publicIP, 57 publicDNS: publicDNS, 58 } 59 60 f := SSHHost(e, private) 61 st := &multistep.BasicStateBag{} 62 st.Put("instance", &ec2.Instance{ 63 InstanceId: aws.String("instance-id"), 64 }) 65 66 host, err := f(st) 67 68 if e.tries > allowTries { 69 t.Fatalf("got %d ec2 DescribeInstances tries, want %d", e.tries, allowTries) 70 } 71 72 switch { 73 case ok && err != nil: 74 t.Fatalf("expected no error, got %+v", err) 75 case !ok && err == nil: 76 t.Fatalf("expected error, got none and host %s", host) 77 } 78 79 if host != wantHost { 80 t.Fatalf("got host %s, want %s", host, wantHost) 81 } 82 } 83 84 type fakeEC2Describer struct { 85 allowTries int 86 tries int 87 88 vpcId string 89 privateIP, publicIP, publicDNS string 90 } 91 92 func (d *fakeEC2Describer) DescribeInstances(in *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error) { 93 d.tries++ 94 95 instance := &ec2.Instance{ 96 InstanceId: aws.String("instance-id"), 97 } 98 99 if d.vpcId != "" { 100 instance.VpcId = aws.String(d.vpcId) 101 } 102 103 if d.tries >= d.allowTries { 104 instance.PublicIpAddress = aws.String(d.publicIP) 105 instance.PrivateIpAddress = aws.String(d.privateIP) 106 instance.PublicDnsName = aws.String(d.publicDNS) 107 } 108 109 out := &ec2.DescribeInstancesOutput{ 110 Reservations: []*ec2.Reservation{ 111 { 112 Instances: []*ec2.Instance{instance}, 113 }, 114 }, 115 } 116 117 return out, nil 118 }