github.com/nicgrayson/terraform@v0.4.3-0.20150415203910-c4de50829380/builtin/providers/google/resource_compute_instance_migrate.go (about)

     1  package google
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"strconv"
     7  	"strings"
     8  
     9  	"github.com/hashicorp/terraform/terraform"
    10  )
    11  
    12  func resourceComputeInstanceMigrateState(
    13  	v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
    14  	if is.Empty() {
    15  		log.Println("[DEBUG] Empty InstanceState; nothing to migrate.")
    16  		return is, nil
    17  	}
    18  
    19  	switch v {
    20  	case 0:
    21  		log.Println("[INFO] Found Compute Instance State v0; migrating to v1")
    22  		return migrateStateV0toV1(is)
    23  	default:
    24  		return is, fmt.Errorf("Unexpected schema version: %d", v)
    25  	}
    26  }
    27  
    28  func migrateStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) {
    29  	log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes)
    30  
    31  	// Delete old count
    32  	delete(is.Attributes, "metadata.#")
    33  
    34  	newMetadata := make(map[string]string)
    35  
    36  	for k, v := range is.Attributes {
    37  		if !strings.HasPrefix(k, "metadata.") {
    38  			continue
    39  		}
    40  
    41  		// We have a key that looks like "metadata.*" and we know it's not
    42  		// metadata.# because we deleted it above, so it must be metadata.<N>.<key>
    43  		// from the List of Maps. Just need to convert it to a single Map by
    44  		// ditching the '<N>' field.
    45  		kParts := strings.SplitN(k, ".", 3)
    46  
    47  		// Sanity check: all three parts should be there and <N> should be a number
    48  		badFormat := false
    49  		if len(kParts) != 3 {
    50  			badFormat = true
    51  		} else if _, err := strconv.Atoi(kParts[1]); err != nil {
    52  			badFormat = true
    53  		}
    54  
    55  		if badFormat {
    56  			return is, fmt.Errorf(
    57  				"migration error: found metadata key in unexpected format: %s", k)
    58  		}
    59  
    60  		// Rejoin as "metadata.<key>"
    61  		newK := strings.Join([]string{kParts[0], kParts[2]}, ".")
    62  		newMetadata[newK] = v
    63  		delete(is.Attributes, k)
    64  	}
    65  
    66  	for k, v := range newMetadata {
    67  		is.Attributes[k] = v
    68  	}
    69  
    70  	log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes)
    71  	return is, nil
    72  }