Skip to content

Instantly share code, notes, and snippets.

@deepthawtz
Last active November 14, 2017 11:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepthawtz/8726d3d0efe4fb48d01180074fa818f9 to your computer and use it in GitHub Desktop.
Save deepthawtz/8726d3d0efe4fb48d01180074fa818f9 to your computer and use it in GitHub Desktop.
wrote this utility to copy AWS tags from EC2 instances to the EBS volumes they mount
package main
import (
"fmt"
"log"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
)
type tag struct {
Key string
Value string
}
func main() {
for _, r := range []string{"us-east-1", "us-west-1"} {
tagVolumesInRegion(r)
}
}
func tagVolumesInRegion(r string) {
svc := ec2.New(session.New(), &aws.Config{Region: aws.String(r)})
err := svc.DescribeInstancesPages(nil, func(page *ec2.DescribeInstancesOutput, lastPage bool) bool {
for _, r := range page.Reservations {
for _, i := range r.Instances {
var tags []tag
for _, t := range i.Tags {
if *t.Key == "Environment" || *t.Key == "CC" {
ts := tag{Key: *t.Key, Value: *t.Value}
tags = append(tags, ts)
}
}
if len(tags) == 0 {
fmt.Printf("[%s] in region %s has no CC or Environment tags\n", *i.InstanceId, r)
continue
}
for _, v := range i.BlockDeviceMappings {
var tagsToAdd []*ec2.Tag
for _, t := range tags {
tagsToAdd = append(tagsToAdd, &ec2.Tag{Key: aws.String(t.Key), Value: aws.String(t.Value)})
}
fmt.Printf("adding tags %s to volume %s.........", tags, *v.Ebs.VolumeId)
resp, err := svc.CreateTags(&ec2.CreateTagsInput{
Resources: []*string{
aws.String(*v.Ebs.VolumeId),
},
Tags: tagsToAdd,
// DryRun: aws.Bool(true),
})
if err != nil {
fmt.Println("failure in CreateTags", err)
fmt.Println(resp)
}
fmt.Printf("DONE\n")
time.Sleep(500 * time.Millisecond) // to keep under rate limit
}
}
}
return lastPage == false
})
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment