github.com/gabrielperezs/terraform@v0.7.0-rc2.0.20160715084931-f7da2612946f/builtin/providers/cloudstack/tags.go (about) 1 package cloudstack 2 3 import ( 4 "log" 5 6 "github.com/hashicorp/terraform/helper/schema" 7 "github.com/xanzy/go-cloudstack/cloudstack" 8 ) 9 10 // tagsSchema returns the schema to use for tags 11 func tagsSchema() *schema.Schema { 12 return &schema.Schema{ 13 Type: schema.TypeMap, 14 Optional: true, 15 Computed: true, 16 } 17 } 18 19 // setTags is a helper to set the tags for a resource. It expects the 20 // tags field to be named "tags" 21 func setTags(cs *cloudstack.CloudStackClient, d *schema.ResourceData, resourcetype string) error { 22 oraw, nraw := d.GetChange("tags") 23 o := oraw.(map[string]interface{}) 24 n := nraw.(map[string]interface{}) 25 26 remove, create := diffTags(tagsFromSchema(o), tagsFromSchema(n)) 27 log.Printf("[DEBUG] tags to remove: %v", remove) 28 log.Printf("[DEBUG] tags to create: %v", create) 29 30 // First remove any obsolete tags 31 if len(remove) > 0 { 32 log.Printf("[DEBUG] Removing tags: %v from %s", remove, d.Id()) 33 p := cs.Resourcetags.NewDeleteTagsParams([]string{d.Id()}, resourcetype) 34 p.SetTags(remove) 35 _, err := cs.Resourcetags.DeleteTags(p) 36 if err != nil { 37 return err 38 } 39 } 40 41 // Then add any new tags 42 if len(create) > 0 { 43 log.Printf("[DEBUG] Creating tags: %v for %s", create, d.Id()) 44 p := cs.Resourcetags.NewCreateTagsParams([]string{d.Id()}, resourcetype, create) 45 _, err := cs.Resourcetags.CreateTags(p) 46 if err != nil { 47 return err 48 } 49 } 50 51 return nil 52 } 53 54 // diffTags takes the old and the new tag sets and returns the difference of 55 // both. The remaining tags are those that need to be removed and created 56 func diffTags(oldTags, newTags map[string]string) (map[string]string, map[string]string) { 57 for k, old := range oldTags { 58 new, ok := newTags[k] 59 if ok && old == new { 60 // We should avoid removing or creating tags we already have 61 delete(oldTags, k) 62 delete(newTags, k) 63 } 64 } 65 66 return oldTags, newTags 67 } 68 69 // tagsFromSchema takes the raw schema tags and returns them as a 70 // properly asserted map[string]string 71 func tagsFromSchema(m map[string]interface{}) map[string]string { 72 result := make(map[string]string, len(m)) 73 for k, v := range m { 74 result[k] = v.(string) 75 } 76 return result 77 }