github.com/danp/terraform@v0.9.5-0.20170426144147-39d740081351/builtin/providers/google/resource_compute_instance_group_migrate.go (about)

     1  package google
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"strconv"
     7  	"strings"
     8  
     9  	"github.com/hashicorp/terraform/helper/schema"
    10  	"github.com/hashicorp/terraform/terraform"
    11  )
    12  
    13  func resourceComputeInstanceGroupMigrateState(
    14  	v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
    15  	if is.Empty() {
    16  		log.Println("[DEBUG] Empty InstanceState; nothing to migrate.")
    17  		return is, nil
    18  	}
    19  
    20  	switch v {
    21  	case 0:
    22  		log.Println("[INFO] Found Compute Instance Group State v0; migrating to v1")
    23  		is, err := migrateInstanceGroupStateV0toV1(is)
    24  		if err != nil {
    25  			return is, err
    26  		}
    27  		return is, nil
    28  	default:
    29  		return is, fmt.Errorf("Unexpected schema version: %d", v)
    30  	}
    31  }
    32  
    33  func migrateInstanceGroupStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) {
    34  	log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes)
    35  
    36  	newInstances := []string{}
    37  
    38  	for k, v := range is.Attributes {
    39  		if !strings.HasPrefix(k, "instances.") {
    40  			continue
    41  		}
    42  
    43  		if k == "instances.#" {
    44  			continue
    45  		}
    46  
    47  		// Key is now of the form instances.%d
    48  		kParts := strings.Split(k, ".")
    49  
    50  		// Sanity check: two parts should be there and <N> should be a number
    51  		badFormat := false
    52  		if len(kParts) != 2 {
    53  			badFormat = true
    54  		} else if _, err := strconv.Atoi(kParts[1]); err != nil {
    55  			badFormat = true
    56  		}
    57  
    58  		if badFormat {
    59  			return is, fmt.Errorf("migration error: found instances key in unexpected format: %s", k)
    60  		}
    61  
    62  		newInstances = append(newInstances, v)
    63  		delete(is.Attributes, k)
    64  	}
    65  
    66  	for _, v := range newInstances {
    67  		hash := schema.HashString(v)
    68  		newKey := fmt.Sprintf("instances.%d", hash)
    69  		is.Attributes[newKey] = v
    70  	}
    71  
    72  	log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes)
    73  	return is, nil
    74  }