-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (81 loc) · 2.29 KB
/
main.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
94
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
)
var (
filePath string
module string
)
type ResourceInstanceAttributes struct {
ID string `json:"id"`
Type string `json:"type"`
}
type ResourceInstance struct {
SchemaVersion int `json:"schema_version"`
Attributes ResourceInstanceAttributes `json:"attributes,omitempty"`
}
type Resource struct {
Module string `json:"module,omitempty"`
Mode string `json:"mode"`
Type string `json:"type"`
Name string `json:"name"`
Provider string `json:"provider"`
Instances []ResourceInstance `json:"instances"`
}
type TerraformState struct {
Version int `json:"version"`
TerraformVersion string `json:"terraform_version"`
Resources []Resource `json:"resources"`
}
func main() {
flag.StringVar(&filePath, "file", "state.json", "path to state file")
flag.StringVar(&module, "module", "all", "name of module to filter resources by")
flag.Parse()
f, err := os.Open(filePath)
if err != nil {
fmt.Println(err)
}
defer f.Close()
b, err := ioutil.ReadAll(f)
var state TerraformState
json.Unmarshal(b, &state)
for r := 0; r < len(state.Resources); r++ {
// If we're only looking at a particular resource, skip
// all other resources that aren't in the selected module
if module != "all" && state.Resources[r].Module != module {
continue
}
// Skip when state item is not a resource (mode=managed)
if state.Resources[r].Mode != "managed" {
continue
}
// Deal with resources that have a `count` set
if len(state.Resources[r].Instances) >= 2 {
for i := 0; i < len(state.Resources[r].Instances); i++ {
fmt.Printf(
"terraform import \"%s.%s.%s[%s]\" \"%s\"\n",
state.Resources[r].Module,
state.Resources[r].Type,
state.Resources[r].Name,
strconv.Itoa(i),
state.Resources[r].Instances[i].Attributes.ID,
)
}
} else if len(state.Resources[r].Instances) == 1 {
fmt.Printf(
"terraform import \"%s.%s.%s\" \"%s\"\n",
state.Resources[r].Module,
state.Resources[r].Type,
state.Resources[r].Name,
state.Resources[r].Instances[int(0)].Attributes.ID,
)
} else if len(state.Resources[r].Instances) == 0 {
continue
}
}
}