github.com/gabrielperezs/terraform@v0.7.0-rc2.0.20160715084931-f7da2612946f/builtin/providers/digitalocean/tags.go (about) 1 package digitalocean 2 3 import ( 4 "log" 5 6 "github.com/digitalocean/godo" 7 "github.com/hashicorp/terraform/helper/schema" 8 ) 9 10 // setTags is a helper to set the tags for a resource. It expects the 11 // tags field to be named "tags" 12 func setTags(conn *godo.Client, d *schema.ResourceData) error { 13 oraw, nraw := d.GetChange("tags") 14 remove, create := diffTags(tagsFromSchema(oraw), tagsFromSchema(nraw)) 15 16 log.Printf("[DEBUG] Removing tags: %#v from %s", remove, d.Id()) 17 for _, tag := range remove { 18 _, err := conn.Tags.UntagResources(tag, &godo.UntagResourcesRequest{ 19 Resources: []godo.Resource{ 20 godo.Resource{ 21 ID: d.Id(), 22 Type: godo.DropletResourceType, 23 }, 24 }, 25 }) 26 if err != nil { 27 return err 28 } 29 } 30 31 log.Printf("[DEBUG] Creating tags: %s for %s", create, d.Id()) 32 for _, tag := range create { 33 _, err := conn.Tags.TagResources(tag, &godo.TagResourcesRequest{ 34 Resources: []godo.Resource{ 35 godo.Resource{ 36 ID: d.Id(), 37 Type: godo.DropletResourceType, 38 }, 39 }, 40 }) 41 if err != nil { 42 return err 43 } 44 } 45 46 return nil 47 } 48 49 // tagsFromSchema takes the raw schema tags and returns them as a 50 // properly asserted map[string]string 51 func tagsFromSchema(raw interface{}) map[string]string { 52 result := make(map[string]string) 53 for _, t := range raw.([]interface{}) { 54 result[t.(string)] = t.(string) 55 } 56 57 return result 58 } 59 60 // diffTags takes the old and the new tag sets and returns the difference of 61 // both. The remaining tags are those that need to be removed and created 62 func diffTags(oldTags, newTags map[string]string) (map[string]string, map[string]string) { 63 for k := range oldTags { 64 _, ok := newTags[k] 65 if ok { 66 delete(newTags, k) 67 delete(oldTags, k) 68 } 69 } 70 71 return oldTags, newTags 72 }