|
| 1 | +// Package ssm implements common SSM utilities. |
| 2 | +package ssm |
| 3 | + |
| 4 | +import ( |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/aws/aws-sdk-go/aws" |
| 8 | + "github.com/aws/aws-sdk-go/service/ssm" |
| 9 | + "github.com/aws/aws-sdk-go/service/ssm/ssmiface" |
| 10 | + "go.uber.org/zap" |
| 11 | +) |
| 12 | + |
| 13 | +// FetchConfig is the SSM fetch configuration. |
| 14 | +type FetchConfig struct { |
| 15 | + Logger *zap.Logger |
| 16 | + SSMAPI ssmiface.SSMAPI |
| 17 | + DocumentName string |
| 18 | + InvokedAfter time.Time |
| 19 | + BatchLimit int64 |
| 20 | + BatchInterval time.Duration |
| 21 | +} |
| 22 | + |
| 23 | +const rfc3339Micro = "2006-01-02T15:04:05.999Z07:00" |
| 24 | + |
| 25 | +// FetchOutputs downloads SSM doc run outputs. |
| 26 | +// It only returns the invocation whose status is "Success". |
| 27 | +// e.g. aws ssm list-command-invocations --details --filter key=DocumentName,value=ResourceCounterSSMDocDevStack |
| 28 | +func FetchOutputs(cfg FetchConfig) (ivs []*ssm.CommandInvocation, err error) { |
| 29 | + cfg.Logger.Info("fetching SSM doc outputs", zap.String("document-name", cfg.DocumentName), zap.Int64("batch-limit", cfg.BatchLimit)) |
| 30 | + input := &ssm.ListCommandInvocationsInput{ |
| 31 | + Details: aws.Bool(true), |
| 32 | + MaxResults: aws.Int64(cfg.BatchLimit), |
| 33 | + Filters: []*ssm.CommandFilter{ |
| 34 | + { |
| 35 | + Key: aws.String("DocumentName"), |
| 36 | + Value: aws.String(cfg.DocumentName), |
| 37 | + }, |
| 38 | + { |
| 39 | + Key: aws.String("InvokedAfter"), |
| 40 | + Value: aws.String(cfg.InvokedAfter.Format(rfc3339Micro)), |
| 41 | + }, |
| 42 | + }, |
| 43 | + } |
| 44 | + var output *ssm.ListCommandInvocationsOutput |
| 45 | + for { |
| 46 | + output, err = cfg.SSMAPI.ListCommandInvocations(input) |
| 47 | + if err != nil { |
| 48 | + cfg.Logger.Warn("failed to fetch SSM doc outputs", zap.Error(err)) |
| 49 | + return nil, err |
| 50 | + } |
| 51 | + rs := output.CommandInvocations |
| 52 | + n := len(rs) |
| 53 | + if n == 0 { |
| 54 | + break |
| 55 | + } |
| 56 | + for _, rv := range rs { |
| 57 | + if aws.StringValue(rv.Status) == "Success" { |
| 58 | + ivs = append(ivs, rv) |
| 59 | + } |
| 60 | + } |
| 61 | + token := aws.StringValue(output.NextToken) |
| 62 | + input.NextToken = aws.String(token) |
| 63 | + cfg.Logger.Info("received SSM command invocation outputs", zap.Int("received", n), zap.Int("total", len(ivs))) |
| 64 | + if token == "" { |
| 65 | + break |
| 66 | + } |
| 67 | + time.Sleep(cfg.BatchInterval) |
| 68 | + } |
| 69 | + cfg.Logger.Info("fetching SSM doc outputs", zap.Int("total", len(ivs))) |
| 70 | + return ivs, nil |
| 71 | +} |
0 commit comments