/
ssm.go
262 lines (216 loc) · 10.1 KB
/
ssm.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
package aws
import (
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/ssm"
"github.com/gruntwork-io/terratest/modules/logger"
"github.com/gruntwork-io/terratest/modules/retry"
"github.com/gruntwork-io/terratest/modules/testing"
"github.com/stretchr/testify/require"
)
// GetParameter retrieves the latest version of SSM Parameter at keyName with decryption.
func GetParameter(t testing.TestingT, awsRegion string, keyName string) string {
keyValue, err := GetParameterE(t, awsRegion, keyName)
require.NoError(t, err)
return keyValue
}
// GetParameterE retrieves the latest version of SSM Parameter at keyName with decryption.
func GetParameterE(t testing.TestingT, awsRegion string, keyName string) (string, error) {
ssmClient, err := NewSsmClientE(t, awsRegion)
if err != nil {
return "", err
}
return GetParameterWithClientE(t, ssmClient, keyName)
}
// GetParameterE retrieves the latest version of SSM Parameter at keyName with decryption with the ability to provide the SSM client.
func GetParameterWithClientE(t testing.TestingT, client *ssm.SSM, keyName string) (string, error) {
resp, err := client.GetParameter(&ssm.GetParameterInput{Name: aws.String(keyName), WithDecryption: aws.Bool(true)})
if err != nil {
return "", err
}
parameter := *resp.Parameter
return *parameter.Value, nil
}
// PutParameter creates new version of SSM Parameter at keyName with keyValue as SecureString.
func PutParameter(t testing.TestingT, awsRegion string, keyName string, keyDescription string, keyValue string) int64 {
version, err := PutParameterE(t, awsRegion, keyName, keyDescription, keyValue)
require.NoError(t, err)
return version
}
// PutParameterE creates new version of SSM Parameter at keyName with keyValue as SecureString.
func PutParameterE(t testing.TestingT, awsRegion string, keyName string, keyDescription string, keyValue string) (int64, error) {
ssmClient, err := NewSsmClientE(t, awsRegion)
if err != nil {
return 0, err
}
return PutParameterWithClientE(t, ssmClient, keyName, keyDescription, keyValue)
}
// PutParameterE creates new version of SSM Parameter at keyName with keyValue as SecureString with the ability to provide the SSM client.
func PutParameterWithClientE(t testing.TestingT, client *ssm.SSM, keyName string, keyDescription string, keyValue string) (int64, error) {
resp, err := client.PutParameter(&ssm.PutParameterInput{Name: aws.String(keyName), Description: aws.String(keyDescription), Value: aws.String(keyValue), Type: aws.String("SecureString")})
if err != nil {
return 0, err
}
return *resp.Version, nil
}
// DeleteParameter deletes all versions of SSM Parameter at keyName.
func DeleteParameter(t testing.TestingT, awsRegion string, keyName string) {
err := DeleteParameterE(t, awsRegion, keyName)
require.NoError(t, err)
}
// DeleteParameterE deletes all versions of SSM Parameter at keyName.
func DeleteParameterE(t testing.TestingT, awsRegion string, keyName string) error {
ssmClient, err := NewSsmClientE(t, awsRegion)
if err != nil {
return err
}
return DeleteParameterWithClientE(t, ssmClient, keyName)
}
// DeleteParameterE deletes all versions of SSM Parameter at keyName with the ability to provide the SSM client.
func DeleteParameterWithClientE(t testing.TestingT, client *ssm.SSM, keyName string) error {
_, err := client.DeleteParameter(&ssm.DeleteParameterInput{Name: aws.String(keyName)})
if err != nil {
return err
}
return nil
}
// NewSsmClient creates a SSM client.
func NewSsmClient(t testing.TestingT, region string) *ssm.SSM {
client, err := NewSsmClientE(t, region)
require.NoError(t, err)
return client
}
// NewSsmClientE creates an SSM client.
func NewSsmClientE(t testing.TestingT, region string) (*ssm.SSM, error) {
sess, err := NewAuthenticatedSession(region)
if err != nil {
return nil, err
}
return ssm.New(sess), nil
}
// WaitForSsmInstanceE waits until the instance get registered to the SSM inventory.
func WaitForSsmInstanceE(t testing.TestingT, awsRegion, instanceID string, timeout time.Duration) error {
client, err := NewSsmClientE(t, awsRegion)
if err != nil {
return err
}
return WaitForSsmInstanceWithClientE(t, client, instanceID, timeout)
}
// WaitForSsmInstanceE waits until the instance get registered to the SSM inventory with the ability to provide the SSM client.
func WaitForSsmInstanceWithClientE(t testing.TestingT, client *ssm.SSM, instanceID string, timeout time.Duration) error {
timeBetweenRetries := 2 * time.Second
maxRetries := int(timeout.Seconds() / timeBetweenRetries.Seconds())
description := fmt.Sprintf("Waiting for %s to appear in the SSM inventory", instanceID)
input := &ssm.GetInventoryInput{
Filters: []*ssm.InventoryFilter{
{
Key: aws.String("AWS:InstanceInformation.InstanceId"),
Type: aws.String("Equal"),
Values: aws.StringSlice([]string{instanceID}),
},
},
}
_, err := retry.DoWithRetryE(t, description, maxRetries, timeBetweenRetries, func() (string, error) {
resp, err := client.GetInventory(input)
if err != nil {
return "", err
}
if len(resp.Entities) != 1 {
return "", fmt.Errorf("%s is not in the SSM inventory", instanceID)
}
return "", nil
})
return err
}
// WaitForSsmInstance waits until the instance get registered to the SSM inventory.
func WaitForSsmInstance(t testing.TestingT, awsRegion, instanceID string, timeout time.Duration) {
err := WaitForSsmInstanceE(t, awsRegion, instanceID, timeout)
require.NoError(t, err)
}
// CheckSsmCommand checks that you can run the given command on the given instance through AWS SSM.
func CheckSsmCommand(t testing.TestingT, awsRegion, instanceID, command string, timeout time.Duration) *CommandOutput {
return CheckSsmCommandWithDocument(t, awsRegion, instanceID, command, "AWS-RunShellScript", timeout)
}
// CommandOutput contains the result of the SSM command.
type CommandOutput struct {
Stdout string
Stderr string
ExitCode int64
}
// CheckSsmCommandE checks that you can run the given command on the given instance through AWS SSM. Returns the result and an error if one occurs.
func CheckSsmCommandE(t testing.TestingT, awsRegion, instanceID, command string, timeout time.Duration) (*CommandOutput, error) {
return CheckSsmCommandWithDocumentE(t, awsRegion, instanceID, command, "AWS-RunShellScript", timeout)
}
// CheckSSMCommandWithClientE checks that you can run the given command on the given instance through AWS SSM with the ability to provide the SSM client. Returns the result and an error if one occurs.
func CheckSSMCommandWithClientE(t testing.TestingT, client *ssm.SSM, instanceID, command string, timeout time.Duration) (*CommandOutput, error) {
return CheckSSMCommandWithClientWithDocumentE(t, client, instanceID, command, "AWS-RunShellScript", timeout)
}
// CheckSsmCommandWithDocument checks that you can run the given command on the given instance through AWS SSM with specified Command Doc type.
func CheckSsmCommandWithDocument(t testing.TestingT, awsRegion, instanceID, command string, commandDocName string, timeout time.Duration) *CommandOutput {
result, err := CheckSsmCommandWithDocumentE(t, awsRegion, instanceID, command, commandDocName, timeout)
require.NoErrorf(t, err, "failed to execute '%s' on %s (%v):]\n stdout: %#v\n stderr: %#v", command, instanceID, err, result.Stdout, result.Stderr)
return result
}
// CheckSsmCommandWithDocumentE checks that you can run the given command on the given instance through AWS SSM with specified Command Doc type. Returns the result and an error if one occurs.
func CheckSsmCommandWithDocumentE(t testing.TestingT, awsRegion, instanceID, command string, commandDocName string, timeout time.Duration) (*CommandOutput, error) {
logger.Logf(t, "Running command '%s' on EC2 instance with ID '%s'", command, instanceID)
// Now that we know the instance in the SSM inventory, we can send the command
client, err := NewSsmClientE(t, awsRegion)
if err != nil {
return nil, err
}
return CheckSSMCommandWithClientWithDocumentE(t, client, instanceID, command, commandDocName, timeout)
}
// CheckSSMCommandWithClientWithDocumentE checks that you can run the given command on the given instance through AWS SSM with the ability to provide the SSM client with specified Command Doc type. Returns the result and an error if one occurs.
func CheckSSMCommandWithClientWithDocumentE(t testing.TestingT, client *ssm.SSM, instanceID, command string, commandDocName string, timeout time.Duration) (*CommandOutput, error) {
timeBetweenRetries := 2 * time.Second
maxRetries := int(timeout.Seconds() / timeBetweenRetries.Seconds())
resp, err := client.SendCommand(&ssm.SendCommandInput{
Comment: aws.String("Terratest SSM"),
DocumentName: aws.String(commandDocName),
InstanceIds: aws.StringSlice([]string{instanceID}),
Parameters: map[string][]*string{
"commands": aws.StringSlice([]string{command}),
},
})
if err != nil {
return nil, err
}
// Wait for the result
description := "Waiting for the result of the command"
retryableErrors := map[string]string{
"InvocationDoesNotExist": "InvocationDoesNotExist",
"bad status: Pending": "bad status: Pending",
"bad status: InProgress": "bad status: InProgress",
"bad status: Delayed": "bad status: Delayed",
}
result := &CommandOutput{}
_, err = retry.DoWithRetryableErrorsE(t, description, retryableErrors, maxRetries, timeBetweenRetries, func() (string, error) {
resp, err := client.GetCommandInvocation(&ssm.GetCommandInvocationInput{
CommandId: resp.Command.CommandId,
InstanceId: &instanceID,
})
if err != nil {
return "", err
}
result.Stderr = aws.StringValue(resp.StandardErrorContent)
result.Stdout = aws.StringValue(resp.StandardOutputContent)
result.ExitCode = aws.Int64Value(resp.ResponseCode)
status := aws.StringValue(resp.Status)
if status == ssm.CommandInvocationStatusSuccess {
return "", nil
}
if status == ssm.CommandInvocationStatusFailed {
return "", fmt.Errorf(aws.StringValue(resp.StatusDetails))
}
return "", fmt.Errorf("bad status: %s", status)
})
if err != nil {
if actualErr, ok := err.(retry.FatalError); ok {
return result, actualErr.Underlying
}
return result, fmt.Errorf("unexpected error: %v", err)
}
return result, nil
}