forked from GoogleCloudPlatform/magic-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresource_compute_firewall_migrate.go
93 lines (79 loc) · 2.18 KB
/
resource_compute_firewall_migrate.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package google
import (
"fmt"
"log"
"sort"
"strconv"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)
func resourceComputeFirewallMigrateState(
v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
if is.Empty() {
log.Println("[DEBUG] Empty InstanceState; nothing to migrate.")
return is, nil
}
switch v {
case 0:
log.Println("[INFO] Found Compute Firewall State v0; migrating to v1")
is, err := migrateFirewallStateV0toV1(is)
if err != nil {
return is, err
}
return is, nil
default:
return is, fmt.Errorf("Unexpected schema version: %d", v)
}
}
func migrateFirewallStateV0toV1(is *terraform.InstanceState) (*terraform.InstanceState, error) {
log.Printf("[DEBUG] Attributes before migration: %#v", is.Attributes)
idx := 0
portCount := 0
newPorts := make(map[string]string)
keys := make([]string, len(is.Attributes))
for k := range is.Attributes {
keys[idx] = k
idx++
}
sort.Strings(keys)
for _, k := range keys {
if !strings.HasPrefix(k, "allow.") {
continue
}
if k == "allow.#" {
continue
}
if strings.HasSuffix(k, ".ports.#") {
continue
}
if strings.HasSuffix(k, ".protocol") {
continue
}
// We have a key that looks like "allow.<hash>.ports.*" and we know it's not
// allow.<hash>.ports.# because we deleted it above, so it must be allow.<hash1>.ports.<hash2>
// from the Set of Ports. Just need to convert it to a list by
// replacing second hash with sequential numbers.
kParts := strings.Split(k, ".")
// Sanity check: all four parts should be there and <hash> should be a number
badFormat := false
if len(kParts) != 4 {
badFormat = true
} else if _, err := strconv.Atoi(kParts[1]); err != nil {
badFormat = true
}
if badFormat {
return is, fmt.Errorf(
"migration error: found port key in unexpected format: %s", k)
}
allowHash, _ := strconv.Atoi(kParts[1])
newK := fmt.Sprintf("allow.%d.ports.%d", allowHash, portCount)
portCount++
newPorts[newK] = is.Attributes[k]
delete(is.Attributes, k)
}
for k, v := range newPorts {
is.Attributes[k] = v
}
log.Printf("[DEBUG] Attributes after migration: %#v", is.Attributes)
return is, nil
}