github.com/gabrielperezs/terraform@v0.7.0-rc2.0.20160715084931-f7da2612946f/builtin/providers/aws/tagsELB.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/elb" 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 setTagsELB(conn *elb.ELB, d *schema.ResourceData) 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 := diffTagsELB(tagsFromMapELB(o), tagsFromMapELB(n)) 19 20 // Set tags 21 if len(remove) > 0 { 22 log.Printf("[DEBUG] Removing tags: %#v", remove) 23 k := make([]*elb.TagKeyOnly, 0, len(remove)) 24 for _, t := range remove { 25 k = append(k, &elb.TagKeyOnly{Key: t.Key}) 26 } 27 _, err := conn.RemoveTags(&elb.RemoveTagsInput{ 28 LoadBalancerNames: []*string{aws.String(d.Get("name").(string))}, 29 Tags: k, 30 }) 31 if err != nil { 32 return err 33 } 34 } 35 if len(create) > 0 { 36 log.Printf("[DEBUG] Creating tags: %#v", create) 37 _, err := conn.AddTags(&elb.AddTagsInput{ 38 LoadBalancerNames: []*string{aws.String(d.Get("name").(string))}, 39 Tags: create, 40 }) 41 if err != nil { 42 return err 43 } 44 } 45 } 46 47 return nil 48 } 49 50 // diffTags takes our tags locally and the ones remotely and returns 51 // the set of tags that must be created, and the set of tags that must 52 // be destroyed. 53 func diffTagsELB(oldTags, newTags []*elb.Tag) ([]*elb.Tag, []*elb.Tag) { 54 // First, we're creating everything we have 55 create := make(map[string]interface{}) 56 for _, t := range newTags { 57 create[*t.Key] = *t.Value 58 } 59 60 // Build the list of what to remove 61 var remove []*elb.Tag 62 for _, t := range oldTags { 63 old, ok := create[*t.Key] 64 if !ok || old != *t.Value { 65 // Delete it! 66 remove = append(remove, t) 67 } 68 } 69 70 return tagsFromMapELB(create), remove 71 } 72 73 // tagsFromMap returns the tags for the given map of data. 74 func tagsFromMapELB(m map[string]interface{}) []*elb.Tag { 75 var result []*elb.Tag 76 for k, v := range m { 77 result = append(result, &elb.Tag{ 78 Key: aws.String(k), 79 Value: aws.String(v.(string)), 80 }) 81 } 82 83 return result 84 } 85 86 // tagsToMap turns the list of tags into a map. 87 func tagsToMapELB(ts []*elb.Tag) map[string]string { 88 result := make(map[string]string) 89 for _, t := range ts { 90 result[*t.Key] = *t.Value 91 } 92 93 return result 94 }