forked from gruntwork-io/terraform-google-network
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmanagement_network_test.go
275 lines (227 loc) · 10.3 KB
/
management_network_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
package test
import (
"fmt"
"path/filepath"
"strings"
"testing"
"time"
"github.com/gruntwork-io/terratest/modules/gcp"
"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"
)
func TestNetworkManagement(t *testing.T) {
t.Parallel()
//os.Setenv("SKIP_bootstrap", "true")
//os.Setenv("SKIP_deploy", "true")
//os.Setenv("SKIP_validate_outputs", "true")
//os.Setenv("SKIP_ssh_tests", "true")
//os.Setenv("SKIP_teardown", "true")
_examplesDir := test_structure.CopyTerraformFolderToTemp(t, "../", "examples")
exampleDir := filepath.Join(_examplesDir, "network-management")
test_structure.RunTestStage(t, "bootstrap", func() {
projectId := gcp.GetGoogleProjectIDFromEnvVar(t)
region := getRandomRegion(t, projectId)
terraformOptions := createNetworkManagementTerraformOptions(t, strings.ToLower(random.UniqueId()), projectId, region, exampleDir)
test_structure.SaveTerraformOptions(t, exampleDir, terraformOptions)
test_structure.SaveString(t, exampleDir, KEY_PROJECT, projectId)
})
// 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, exampleDir)
terraform.Destroy(t, terraformOptions)
})
test_structure.RunTestStage(t, "deploy", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, exampleDir)
terraform.InitAndApply(t, terraformOptions)
})
/*
Test Outputs
*/
// Guarantee that we see expected values from state
test_structure.RunTestStage(t, "validate_outputs", func() {
terraformOptions := test_structure.LoadTerraformOptions(t, exampleDir)
var stateValues = []struct {
outputKey string
expectedValue string
// With two string insertion points
message string
}{
// Testing the cidr block itself is just reading the value out of the Terraform config;
// by testing the gateway addresses, we've confirmed that the API had allocated the correct
// block, although not necessarily the correct size.
{"public_subnetwork_gateway", "10.0.0.1", "expected a public gateway of %s but saw %s"},
{"private_subnetwork_gateway", "10.0.16.1", "expected a public gateway of %s but saw %s"},
// Network tags as interpolation targets
{"public", "public", "expected a tag of %s but saw %s"},
{"private", "private", "expected a tag of %s but saw %s"},
{"private_persistence", "private-persistence", "expected a tag of %s but saw %s"},
}
for _, tt := range stateValues {
t.Run(tt.outputKey, func(t *testing.T) {
value, err := terraform.OutputE(t, terraformOptions, tt.outputKey)
if err != nil {
t.Errorf("could not find %s in outputs: %s", tt.outputKey, err)
}
if value != tt.expectedValue {
t.Errorf(tt.message, tt.expectedValue, value)
}
})
}
})
/*
Test SSH
*/
test_structure.RunTestStage(t, "ssh_tests", func() {
project := test_structure.LoadString(t, exampleDir, KEY_PROJECT)
terraformOptions := test_structure.LoadTerraformOptions(t, exampleDir)
external := FetchFromOutput(t, terraformOptions, project, "instance_default_network")
publicWithIp := FetchFromOutput(t, terraformOptions, project, "instance_public_with_ip")
publicWithoutIp := FetchFromOutput(t, terraformOptions, project, "instance_public_without_ip")
privatePublic := FetchFromOutput(t, terraformOptions, project, "instance_private_public")
private := FetchFromOutput(t, terraformOptions, project, "instance_private")
privatePersistence := FetchFromOutput(t, terraformOptions, project, "instance_private_persistence")
keyPair := ssh.GenerateRSAKeyPair(t, 2048)
sshUsername := "terratest"
// Attach the SSH Key to each instances so we can access them at will later
for _, v := range []*gcp.Instance{external, publicWithIp, publicWithoutIp, privatePublic, private, privatePersistence} {
// Adding instance metadata uses a shared fingerprint per-project, and it's (slightly) eventually consistent.
// This means we'll get an error on mismatch, so we can try a few times and make sure we get it right.
retry.DoWithRetry(t, "Adding SSH Key", 20, 1*time.Second, func() (string, error) {
err := v.AddSshKeyE(t, sshUsername, keyPair.PublicKey)
return "", err
})
}
// "external internet" settings pulled from the instance in the default network
externalHost := ssh.Host{
Hostname: external.GetPublicIp(t),
SshKeyPair: keyPair,
SshUserName: sshUsername,
}
// We can SSH to the public instance w/ an IP
publicWithIpHost := ssh.Host{
Hostname: publicWithIp.GetPublicIp(t),
SshKeyPair: keyPair,
SshUserName: sshUsername,
}
// The public instance w/ no IP can't be accessed directly but can through a bastion
if _, err := publicWithoutIp.GetPublicIpE(t); err == nil {
t.Errorf("Found an external IP on %s when it should have had none", publicWithoutIp.Name)
}
publicWithoutIpHost := ssh.Host{
Hostname: publicWithoutIp.Name,
SshKeyPair: keyPair,
SshUserName: sshUsername,
}
// The private instance tagged public w/ no IP can't be accessed directly but can through a bastion
if _, err := privatePublic.GetPublicIpE(t); err == nil {
t.Errorf("Found an external IP on %s when it should have had none", privatePublic.Name)
}
privatePublicHost := ssh.Host{
Hostname: privatePublic.Name,
SshKeyPair: keyPair,
SshUserName: sshUsername,
}
// The private instance [in a private subnetwork] w/ no IP can't be accessed directly but can through a bastion
if _, err := private.GetPublicIpE(t); err == nil {
t.Errorf("Found an external IP on %s when it should have had none", private.Name)
}
privateHost := ssh.Host{
Hostname: private.Name,
SshKeyPair: keyPair,
SshUserName: sshUsername,
}
// The private-persistence instance [in a private subnetwork] w/ no IP can't be accessed directly but can through a bastion from a private instance
if _, err := privatePersistence.GetPublicIpE(t); err == nil {
t.Errorf("Found an external IP on %s when it should have had none", privatePersistence.Name)
}
privatePersistenceHost := ssh.Host{
Hostname: privatePersistence.Name,
SshKeyPair: keyPair,
SshUserName: sshUsername,
}
sshChecks := []SSHCheck{
// Success
{"public", func(t *testing.T) { testSSHOn1Host(t, ExpectSuccess, publicWithIpHost) }},
{"public to external", func(t *testing.T) { testSSHOn2Hosts(t, ExpectSuccess, publicWithIpHost, externalHost) }},
{"public to public-no-ip", func(t *testing.T) { testSSHOn2Hosts(t, ExpectSuccess, publicWithIpHost, publicWithoutIpHost) }},
{"public to private-public", func(t *testing.T) { testSSHOn2Hosts(t, ExpectSuccess, publicWithIpHost, privatePublicHost) }},
{"public to private", func(t *testing.T) { testSSHOn2Hosts(t, ExpectSuccess, publicWithIpHost, privateHost) }},
// TODO: Add a third jump to terratest to test the following:
// {"public to privatePublic to external", func(t *testing.T) { testSSHOn3Hosts(t, ExpectSuccess, publicWithIpHost, privatePublicHost, externalHost)} },
// {"public to private to private-persistence", func(t *testing.T) { testSSHOn3Hosts(t, ExpectSuccess, publicWithIpHost, privateHost, privatePersistenceHost)} },
// Failure
{"public-no-ip", func(t *testing.T) { testSSHOn1Host(t, ExpectFailure, publicWithoutIpHost) }},
{"private-public", func(t *testing.T) { testSSHOn1Host(t, ExpectFailure, privatePublicHost) }},
{"private", func(t *testing.T) { testSSHOn1Host(t, ExpectFailure, privateHost) }},
{"public to private-persistence", func(t *testing.T) { testSSHOn2Hosts(t, ExpectFailure, publicWithIpHost, privatePersistenceHost) }},
// TODO: Add a third jump to terratest to test the following:
// {"public to private to external", func(t *testing.T) { testSSHOn3Hosts(t, ExpectFailure, publicWithIpHost, privateHost, externalHost)} },
}
// We need to run a series of parallel funcs inside a serial func in order to ensure that defer statements are ran after they've all completed
t.Run("sshConnections", func(t *testing.T) {
for _, check := range sshChecks {
check := check // capture variable in local scope
t.Run(check.Name, func(t *testing.T) {
t.Parallel()
check.Check(t)
})
}
})
})
}
type SSHCheck struct {
Name string
Check func(t *testing.T)
}
func doWithRetryAndTimeoutE(t *testing.T, description string, maxRetries int, sshSleepBetweenRetries time.Duration, timeoutPerRetry time.Duration, action func() (string, error)) (string, error) {
return retry.DoWithRetryE(t, description, maxRetries, sshSleepBetweenRetries, func() (string, error) {
return retry.DoWithTimeoutE(t, description, timeoutPerRetry, action)
})
}
func testSSHOn1Host(t *testing.T, expectSuccess bool, host ssh.Host) {
maxRetries := SSHMaxRetries
if !expectSuccess {
maxRetries = SSHMaxRetriesExpectError
}
_, err := doWithRetryAndTimeoutE(t, "Attempting to SSH", maxRetries, SSHSleepBetweenRetries, SSHTimeout, func() (string, error) {
output, err := ssh.CheckSshCommandE(t, host, fmt.Sprintf("echo '%s'", SSHEchoText))
if err != nil {
return "", err
}
if strings.TrimSpace(SSHEchoText) != strings.TrimSpace(output) {
return "", fmt.Errorf("Expected: %s. Got: %s\n", SSHEchoText, output)
}
return "", nil
})
if err != nil && expectSuccess {
t.Fatalf("Expected success but saw: %s", err)
}
if err == nil && !expectSuccess {
t.Fatalf("Expected an error but saw none.")
}
}
func testSSHOn2Hosts(t *testing.T, expectSuccess bool, publicHost, secondHost ssh.Host) {
maxRetries := SSHMaxRetries
if !expectSuccess {
maxRetries = SSHMaxRetriesExpectError
}
_, err := doWithRetryAndTimeoutE(t, "Attempting to SSH", maxRetries, SSHSleepBetweenRetries, SSHTimeout, func() (string, error) {
output, err := ssh.CheckPrivateSshConnectionE(t, publicHost, secondHost, fmt.Sprintf("echo '%s'", SSHEchoText))
if err != nil {
return "", err
}
if strings.TrimSpace(SSHEchoText) != strings.TrimSpace(output) {
return "", fmt.Errorf("Expected: %s. Got: %s\n", SSHEchoText, output)
}
return "", nil
})
if err != nil && expectSuccess {
t.Fatalf("Expected success but saw: %s", err)
}
if err == nil && !expectSuccess {
t.Fatalf("Expected an error but saw none.")
}
}