Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SSM Association Create Route for Targeting Tags #109

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ vendor
.vscode
debug
.idea/
*.exe
*.exe
# Fresh
tmp/runner-build
66 changes: 66 additions & 0 deletions api/handlers_sgs.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/YaleSpinup/apierror"
"github.com/YaleSpinup/ec2-api/ec2"
"github.com/YaleSpinup/ec2-api/ssm"
"github.com/gorilla/mux"
)

Expand Down Expand Up @@ -227,3 +228,68 @@ func (s *server) SecurityGroupDeleteHandler(w http.ResponseWriter, r *http.Reque

handleResponseOk(w, "OK")
}

func (s *server) SSMAssociationByTagHandler(w http.ResponseWriter, r *http.Request) {
w = LogWriter{w}
vars := mux.Vars(r)
account := s.mapAccountNumber(vars["account"])

req := &SSMAssociationByTagRequest{}
if err := json.NewDecoder(r.Body).Decode(req); err != nil {
msg := fmt.Sprintf("cannot decode body into ssm create input %s", err)
handleError(w, apierror.New(apierror.ErrBadRequest, msg, err))
return
}

// Check for missing values in request body
errMsg := ""
if req.Document == "" {
errMsg = fmt.Sprintf("document is mandatory")
}
if len(req.TagFilters) == 0 {
errMsg = fmt.Sprintf("tagFilters is mandatory")
}
for _, tagValues := range req.TagFilters {
if len(tagValues) == 0 {
errMsg = fmt.Sprintf("You are missing values for one of your tags")
}
}
if errMsg != "" {
handleError(w, apierror.New(apierror.ErrBadRequest, errMsg, nil))
return
}

// Assume role in account
role := fmt.Sprintf("arn:aws:iam::%s:role/%s", account, s.session.RoleName)
policy, err := ssmAssociationPolicy()
if err != nil {
handleError(w, err)
return
}

session, err := s.assumeRole(
r.Context(),
s.session.ExternalID,
role,
policy,
"arn:aws:iam::aws:policy/AmazonSSMReadOnlyAccess",
"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",
)
if err != nil {
msg := fmt.Sprintf("failed to assume role in account: %s", account)
handleError(w, apierror.New(apierror.ErrForbidden, msg, err))
return
}

service := ssm.New(
ssm.WithSession(session.Session),
)

out, err := service.CreateAssociationByTag(r.Context(), req.Name, req.Document, req.DocumentVersion, req.TagFilters, req.Parameters)
if err != nil {
handleError(w, err)
return
}

handleResponseOk(w, out)
}
1 change: 1 addition & 0 deletions api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func (s *server) routes() {
api.HandleFunc("/{account}/instances", s.InstanceCreateHandler).Methods(http.MethodPost)
api.HandleFunc("/{account}/instances/{id}/volumes", s.VolumeAttachHandler).Methods(http.MethodPost)
api.HandleFunc("/{account}/sgs", s.SecurityGroupCreateHandler).Methods(http.MethodPost)
api.HandleFunc("/{account}/ssm/association", s.SSMAssociationByTagHandler).Methods(http.MethodPost)
api.HandleFunc("/{account}/volumes", s.VolumeCreateHandler).Methods(http.MethodPost)
api.HandleFunc("/{account}/snapshots", s.SnapshotCreateHandler).Methods(http.MethodPost)
api.HandleFunc("/{account}/images", s.ImageCreateHandler).Methods(http.MethodPost)
Expand Down
11 changes: 10 additions & 1 deletion api/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package api

import (
"encoding/json"
"github.com/aws/aws-sdk-go/service/iam"
"time"

"github.com/aws/aws-sdk-go/service/iam"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/service/ec2"
Expand Down Expand Up @@ -808,6 +809,14 @@ type SSMAssociationRequest struct {
Document string `json:"document"`
}

type SSMAssociationByTagRequest struct {
Name string `json:"name"`
Document string `json:"document"`
DocumentVersion int `json:"documentVersion"`
TagFilters map[string][]string `json:"tagFilters"`
Parameters map[string][]string `json:"parameters"`
}

type SsmCommandRequest struct {
DocumentName string `json:"document_name"`
Parameters map[string][]*string `json:"parameters"`
Expand Down
57 changes: 57 additions & 0 deletions ssm/association.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ssm

import (
"context"
"strconv"

"github.com/YaleSpinup/apierror"
"github.com/YaleSpinup/ec2-api/common"
Expand Down Expand Up @@ -40,3 +41,59 @@ func (s *SSM) CreateAssociation(ctx context.Context, instanceId, docName string)
log.Debugf("got output creating SSM Association: %+v", out)
return aws.StringValue(out.AssociationDescription.AssociationId), nil
}

func (s *SSM) CreateAssociationByTag(ctx context.Context, associationName string, docName string, docVersion int, tagFilters map[string][]string, parameters map[string][]string) (string, error) {
// Create the Targets structure
targets := []*ssm.Target{}
for tagKey, tagValues := range tagFilters {
if tagKey == "" {
return "", apierror.New(apierror.ErrBadRequest, "tag key cannot be empty", nil)
}
targets = append(targets,
&ssm.Target{
Key: aws.String("tag:" + tagKey),
Values: aws.StringSlice(tagValues),
},
)
}

// Create the input
input := &ssm.CreateAssociationInput{
Name: aws.String(docName),
Targets: targets,
}

// Optionally add fields if present
// Handle optoinal association name
if associationName != "" {
input.AssociationName = aws.String(associationName)
}
// Handle optional document version
if docVersion != 0 {
input.DocumentVersion = aws.String(strconv.Itoa(docVersion))
} else {
input.DocumentVersion = aws.String("$DEFAULT")
}
// Handle optional parameters
if len(parameters) > 0 {
// Conver the parameters from map[string][]string to map[string][]*string
awsParams := make(map[string][]*string)
for key, values := range parameters {
// Convert each string in the slice to *string
var awsValues []*string
for _, val := range values {
awsValues = append(awsValues, aws.String(val))
}
awsParams[key] = awsValues
}
input.Parameters = awsParams
}

out, err := s.Service.CreateAssociationWithContext(ctx, input)
if err != nil {
return "", common.ErrCode("failed to create association", err)
}
log.Debugf("got output creating SSM Association: %+v", out)
log.Info("created association with id: ", aws.StringValue(out.AssociationDescription.AssociationId))
return aws.StringValue(out.AssociationDescription.AssociationId), nil
}
Loading