github.com/minamijoyo/terraform@v0.7.8-0.20161029001309-18b3736ba44b/builtin/providers/consul/resource_consul_keys_migrate.go (about) 1 package consul 2 3 import ( 4 "fmt" 5 "log" 6 "strings" 7 8 "github.com/hashicorp/terraform/helper/schema" 9 "github.com/hashicorp/terraform/terraform" 10 ) 11 12 func resourceConsulKeysMigrateState( 13 v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { 14 switch v { 15 case 0: 16 log.Println("[INFO] Found consul_keys State v0; migrating to v1") 17 return resourceConsulKeysMigrateStateV0toV1(is) 18 default: 19 return is, fmt.Errorf("Unexpected schema version: %d", v) 20 } 21 } 22 23 func resourceConsulKeysMigrateStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { 24 if is.Empty() || is.Attributes == nil { 25 log.Println("[DEBUG] Empty InstanceState; nothing to migrate.") 26 return is, nil 27 } 28 29 log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) 30 31 res := resourceConsulKeys() 32 keys, err := readV0Keys(is, res) 33 if err != nil { 34 return is, err 35 } 36 if err := clearV0Keys(is); err != nil { 37 return is, err 38 } 39 if err := writeV1Keys(is, res, keys); err != nil { 40 return is, err 41 } 42 43 log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes) 44 return is, nil 45 } 46 47 func readV0Keys( 48 is *terraform.InstanceState, 49 res *schema.Resource, 50 ) (*schema.Set, error) { 51 reader := &schema.MapFieldReader{ 52 Schema: res.Schema, 53 Map: schema.BasicMapReader(is.Attributes), 54 } 55 result, err := reader.ReadField([]string{"key"}) 56 if err != nil { 57 return nil, err 58 } 59 60 oldKeys, ok := result.Value.(*schema.Set) 61 if !ok { 62 return nil, fmt.Errorf("Got unexpected value from state: %#v", result.Value) 63 } 64 return oldKeys, nil 65 } 66 67 func clearV0Keys(is *terraform.InstanceState) error { 68 for k := range is.Attributes { 69 if strings.HasPrefix(k, "key.") { 70 delete(is.Attributes, k) 71 } 72 } 73 return nil 74 } 75 76 func writeV1Keys( 77 is *terraform.InstanceState, 78 res *schema.Resource, 79 keys *schema.Set, 80 ) error { 81 writer := schema.MapFieldWriter{ 82 Schema: res.Schema, 83 } 84 if err := writer.WriteField([]string{"key"}, keys); err != nil { 85 return err 86 } 87 for k, v := range writer.Map() { 88 is.Attributes[k] = v 89 } 90 91 return nil 92 }