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

Tags for volumes in an Instance #35

Merged
merged 6 commits into from
Jun 16, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
29 changes: 11 additions & 18 deletions api/handlers_instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,38 +518,31 @@ func (s *server) InstanceUpdateHandler(w http.ResponseWriter, r *http.Request) {
return
}

role := fmt.Sprintf("arn:aws:iam::%s:role/%s", account, s.session.RoleName)
policy, err := instanceUpdatePolicy()
policy, err := generatePolicy([]string{"ec2:CreateTags", "ec2:ModifyInstanceAttribute"})
if err != nil {
handleError(w, err)
return
}

session, err := s.assumeRole(
r.Context(),
s.session.ExternalID,
role,
policy,
"arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess",
)
orch, err := s.newEc2Orchestrator(r.Context(), &sessionParams{
role: fmt.Sprintf("arn:aws:iam::%s:role/%s", account, s.session.RoleName),
inlinePolicy: policy,
policyArns: []string{
"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))
handleError(w, err)
return
}

service := ec2.New(
ec2.WithSession(session.Session),
ec2.WithOrg(s.org),
)

if len(req.Tags) > 0 {
if err := service.UpdateTags(r.Context(), req.Tags, instanceId); err != nil {
if err := orch.updateInstanceTags(r.Context(), req.Tags, instanceId); err != nil {
handleError(w, err)
return
}
} else if len(req.InstanceType) > 0 {
if err := service.UpdateAttributes(r.Context(), req.InstanceType["value"], instanceId); err != nil {
if err := orch.ec2Client.UpdateAttributes(r.Context(), req.InstanceType["value"], instanceId); err != nil {
handleError(w, err)
return
}
Expand Down
35 changes: 35 additions & 0 deletions api/orchestration_instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"strings"

"github.com/YaleSpinup/apierror"
"github.com/YaleSpinup/ec2-api/common"
"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 @@ -131,3 +132,37 @@ func (o *ssmOrchestrator) sendInstancesCommand(ctx context.Context, req *SsmComm
}
return aws.StringValue(cmd.CommandId), nil
}
func (o *ec2Orchestrator) updateInstanceTags(ctx context.Context, rawTags map[string]string, ids ...string) error {
if len(ids) == 0 || len(rawTags) == 0 {
return apierror.New(apierror.ErrBadRequest, "invalid input", nil)
}
var tags []*ec2.Tag
for key, val := range rawTags {
tags = append(tags, &ec2.Tag{Key: aws.String(key), Value: aws.String(val)})
}

volumeIds := []string{}
for _, id := range ids {
if strings.HasPrefix(id, "i-") {
vIds, err := o.ec2Client.ListInstanceVolumes(ctx, id)
if err != nil {
return common.ErrCode("describing volumes for instance", err)
}
volumeIds = append(volumeIds, vIds...)
}
}

ids = append(ids, volumeIds...)
log.Infof("updating resources: %v with tags %+v", ids, tags)

input := ec2.CreateTagsInput{
Resources: aws.StringSlice(ids),
Tags: tags,
}

if err := o.ec2Client.UpdateInstanceTags(ctx, &input); err != nil {
return err
}

return nil
}
24 changes: 0 additions & 24 deletions api/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -289,30 +289,6 @@ func sendCommandPolicy() (string, error) {
return string(j), nil
}

func instanceUpdatePolicy() (string, error) {
log.Debugf("generating tag create policy document")
policy := iam.PolicyDocument{
Version: "2012-10-17",
Statement: []iam.StatementEntry{
{
Effect: "Allow",
Action: []string{
"ec2:CreateTags",
"ec2:ModifyInstanceAttribute",
},
Resource: []string{"*"},
},
},
}

j, err := json.Marshal(policy)
if err != nil {
return "", err
}

return string(j), nil
}

func ssmAssociationPolicy() (string, error) {
log.Debugf("generating tag create policy document")
policy := iam.PolicyDocument{
Expand Down
52 changes: 14 additions & 38 deletions ec2/tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package ec2

import (
"context"
"strings"

"github.com/YaleSpinup/apierror"
"github.com/YaleSpinup/ec2-api/common"
Expand All @@ -20,43 +19,6 @@ func (e *Ec2) UpdateTags(ctx context.Context, rawTags map[string]string, ids ...
tags = append(tags, &ec2.Tag{Key: aws.String(key), Value: aws.String(val)})
}

instanceIDs := []*string{}
for _, id := range ids {
if strings.HasPrefix(id, "i-") {
instanceIDs = append(instanceIDs, aws.String(id))
}
}

describeVolumesInput := ec2.DescribeVolumesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("attachment.instance-id"),
Values: instanceIDs,
},
},
MaxResults: aws.Int64(1000),
}

for {
out, err := e.Service.DescribeVolumesWithContext(ctx, &describeVolumesInput)
if err != nil {
return common.ErrCode("describing volumes for instance", err)
}

log.Debugf("got describe volumes output %+v", out)

for _, v := range out.Volumes {
ids = append(ids, aws.StringValue(v.VolumeId))
}

if out.NextToken != nil {
describeVolumesInput.NextToken = out.NextToken
continue
}

break
}

log.Infof("updating resources: %v with tags %+v", ids, tags)

input := ec2.CreateTagsInput{
Expand All @@ -70,3 +32,17 @@ func (e *Ec2) UpdateTags(ctx context.Context, rawTags map[string]string, ids ...

return nil
}

func (e *Ec2) UpdateInstanceTags(ctx context.Context, input *ec2.CreateTagsInput) error {
nvnyale marked this conversation as resolved.
Show resolved Hide resolved
if input == nil {
return apierror.New(apierror.ErrBadRequest, "invalid input", nil)
}

log.Infof("updating tags: %v", input)

if _, err := e.Service.CreateTagsWithContext(ctx, input); err != nil {
return common.ErrCode("creating tags", err)
}

return nil
}
65 changes: 65 additions & 0 deletions ec2/tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,68 @@ func TestEc2_UpdateTags(t *testing.T) {
})
}
}
func TestEc2_UpdateInstanceTags(t *testing.T) {
type fields struct {
Service ec2iface.EC2API
}
type args struct {
ctx context.Context
input *ec2.CreateTagsInput
}
tests := []struct {
name string
fields fields
args args
wantErr bool
}{
{
name: "success case",
args: args{ctx: context.TODO(), input: &ec2.CreateTagsInput{
Resources: aws.StringSlice(inpIds),
Tags: expTags}},
fields: fields{Service: newmockEC2Client(t, nil)},
wantErr: false,
},
{
name: "aws error",
args: args{ctx: context.TODO(), input: &ec2.CreateTagsInput{
Resources: aws.StringSlice(inpIds),
Tags: expTags}},
fields: fields{Service: newmockEC2Client(t, awserr.New("Bad Request", "boom.", nil))},
wantErr: true,
},
{
name: "no tags",
fields: fields{Service: newmockEC2Client(t, nil)},
args: args{ctx: context.TODO(), input: &ec2.CreateTagsInput{
Resources: aws.StringSlice(inpIds),
Tags: nil}},
wantErr: true,
},
{
name: "no ids",
fields: fields{Service: newmockEC2Client(t, nil)},
args: args{ctx: context.TODO(), input: &ec2.CreateTagsInput{
Resources: aws.StringSlice([]string{}),
Tags: expTags}},
wantErr: true,
},
{
name: "no input",
fields: fields{Service: newmockEC2Client(t, nil)},
args: args{ctx: context.TODO(), input: nil},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
e := &Ec2{
Service: tt.fields.Service,
}
if err := e.UpdateInstanceTags(tt.args.ctx, tt.args.input); (err != nil) != tt.wantErr {
t.Errorf("Ec2.UpdateTags() error = %v, wantErr %v", err, tt.wantErr)
return
}
})
}
}