github.com/anuaimi/terraform@v0.6.4-0.20150904235404-2bf9aec61da8/builtin/providers/aws/tagsRDS.go (about) 1 package aws 2 3 import ( 4 "log" 5 6 "github.com/aws/aws-sdk-go/aws" 7 "github.com/aws/aws-sdk-go/service/rds" 8 "github.com/hashicorp/terraform/helper/schema" 9 ) 10 11 // setTags is a helper to set the tags for a resource. It expects the 12 // tags field to be named "tags" 13 func setTagsRDS(conn *rds.RDS, d *schema.ResourceData, arn string) error { 14 if d.HasChange("tags") { 15 oraw, nraw := d.GetChange("tags") 16 o := oraw.(map[string]interface{}) 17 n := nraw.(map[string]interface{}) 18 create, remove := diffTagsRDS(tagsFromMapRDS(o), tagsFromMapRDS(n)) 19 20 // Set tags 21 if len(remove) > 0 { 22 log.Printf("[DEBUG] Removing tags: %#v", remove) 23 k := make([]*string, len(remove), len(remove)) 24 for i, t := range remove { 25 k[i] = t.Key 26 } 27 28 _, err := conn.RemoveTagsFromResource(&rds.RemoveTagsFromResourceInput{ 29 ResourceName: aws.String(arn), 30 TagKeys: k, 31 }) 32 if err != nil { 33 return err 34 } 35 } 36 if len(create) > 0 { 37 log.Printf("[DEBUG] Creating tags: %#v", create) 38 _, err := conn.AddTagsToResource(&rds.AddTagsToResourceInput{ 39 ResourceName: aws.String(arn), 40 Tags: create, 41 }) 42 if err != nil { 43 return err 44 } 45 } 46 } 47 48 return nil 49 } 50 51 // diffTags takes our tags locally and the ones remotely and returns 52 // the set of tags that must be created, and the set of tags that must 53 // be destroyed. 54 func diffTagsRDS(oldTags, newTags []*rds.Tag) ([]*rds.Tag, []*rds.Tag) { 55 // First, we're creating everything we have 56 create := make(map[string]interface{}) 57 for _, t := range newTags { 58 create[*t.Key] = *t.Value 59 } 60 61 // Build the list of what to remove 62 var remove []*rds.Tag 63 for _, t := range oldTags { 64 old, ok := create[*t.Key] 65 if !ok || old != *t.Value { 66 // Delete it! 67 remove = append(remove, t) 68 } 69 } 70 71 return tagsFromMapRDS(create), remove 72 } 73 74 // tagsFromMap returns the tags for the given map of data. 75 func tagsFromMapRDS(m map[string]interface{}) []*rds.Tag { 76 result := make([]*rds.Tag, 0, len(m)) 77 for k, v := range m { 78 result = append(result, &rds.Tag{ 79 Key: aws.String(k), 80 Value: aws.String(v.(string)), 81 }) 82 } 83 84 return result 85 } 86 87 // tagsToMap turns the list of tags into a map. 88 func tagsToMapRDS(ts []*rds.Tag) map[string]string { 89 result := make(map[string]string) 90 for _, t := range ts { 91 result[*t.Key] = *t.Value 92 } 93 94 return result 95 }