github.com/hobbeswalsh/terraform@v0.3.7-0.20150619183303-ad17cf55a0fa/builtin/providers/aws/resource_aws_security_group_rule_migrate.go (about) 1 package aws 2 3 import ( 4 "fmt" 5 "log" 6 "strconv" 7 "strings" 8 9 "github.com/aws/aws-sdk-go/aws" 10 "github.com/aws/aws-sdk-go/service/ec2" 11 "github.com/hashicorp/terraform/terraform" 12 ) 13 14 func resourceAwsSecurityGroupRuleMigrateState( 15 v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) { 16 switch v { 17 case 0: 18 log.Println("[INFO] Found AWS Security Group State v0; migrating to v1") 19 return migrateSGRuleStateV0toV1(is) 20 default: 21 return is, fmt.Errorf("Unexpected schema version: %d", v) 22 } 23 24 return is, nil 25 } 26 27 func migrateSGRuleStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) { 28 if is.Empty() { 29 log.Println("[DEBUG] Empty InstanceState; nothing to migrate.") 30 return is, nil 31 } 32 33 perm, err := migrateExpandIPPerm(is.Attributes) 34 35 if err != nil { 36 return nil, fmt.Errorf("[WARN] Error making new IP Permission in Security Group migration") 37 } 38 39 log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes) 40 newID := ipPermissionIDHash(is.Attributes["type"], perm) 41 is.Attributes["id"] = newID 42 is.ID = newID 43 log.Printf("[DEBUG] Attributes after migration: %#v, new id: %s", is.Attributes, newID) 44 return is, nil 45 } 46 47 func migrateExpandIPPerm(attrs map[string]string) (*ec2.IPPermission, error) { 48 var perm ec2.IPPermission 49 tp, err := strconv.Atoi(attrs["to_port"]) 50 if err != nil { 51 return nil, fmt.Errorf("Error converting to_port in Security Group migration") 52 } 53 54 fp, err := strconv.Atoi(attrs["from_port"]) 55 if err != nil { 56 return nil, fmt.Errorf("Error converting from_port in Security Group migration") 57 } 58 59 perm.ToPort = aws.Long(int64(tp)) 60 perm.FromPort = aws.Long(int64(fp)) 61 perm.IPProtocol = aws.String(attrs["protocol"]) 62 63 groups := make(map[string]bool) 64 if attrs["self"] == "true" { 65 groups[attrs["security_group_id"]] = true 66 } 67 68 if attrs["source_security_group_id"] != "" { 69 groups[attrs["source_security_group_id"]] = true 70 } 71 72 if len(groups) > 0 { 73 perm.UserIDGroupPairs = make([]*ec2.UserIDGroupPair, len(groups)) 74 // build string list of group name/ids 75 var gl []string 76 for k, _ := range groups { 77 gl = append(gl, k) 78 } 79 80 for i, name := range gl { 81 perm.UserIDGroupPairs[i] = &ec2.UserIDGroupPair{ 82 GroupID: aws.String(name), 83 } 84 } 85 } 86 87 var cb []string 88 for k, v := range attrs { 89 if k != "cidr_blocks.#" && strings.HasPrefix(k, "cidr_blocks") { 90 cb = append(cb, v) 91 } 92 } 93 if len(cb) > 0 { 94 perm.IPRanges = make([]*ec2.IPRange, len(cb)) 95 for i, v := range cb { 96 perm.IPRanges[i] = &ec2.IPRange{CIDRIP: aws.String(v)} 97 } 98 } 99 100 return &perm, nil 101 }