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

     1  package aws
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  
     7  	"github.com/hashicorp/terraform/helper/schema"
     8  	"github.com/hashicorp/terraform/terraform"
     9  	"strings"
    10  )
    11  
    12  func resourceAwsDynamoDbTableMigrateState(
    13  	v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
    14  	switch v {
    15  	case 0:
    16  		log.Println("[INFO] Found AWS DynamoDB Table State v0; migrating to v1")
    17  		return migrateDynamoDBStateV0toV1(is)
    18  	default:
    19  		return is, fmt.Errorf("Unexpected schema version: %d", v)
    20  	}
    21  }
    22  
    23  func migrateDynamoDBStateV0toV1(is *terraform.InstanceState) (*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] DynamoDB Table Attributes before Migration: %#v", is.Attributes)
    30  
    31  	prefix := "global_secondary_index"
    32  	entity := resourceAwsDynamoDbTable()
    33  
    34  	// Read old keys
    35  	reader := &schema.MapFieldReader{
    36  		Schema: entity.Schema,
    37  		Map:    schema.BasicMapReader(is.Attributes),
    38  	}
    39  	result, err := reader.ReadField([]string{prefix})
    40  	if err != nil {
    41  		return nil, err
    42  	}
    43  
    44  	oldKeys, ok := result.Value.(*schema.Set)
    45  	if !ok {
    46  		return nil, fmt.Errorf("Got unexpected value from state: %#v", result.Value)
    47  	}
    48  
    49  	// Delete old keys
    50  	for k := range is.Attributes {
    51  		if strings.HasPrefix(k, fmt.Sprintf("%s.", prefix)) {
    52  			delete(is.Attributes, k)
    53  		}
    54  	}
    55  
    56  	// Write new keys
    57  	writer := schema.MapFieldWriter{
    58  		Schema: entity.Schema,
    59  	}
    60  	if err := writer.WriteField([]string{prefix}, oldKeys); err != nil {
    61  		return is, err
    62  	}
    63  	for k, v := range writer.Map() {
    64  		is.Attributes[k] = v
    65  	}
    66  
    67  	log.Printf("[DEBUG] DynamoDB Table Attributes after State Migration: %#v", is.Attributes)
    68  
    69  	return is, nil
    70  }