/
ssm.go
348 lines (282 loc) · 7.41 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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package aws
import (
"context"
"fmt"
"io"
"strings"
"text/tabwriter"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/ssm"
"github.com/aws/aws-sdk-go-v2/service/ssm/types"
)
// SSM client struct
type SSM struct {
Client *ssm.Client
}
// NewSsmSess return SSM struct initialized
func NewSsmClient(profile, region string) *SSM {
return &SSM{
Client: ssm.NewFromConfig(GetSession(profile, region)),
}
}
// Session ssm session history struct
type Session struct {
SessionId string
Owner string
Target string
StartDate string
EndDate string
}
// Sessions Session struct slice
type Sessions []Session
// Response sendcommand response struct
type Response struct {
InstanceId string `json:"instance_id"`
Status string `json:"status"`
Output []string `json:"output"`
}
// Responses Response struct slice
type Responses []Response
// CmdLog sendcommand log struct
type CmdLog struct {
DocumentName string
Commands string
Targets string
Status string
RequestedDateTime string
}
// CmdLogs CommandLog struct slice
type CmdLogs []CmdLog
// Parameter parameter store struct
type Parameter struct {
Name string
Value string
Description string
}
// Parameters Parameter struct slice
type Parameters []Parameter
// DescribeInstanceInformation return []string (ssm.DescribeInstanceInformationOutput.InstanceId)
// input ssm.DescribeInstanceInformationInput
func (c *SSM) DescribeInstanceInformation(input *ssm.DescribeInstanceInformationInput) ([]string, error) {
ids := []string{}
paginator := ssm.NewDescribeInstanceInformationPaginator(c.Client, input)
for paginator.HasMorePages() {
page, err := paginator.NextPage(context.Background())
if err != nil {
return nil, fmt.Errorf("describe instance information: %v", err)
}
for _, i := range page.InstanceInformationList {
ids = append(ids, *i.InstanceId)
}
}
return ids, nil
}
// CreateStartSession return ssm.StartSessionOutput, string ()
// input ssm.DescribeInstanceInformationInput
func (c *SSM) StartSession(input *ssm.StartSessionInput) (*ssm.StartSessionOutput, error) {
subctx, cancel := context.WithTimeout(context.Background(), time.Second*15)
defer cancel()
sess, err := c.Client.StartSession(subctx, input)
if err != nil {
return nil, fmt.Errorf("start session: %v", err)
}
return sess, nil
}
// DeleteStartSession return none (Only error)
// input ssm.TerminateSessionInput
func (c *SSM) DeleteSession(input *ssm.TerminateSessionInput) error {
subctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
if _, err := c.Client.TerminateSession(subctx, input); err != nil {
return fmt.Errorf("terminate session: %v", err)
}
return nil
}
// SendCommand return ssm.SendCommandOutput
// input ssm.SendCommandInput
func (c *SSM) SendCommand(input *ssm.SendCommandInput) (*ssm.SendCommandOutput, error) {
output, err := c.Client.SendCommand(context.TODO(), input)
if err != nil {
return nil, fmt.Errorf("command send: %v", err)
}
return output, nil
}
// ListCommandInvocations return Responses
// input ssm.ListCommandInvocationsInput
func (c *SSM) ListCommandInvocations(input *ssm.ListCommandInvocationsInput) (Responses, error) {
resp := Responses{}
for {
output, err := c.Client.ListCommandInvocations(context.TODO(), input)
if err != nil {
return nil, fmt.Errorf("list command invocation: %v", err)
}
if len(output.CommandInvocations) == 0 {
time.Sleep(100 * time.Millisecond)
continue
}
inprogress := false
for _, ci := range output.CommandInvocations {
if ci.Status == "InProgress" {
inprogress = true
break
}
}
if inprogress {
time.Sleep(100 * time.Millisecond)
continue
}
for _, ci := range output.CommandInvocations {
out := *ci.CommandPlugins[0].Output
spl := strings.Split(out, "\n")
if len(spl[len(spl)-1]) < 1 {
spl = spl[:len(spl)-1]
}
res := Response{
InstanceId: *ci.InstanceId,
Status: string(ci.Status),
Output: spl,
}
resp = append(resp, res)
if len(out) < 2500 {
continue
}
res.Output = spl
}
break
}
return resp, nil
}
// DescribeParameters return []*ssm.Parameters
// input ssm.DescribeParametersInput
func (c *SSM) DescribeParameters(input *ssm.DescribeParametersInput) ([]types.ParameterMetadata, error) {
var params []types.ParameterMetadata
paginator := ssm.NewDescribeParametersPaginator(c.Client, input)
for paginator.HasMorePages() {
page, err := paginator.NextPage(context.Background())
if err != nil {
return nil, fmt.Errorf("describe paramaters: %v", err)
}
params = append(params, page.Parameters...)
}
if len(params) == 0 {
return nil, fmt.Errorf("no parameters")
}
return params, nil
}
// GetParameter return Parameters
// input []*ssm.ParameterMetadata
func (c *SSM) GetParameter(params []types.ParameterMetadata) (Parameters, error) {
list := Parameters{}
for _, p := range params {
input := &ssm.GetParameterInput{
Name: aws.String(*p.Name),
}
output, err := c.Client.GetParameter(context.TODO(), input)
if err != nil {
return nil, fmt.Errorf("get parameter: %v", err)
}
description := "None"
if p.Description != nil {
description = *p.Description
}
list = append(list, Parameter{
Name: *p.Name,
Value: *output.Parameter.Value,
Description: description,
})
}
return list, nil
}
func PrintSessHist(wrt io.Writer, resources Sessions) error {
w := tabwriter.NewWriter(wrt, 0, 8, 1, ' ', 0)
header := []string{
"SessionId",
"Owner",
"Target",
"StartDate",
"EndDate",
}
if _, err := fmt.Fprintln(w, strings.Join(header, "\t")); err != nil {
return fmt.Errorf("%v", err)
}
for _, r := range resources {
if _, err := fmt.Fprintln(w, r.HistTabString()); err != nil {
return fmt.Errorf("%v", err)
}
}
if err := w.Flush(); err != nil {
return fmt.Errorf("%v", err)
}
return nil
}
func (i *Session) HistTabString() string {
fields := []string{
i.SessionId,
i.Owner,
i.Target,
i.StartDate,
i.EndDate,
}
return strings.Join(fields, "\t")
}
func PrintCmdLogs(wrt io.Writer, resources CmdLogs) error {
w := tabwriter.NewWriter(wrt, 0, 8, 1, ' ', 0)
header := []string{
"DocumentName",
"Commands",
"Targets",
"Status",
"RequestedDateTime",
}
if _, err := fmt.Fprintln(w, strings.Join(header, "\t")); err != nil {
return fmt.Errorf("%v", err)
}
for _, r := range resources {
if _, err := fmt.Fprintln(w, r.CmdLogTabString()); err != nil {
return fmt.Errorf("%v", err)
}
}
if err := w.Flush(); err != nil {
return fmt.Errorf("%v", err)
}
return nil
}
func (i *CmdLog) CmdLogTabString() string {
fields := []string{
i.DocumentName,
i.Commands,
i.Targets,
i.Status,
i.RequestedDateTime,
}
return strings.Join(fields, "\t")
}
func PrintParameters(wrt io.Writer, resources Parameters) error {
w := tabwriter.NewWriter(wrt, 0, 8, 1, ' ', 0)
header := []string{
"Name",
"Value",
"Description",
}
if _, err := fmt.Fprintln(w, strings.Join(header, "\t")); err != nil {
return fmt.Errorf("%v", err)
}
for _, r := range resources {
if _, err := fmt.Fprintln(w, r.ParameterTabString()); err != nil {
return fmt.Errorf("%v", err)
}
}
if err := w.Flush(); err != nil {
return fmt.Errorf("%v", err)
}
return nil
}
func (i *Parameter) ParameterTabString() string {
fields := []string{
i.Name,
i.Value,
i.Description,
}
return strings.Join(fields, "\t")
}