forked from gruntwork-io/terratest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terraform_scp_example_test.go
331 lines (260 loc) · 11.8 KB
/
terraform_scp_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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
package test
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"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"
test_structure "github.com/gruntwork-io/terratest/modules/test-structure"
"github.com/stretchr/testify/assert"
)
func TestTerraformScpExample(t *testing.T) {
t.Parallel()
exampleFolder := test_structure.CopyTerraformFolderToTemp(t, "../", "examples/terraform-asg-scp-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 := createTerraformOptions(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 SCP a file from an EC2 instance to our local box
test_structure.RunTestStage(t, "validate_file", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, exampleFolder)
keyPair := test_structure.LoadEc2KeyPair(t, exampleFolder)
testScpFromHost(t, terraformOptions, keyPair)
})
// Make sure we can SCP all files in a given remote dir from an EC2 instance to our local box
test_structure.RunTestStage(t, "validate_dir", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, exampleFolder)
keyPair := test_structure.LoadEc2KeyPair(t, exampleFolder)
testScpDirFromHost(t, terraformOptions, keyPair)
})
// Make sure we can SCP all files in a given remote dir from an EC2 instance to our local box
test_structure.RunTestStage(t, "validate_asg", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, exampleFolder)
keyPair := test_structure.LoadEc2KeyPair(t, exampleFolder)
testScpFromAsg(t, terraformOptions, keyPair, exampleFolder)
})
}
func createTerraformOptions(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-asg-scp-example-%s", uniqueID)
// Pick a random AWS region to test in. This helps ensure your code works in all regions.
awsRegion := aws.GetRandomStableRegion(t, nil, nil)
// Create an EC2 KeyPair that we can use for SSH access
keyPairName := fmt.Sprintf("terratest-asg-scp-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 testScpDirFromHost(t *testing.T, terraformOptions *terraform.Options, keyPair *aws.Ec2Keypair) {
// Run `terraform output` to get the value of an output variable
awsRegion := terraformOptions.Vars["aws_region"].(string)
asgName := terraform.Output(t, terraformOptions, "asg_name")
instanceIds := aws.GetInstanceIdsForAsg(t, asgName, awsRegion)
publicInstanceIP := aws.GetPublicIpOfEc2Instance(t, instanceIds[0], awsRegion)
// 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
sshUserName := "ubuntu"
publicHost := ssh.Host{
Hostname: publicInstanceIP,
SshKeyPair: keyPair.KeyPair,
SshUserName: sshUserName,
}
_, remoteTempFilePath := writeSampleDataToInstance(t, publicInstanceIP, sshUserName, keyPair)
remoteTempFolder := filepath.Dir(remoteTempFilePath)
defer cleanup(t, publicInstanceIP, sshUserName, keyPair, remoteTempFolder)
localDestDir := "/tmp/tempFolder"
var testcases = []struct {
name string
options ssh.ScpDownloadOptions
expectedFiles int
}{
{
"GrabAllFiles",
ssh.ScpDownloadOptions{RemoteHost: publicHost, RemoteDir: remoteTempFolder, LocalDir: filepath.Join(localDestDir, random.UniqueId())},
2,
},
{
"GrabAllFilesExplicit",
ssh.ScpDownloadOptions{RemoteHost: publicHost, RemoteDir: remoteTempFolder, LocalDir: filepath.Join(localDestDir, random.UniqueId()), FileNameFilters: []string{"*"}},
2,
},
{
"GrabFilesWithFilter",
ssh.ScpDownloadOptions{RemoteHost: publicHost, RemoteDir: remoteTempFolder, LocalDir: filepath.Join(localDestDir, random.UniqueId()), FileNameFilters: []string{"*.baz"}},
1,
},
}
for _, testCase := range testcases {
// The following is necessary to make sure testCase's values don't
// get updated due to concurrency within the scope of t.Run(..) below
testCase := testCase
t.Run(testCase.name, func(t *testing.T) {
err := ssh.ScpDirFromE(t, testCase.options, false)
if err != nil {
t.Fatalf("Error copying from remote: %s", err.Error())
}
expectedNumFiles := testCase.expectedFiles
fileInfos, err := ioutil.ReadDir(testCase.options.LocalDir)
if err != nil {
t.Fatalf("Error reading from local dir: %s, due to: %s", testCase.options.LocalDir, err.Error())
}
actualNumFilesCopied := len(fileInfos)
if len(fileInfos) != expectedNumFiles {
t.Fatalf("Error: expected %d files to be copied. Only found %d", expectedNumFiles, actualNumFilesCopied)
}
// Clean up the temp file we created
os.RemoveAll(testCase.options.LocalDir)
})
}
}
func testScpFromHost(t *testing.T, terraformOptions *terraform.Options, keyPair *aws.Ec2Keypair) {
// Run `terraform output` to get the value of an output variable
awsRegion := terraformOptions.Vars["aws_region"].(string)
asgName := terraform.Output(t, terraformOptions, "asg_name")
instanceIds := aws.GetInstanceIdsForAsg(t, asgName, awsRegion)
publicInstanceIP := aws.GetPublicIpOfEc2Instance(t, instanceIds[0], awsRegion)
// 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
sshUserName := "ubuntu"
publicHost := ssh.Host{
Hostname: publicInstanceIP,
SshKeyPair: keyPair.KeyPair,
SshUserName: sshUserName,
}
randomData, remoteTempFilePath := writeSampleDataToInstance(t, publicInstanceIP, sshUserName, keyPair)
remoteTempFolder := filepath.Base(remoteTempFilePath)
defer cleanup(t, publicInstanceIP, sshUserName, keyPair, remoteTempFolder)
localTempFileName := "/tmp/test.out"
localFile, err := os.Create(localTempFileName)
// Clean up the temp file we created
defer os.Remove(localTempFileName)
if err != nil {
t.Fatalf("Error: creating local temp file: %s", err.Error())
}
ssh.ScpFileFromE(t, publicHost, remoteTempFilePath, localFile, false)
buf, err := ioutil.ReadFile(localTempFileName)
if err != nil {
t.Fatalf("Error: Unable to read local file from disk: %s", err.Error())
}
localFileContents := string(buf)
if !strings.Contains(localFileContents, randomData) {
t.Fatalf("Error: unable to find %s in the local file. Local file's contents were: %s", randomData, localFileContents)
}
}
func testScpFromAsg(t *testing.T, terraformOptions *terraform.Options, keyPair *aws.Ec2Keypair, exampleFolder string) {
// Run `terraform output` to get the value of an output variable
awsRegion := terraformOptions.Vars["aws_region"].(string)
asgName := terraform.Output(t, terraformOptions, "asg_name")
instanceIds := aws.GetInstanceIdsForAsg(t, asgName, awsRegion)
publicInstanceIP := aws.GetPublicIpOfEc2Instance(t, instanceIds[0], awsRegion)
// This is where we'll store the logs from the remote server
localDestinationDirectory := filepath.Join(exampleFolder, "logs")
sshUserName := "ubuntu"
randomData, remoteTempFilePath := writeSampleDataToInstance(t, publicInstanceIP, sshUserName, keyPair)
remoteTempFolder, remoteTempFileName := filepath.Split(remoteTempFilePath)
defer cleanup(t, publicInstanceIP, sshUserName, keyPair, remoteTempFolder)
// This is where we will look for the downloaded syslog
localSyslogLocation := filepath.Join(localDestinationDirectory, publicInstanceIP, "testFolder", remoteTempFileName)
//Create a RemoteFileSpecification for our test ASG
//We will specify that we'd like to grab /var/log/syslog
//and store that locally.
spec := aws.RemoteFileSpecification{
SshUser: sshUserName,
UseSudo: true,
KeyPair: keyPair,
AsgNames: []string{asgName},
RemotePathToFileFilter: map[string][]string{
remoteTempFolder: {remoteTempFileName},
},
LocalDestinationDir: localDestinationDirectory,
}
// Go and SCP the test file from EC2 instance
aws.FetchFilesFromAsgsE(t, awsRegion, spec)
// Clean up the temp file we created
defer os.RemoveAll(localDestinationDirectory)
//Read the locally copied syslog
buf, err := ioutil.ReadFile(localSyslogLocation)
if err != nil {
t.Fatalf("Error: Unable to read local file from disk: %s", err.Error())
}
localFileContents := string(buf)
assert.Contains(t, localFileContents, randomData)
}
func writeSampleDataToInstance(t *testing.T, publicInstanceIP string, sshUserName string, keyPair *aws.Ec2Keypair) (string, string) {
// 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: sshUserName,
}
// 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)
remoteTempFolder := "/tmp/testFolder"
remoteTempFilePath := filepath.Join(remoteTempFolder, "test.foo")
remoteTempFilePath2 := filepath.Join(remoteTempFolder, "test.baz")
randomData := random.UniqueId()
// Verify that we can SSH to the Instance and run commands
retry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {
_, err := ssh.CheckSshCommandE(t, publicHost, fmt.Sprintf("mkdir -p %s && touch %s && touch %s && echo \"%s\" >> %s", remoteTempFolder, remoteTempFilePath, remoteTempFilePath2, randomData, remoteTempFilePath))
if err != nil {
return "", err
}
return "", nil
})
return randomData, remoteTempFilePath
}
func cleanup(t *testing.T, publicInstanceIP string, sshUserName string, keyPair *aws.Ec2Keypair, folderToClean string) {
publicHost := ssh.Host{
Hostname: publicInstanceIP,
SshKeyPair: keyPair.KeyPair,
SshUserName: sshUserName,
}
maxRetries := 30
timeBetweenRetries := 5 * time.Second
description := fmt.Sprintf("SSH to public host %s", publicInstanceIP)
// clean up the remote folder as we want may want to run another test case
defer retry.DoWithRetry(t, description, maxRetries, timeBetweenRetries, func() (string, error) {
_, err := ssh.CheckSshCommandE(t,
publicHost,
fmt.Sprintf("rm -rf %s", folderToClean))
if err != nil {
return "", err
}
return "", nil
})
}