forked from gruntwork-io/terratest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathterraform_ssh_example_test.go
308 lines (244 loc) · 11.5 KB
/
terraform_ssh_example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package test
import (
"fmt"
"os"
"strings"
"testing"
"time"
"github.com/gruntwork-io/terratest/modules/aws"
"github.com/gruntwork-io/terratest/modules/random"
"github.com/gruntwork-io/terratest/modules/retry"
"github.com/gruntwork-io/terratest/modules/ssh"
"github.com/gruntwork-io/terratest/modules/terraform"
"github.com/gruntwork-io/terratest/modules/test-structure"
)
// An example of how to test the Terraform module in examples/terraform-ssh-example using Terratest. The test also
// shows an example of how to break a test down into "stages" so you can skip stages by setting environment variables
// (e.g., skip stage "teardown" by setting the environment variable "SKIP_teardown=true"), which speeds up iteration
// when running this test over and over again locally.
func TestTerraformSshExample(t *testing.T) {
t.Parallel()
exampleFolder := test_structure.CopyTerraformFolderToTemp(t, "../", "examples/terraform-ssh-example")
// At the end of the test, run `terraform destroy` to clean up any resources that were created
defer test_structure.RunTestStage(t, "teardown", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, exampleFolder)
terraform.Destroy(t, terraformOptions)
keyPair := test_structure.LoadEc2KeyPair(t, exampleFolder)
aws.DeleteEC2KeyPair(t, keyPair)
})
// Deploy the example
test_structure.RunTestStage(t, "setup", func() {
terraformOptions, keyPair := configureTerraformOptions(t, exampleFolder)
// Save the options and key pair so later test stages can use them
test_structure.SaveTerraformOptions(t, exampleFolder, terraformOptions)
test_structure.SaveEc2KeyPair(t, exampleFolder, keyPair)
// This will run `terraform init` and `terraform apply` and fail the test if there are any errors
terraform.InitAndApply(t, terraformOptions)
})
// Make sure we can SSH to the public Instance directly from the public Internet and the private Instance by using
// the public Instance as a jump host
test_structure.RunTestStage(t, "validate", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, exampleFolder)
keyPair := test_structure.LoadEc2KeyPair(t, exampleFolder)
testSSHToPublicHost(t, terraformOptions, keyPair)
testSSHToPrivateHost(t, terraformOptions, keyPair)
testSSHAgentToPublicHost(t, terraformOptions, keyPair)
testSSHAgentToPrivateHost(t, terraformOptions, keyPair)
testSCPToPublicHost(t, terraformOptions, keyPair)
})
}
func configureTerraformOptions(t *testing.T, exampleFolder string) (*terraform.Options, *aws.Ec2Keypair) {
// A unique ID we can use to namespace resources so we don't clash with anything already in the AWS account or
// tests running in parallel
uniqueID := random.UniqueId()
// Give this EC2 Instance and other resources in the Terraform code a name with a unique ID so it doesn't clash
// with anything else in the AWS account.
instanceName := fmt.Sprintf("terratest-ssh-example-%s", uniqueID)
// Pick a random AWS region to test in. This helps ensure your code works in all regions.
awsRegion := aws.GetRandomRegion(t, nil, nil)
// Create an EC2 KeyPair that we can use for SSH access
keyPairName := fmt.Sprintf("terratest-ssh-example-%s", uniqueID)
keyPair := aws.CreateAndImportEC2KeyPair(t, awsRegion, keyPairName)
terraformOptions := &terraform.Options{
// The path to where our Terraform code is located
TerraformDir: exampleFolder,
// Variables to pass to our Terraform code using -var options
Vars: map[string]interface{}{
"aws_region": awsRegion,
"instance_name": instanceName,
"key_pair_name": keyPairName,
},
}
return terraformOptions, keyPair
}
func testSSHToPublicHost(t *testing.T, terraformOptions *terraform.Options, keyPair *aws.Ec2Keypair) {
// Run `terraform output` to get the value of an output variable
publicInstanceIP := terraform.Output(t, terraformOptions, "public_instance_ip")
// We're going to try to SSH to the instance IP, using the Key Pair we created earlier, and the user "ubuntu",
// as we know the Instance is running an Ubuntu AMI that has such a user
publicHost := ssh.Host{
Hostname: publicInstanceIP,
SshKeyPair: keyPair.KeyPair,
SshUserName: "ubuntu",
}
// It can take a minute or so for the Instance to boot up, so retry a few times
maxRetries := 30
timeBetweenRetries := 5 * time.Second
description := fmt.Sprintf("SSH to public host %s", publicInstanceIP)
// Run a simple echo command on the server
expectedText := "Hello, World"
command := fmt.Sprintf("echo -n '%s'", expectedText)
// Verify that we can SSH to the Instance and run commands
retry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {
actualText, err := ssh.CheckSshCommandE(t, publicHost, command)
if err != nil {
return "", err
}
if strings.TrimSpace(actualText) != expectedText {
return "", fmt.Errorf("Expected SSH command to return '%s' but got '%s'", expectedText, actualText)
}
return "", nil
})
}
func testSSHToPrivateHost(t *testing.T, terraformOptions *terraform.Options, keyPair *aws.Ec2Keypair) {
// Run `terraform output` to get the value of an output variable
publicInstanceIP := terraform.Output(t, terraformOptions, "public_instance_ip")
privateInstanceIP := terraform.Output(t, terraformOptions, "private_instance_ip")
// We're going to try to SSH to the private instance using the public instance as a jump host. For both instances,
// we are using the Key Pair we created earlier, and the user "ubuntu", as we know the Instances are running an
// Ubuntu AMI that has such a user
publicHost := ssh.Host{
Hostname: publicInstanceIP,
SshKeyPair: keyPair.KeyPair,
SshUserName: "ubuntu",
}
privateHost := ssh.Host{
Hostname: privateInstanceIP,
SshKeyPair: keyPair.KeyPair,
SshUserName: "ubuntu",
}
// It can take a minute or so for the Instance to boot up, so retry a few times
maxRetries := 30
timeBetweenRetries := 5 * time.Second
description := fmt.Sprintf("SSH to private host %s via public host %s", publicInstanceIP, privateInstanceIP)
// Run a simple echo command on the server
expectedText := "Hello, World"
command := fmt.Sprintf("echo -n '%s'", expectedText)
// Verify that we can SSH to the Instance and run commands
retry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {
actualText, err := ssh.CheckPrivateSshConnectionE(t, publicHost, privateHost, command)
if err != nil {
return "", err
}
if strings.TrimSpace(actualText) != expectedText {
return "", fmt.Errorf("Expected SSH command to return '%s' but got '%s'", expectedText, actualText)
}
return "", nil
})
}
func testSCPToPublicHost(t *testing.T, terraformOptions *terraform.Options, keyPair *aws.Ec2Keypair) {
// Run `terraform output` to get the value of an output variable
publicInstanceIP := terraform.Output(t, terraformOptions, "public_instance_ip")
// We're going to try to SSH to the instance IP, using the Key Pair we created earlier, and the user "ubuntu",
// as we know the Instance is running an Ubuntu AMI that has such a user
publicHost := ssh.Host{
Hostname: publicInstanceIP,
SshKeyPair: keyPair.KeyPair,
SshUserName: "ubuntu",
}
// It can take a minute or so for the Instance to boot up, so retry a few times
maxRetries := 10
timeBetweenRetries := 1 * time.Second
description := fmt.Sprintf("SCP file to public host %s", publicInstanceIP)
// Run a simple echo command on the server
expectedText := "Hello, World"
// Verify that we can SSH to the Instance and run commands
retry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {
err := ssh.ScpFileToE(t, publicHost, os.FileMode(0644), "/tmp/test.txt", expectedText)
if err != nil {
return "", err
}
actualText, err := ssh.FetchContentsOfFileE(t, publicHost, false, "/tmp/test.txt")
if err != nil {
return "", err
}
if strings.TrimSpace(actualText) != expectedText {
return "", fmt.Errorf("Expected SSH command to return '%s' but got '%s'", expectedText, actualText)
}
return "", nil
})
}
func testSSHAgentToPublicHost(t *testing.T, terraformOptions *terraform.Options, keyPair *aws.Ec2Keypair) {
// Run `terraform output` to get the value of an output variable
publicInstanceIP := terraform.Output(t, terraformOptions, "public_instance_ip")
// start the ssh agent
sshAgent := ssh.SshAgentWithKeyPair(t, keyPair.KeyPair)
defer sshAgent.Stop()
// We're going to try to SSH to the instance IP, using the Key Pair we created earlier. Instead of
// directly using the SSH key in the SSH connection, we're going to rely on an existing SSH agent that we
// programatically emulate within this test. We're going to use the user "ubuntu" as we know the Instance
// is running an Ubuntu AMI that has such a user
publicHost := ssh.Host{
Hostname: publicInstanceIP,
SshUserName: "ubuntu",
OverrideSshAgent: sshAgent,
}
// It can take a minute or so for the Instance to boot up, so retry a few times
maxRetries := 30
timeBetweenRetries := 5 * time.Second
description := fmt.Sprintf("SSH with Agent to public host %s", publicInstanceIP)
// Run a simple echo command on the server
expectedText := "Hello, World"
command := fmt.Sprintf("echo -n '%s'", expectedText)
// Verify that we can SSH to the Instance and run commands
retry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {
actualText, err := ssh.CheckSshCommandE(t, publicHost, command)
if err != nil {
return "", err
}
if strings.TrimSpace(actualText) != expectedText {
return "", fmt.Errorf("Expected SSH command to return '%s' but got '%s'", expectedText, actualText)
}
return "", nil
})
}
func testSSHAgentToPrivateHost(t *testing.T, terraformOptions *terraform.Options, keyPair *aws.Ec2Keypair) {
// Run `terraform output` to get the value of an output variable
publicInstanceIP := terraform.Output(t, terraformOptions, "public_instance_ip")
privateInstanceIP := terraform.Output(t, terraformOptions, "private_instance_ip")
// start the ssh agent
sshAgent := ssh.SshAgentWithKeyPair(t, keyPair.KeyPair)
defer sshAgent.Stop()
// We're going to try to SSH to the private instance using the public instance as a jump host. Instead of
// directly using the SSH key in the SSH connection, we're going to rely on an existing SSH agent that we
// programatically emulate within this test. For both instances, we are using the Key Pair we created earlier,
// and the user "ubuntu", as we know the Instances are running an Ubuntu AMI that has such a user
publicHost := ssh.Host{
Hostname: publicInstanceIP,
SshUserName: "ubuntu",
OverrideSshAgent: sshAgent,
}
privateHost := ssh.Host{
Hostname: privateInstanceIP,
SshUserName: "ubuntu",
OverrideSshAgent: sshAgent,
}
// It can take a minute or so for the Instance to boot up, so retry a few times
maxRetries := 30
timeBetweenRetries := 5 * time.Second
description := fmt.Sprintf("SSH with Agent to private host %s via public host %s", publicInstanceIP, privateInstanceIP)
// Run a simple echo command on the server
expectedText := "Hello, World"
command := fmt.Sprintf("echo -n '%s'", expectedText)
// Verify that we can SSH to the Instance and run commands
retry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {
actualText, err := ssh.CheckPrivateSshConnectionE(t, publicHost, privateHost, command)
if err != nil {
return "", err
}
if strings.TrimSpace(actualText) != expectedText {
return "", fmt.Errorf("Expected SSH command to return '%s' but got '%s'", expectedText, actualText)
}
return "", nil
})
}