github.com/mohanarpit/terraform@v0.6.16-0.20160909104007-291f29853544/builtin/providers/cloudflare/resource_cloudflare_record_migrate.go (about) 1 package cloudflare 2 3 import ( 4 "fmt" 5 "log" 6 "strconv" 7 8 "github.com/cloudflare/cloudflare-go" 9 "github.com/hashicorp/terraform/terraform" 10 ) 11 12 func resourceCloudFlareRecordMigrateState( 13 v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { 14 switch v { 15 case 0: 16 log.Println("[INFO] Found CloudFlare Record State v0; migrating to v1") 17 return migrateCloudFlareRecordStateV0toV1(is, meta) 18 default: 19 return is, fmt.Errorf("Unexpected schema version: %d", v) 20 } 21 } 22 23 func migrateCloudFlareRecordStateV0toV1(is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { 24 if is.Empty() { 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 client := meta.(*cloudflare.API) 31 32 // look up new id based on attributes 33 domain := is.Attributes["domain"] 34 zoneId, err := client.ZoneIDByName(domain) 35 if err != nil { 36 return is, fmt.Errorf("Error finding zone %q: %s", domain, err) 37 } 38 39 // all other information is ignored in the DNSRecords call 40 searchRecord := cloudflare.DNSRecord{ 41 Type: is.Attributes["type"], 42 Name: is.Attributes["hostname"], 43 Content: is.Attributes["value"], 44 } 45 46 records, err := client.DNSRecords(zoneId, searchRecord) 47 if err != nil { 48 return is, err 49 } 50 51 for _, r := range records { 52 if is.Attributes["ttl"] != "" { 53 v, err := strconv.Atoi(is.Attributes["ttl"]) 54 if err != nil { 55 return is, fmt.Errorf("Error converting ttl to int in CloudFlare Record Migration") 56 } 57 58 if v != r.TTL { 59 continue 60 } 61 } 62 63 if is.Attributes["proxied"] != "" { 64 b, err := strconv.ParseBool(is.Attributes["proxied"]) 65 if err != nil { 66 return is, fmt.Errorf("Error converting proxied to bool in CloudFlare Record Migration") 67 } 68 69 if b != r.Proxied { 70 continue 71 } 72 } 73 74 if is.Attributes["priority"] != "" { 75 v, err := strconv.Atoi(is.Attributes["priority"]) 76 if err != nil { 77 return is, fmt.Errorf("Error converting priority to int in CloudFlare Record Migration") 78 } 79 80 if v != r.Priority { 81 continue 82 } 83 } 84 85 // assume record found 86 is.Attributes["id"] = r.ID 87 is.ID = r.ID 88 log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes) 89 return is, nil 90 } 91 92 // assume no record found 93 log.Printf("[DEBUG] Attributes after no migration: %#v", is.Attributes) 94 return is, fmt.Errorf("No matching Record found") 95 }