-
Notifications
You must be signed in to change notification settings - Fork 7
/
migrate_command.go
378 lines (343 loc) · 13.7 KB
/
migrate_command.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package cmd
import (
"context"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/Azure/azapi2azurerm/azurerm"
"github.com/Azure/azapi2azurerm/azurerm/schema"
"github.com/Azure/azapi2azurerm/helper"
"github.com/Azure/azapi2azurerm/tf"
"github.com/Azure/azapi2azurerm/types"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/mitchellh/cli"
)
const filenameImport = "imports.tf"
const providerConfig = `
provider "azurerm" {
features {}
}
`
const tempDir = "temp"
type MigrateCommand struct {
Ui cli.Ui
Verbose bool
Strict bool
}
func (c *MigrateCommand) flags() *flag.FlagSet {
fs := defaultFlagSet("plan")
fs.BoolVar(&c.Verbose, "v", false, "whether show terraform logs")
fs.BoolVar(&c.Strict, "strict", false, "strict mode: API versions must be matched")
fs.Usage = func() { c.Ui.Error(c.Help()) }
return fs
}
func (c MigrateCommand) Run(args []string) int {
// AzureRM provider will honor env.var "AZURE_HTTP_USER_AGENT" when constructing for HTTP "User-Agent" header.
os.Setenv("AZURE_HTTP_USER_AGENT", "azapi2azurerm commands/migrate")
f := c.flags()
if err := f.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s", err))
return 1
}
log.Printf("[INFO] initializing terraform...")
workingDirectory, _ := os.Getwd()
terraform, err := tf.NewTerraform(workingDirectory, c.Verbose, false)
if err != nil {
log.Fatal(err)
}
resources, updateResources := PlanCommand{ //nolint
Ui: c.Ui,
Verbose: c.Verbose,
Strict: c.Strict,
}.Plan(terraform, false)
c.MigrateGenericResource(terraform, resources)
c.MigrateGenericUpdateResource(terraform, updateResources)
return 0
}
func (c MigrateCommand) Help() string {
helpText := `
Usage: azapi2azurerm migrate
` + c.Synopsis() + "\nThe Terraform addresses listed in file `azapi2azurerm.ignore` will be ignored during migration.\n\n" + helpForFlags(c.flags())
return strings.TrimSpace(helpText)
}
func (c MigrateCommand) Synopsis() string {
return "Migrate azapi resources to azurerm resources in current working directory"
}
func (c MigrateCommand) MigrateGenericResource(terraform *tf.Terraform, resources []types.GenericResource) {
log.Printf("[INFO] -----------------------------------------------")
log.Printf("[INFO] task: migrate azapi_resource")
// generate import config
config := ""
for _, resource := range resources {
config += resource.EmptyImportConfig()
}
workingDirectory := terraform.GetWorkingDirectory()
if err := ioutil.WriteFile(filepath.Join(workingDirectory, filenameImport), []byte(config), 0644); err != nil {
log.Fatal(err)
}
// import and generate config
for index, r := range resources {
log.Printf("[INFO] migrating resource %s (%d instances) to resource %s...", r.OldAddress(nil), len(r.Instances), r.NewAddress(nil))
// import into real state
for _, instance := range r.Instances {
address := r.NewAddress(instance.Index)
log.Printf("[INFO] importing %s to %s...", instance.ResourceId, address)
if err := terraform.Import(address, instance.ResourceId); err != nil {
log.Printf("[Error] error importing %s : %s", address, instance.ResourceId)
}
}
// write empty config to temp dir for import
tempDirectoryCreate(workingDirectory)
tempPath := filepath.Join(workingDirectory, tempDir)
devTerraform, err := tf.NewTerraform(tempPath, c.Verbose, true)
if err != nil {
log.Fatal(err)
}
config := providerConfig
for _, instance := range r.Instances {
if !r.IsMultipleResources() {
config += fmt.Sprintf("resource \"%s\" \"%s\" {}\n", r.ResourceType, r.Label)
} else {
config += fmt.Sprintf("resource \"%s\" \"%s_%v\" {}\n", r.ResourceType, r.Label, instance.Index)
}
}
if err = ioutil.WriteFile(filepath.Join(tempPath, filenameImport), []byte(config), 0644); err != nil {
log.Fatal(err)
}
if !r.IsMultipleResources() {
instance := r.Instances[0]
log.Printf("[INFO] importing %s to %s and generating config...", instance.ResourceId, r.NewAddress(nil))
if block, err := importAndGenerateConfig(devTerraform, r.NewAddress(nil), instance.ResourceId, r.ResourceType, false); err == nil {
resources[index].Block = block
valuePropMap := helper.GetValuePropMap(resources[index].Block, resources[index].NewAddress(nil))
for i, output := range resources[index].Instances[0].Outputs {
resources[index].Instances[0].Outputs[i].NewName = valuePropMap[output.GetStringValue()]
}
for i, instance := range r.Instances {
props := []string{"location", "tags", "identity", "identity.0", "identity.0.type", "identity.0.identity_ids", "id"}
for _, prop := range props {
resources[index].Instances[i].Outputs = append(resources[index].Instances[i].Outputs, types.Output{
OldName: resources[index].OldAddress(instance.Index) + "." + prop,
NewName: resources[index].NewAddress(instance.Index) + "." + prop,
})
}
}
resources[index].Block = helper.InjectReference(resources[index].Block, resources[index].References)
resources[index].Migrated = true
log.Printf("[INFO] resource %s has migrated to %s", r.OldAddress(nil), r.NewAddress(nil))
} else {
log.Printf("[ERROR] %+v", err)
}
} else {
// import and build combined block
log.Printf("[INFO] generating config...")
blocks := make([]*hclwrite.Block, 0)
for _, instance := range r.Instances {
if block, err := importAndGenerateConfig(devTerraform, fmt.Sprintf("%s.%s_%v", r.ResourceType, r.Label, instance.Index), instance.ResourceId, r.ResourceType, false); err == nil {
blocks = append(blocks, block)
}
}
combinedBlock := hclwrite.NewBlock("resource", []string{r.ResourceType, r.Label})
if r.IsForEach() {
foreachItems := helper.CombineBlock(blocks, combinedBlock, true)
foreachConfig := helper.GetForEachConstants(r.Instances, foreachItems)
combinedBlock.Body().SetAttributeRaw("for_each", helper.GetTokensForExpression(foreachConfig))
} else {
_ = helper.CombineBlock(blocks, combinedBlock, false)
combinedBlock.Body().SetAttributeRaw("count", helper.GetTokensForExpression(fmt.Sprintf("%d", len(r.Instances))))
}
resources[index].Block = combinedBlock
for i, instance := range r.Instances {
valuePropMap := helper.GetValuePropMap(blocks[i], resources[index].NewAddress(instance.Index))
for j, output := range resources[index].Instances[i].Outputs {
resources[index].Instances[i].Outputs[j].NewName = valuePropMap[output.GetStringValue()]
}
}
for i, instance := range r.Instances {
resources[index].Instances[i].Outputs = append(resources[index].Instances[i].Outputs, types.Output{
OldName: resources[index].OldAddress(instance.Index),
NewName: resources[index].NewAddress(instance.Index),
})
props := []string{"location", "tags", "identity", "identity.0", "identity.0.type", "identity.0.identity_ids", "id"}
for _, prop := range props {
resources[index].Instances[i].Outputs = append(resources[index].Instances[i].Outputs, types.Output{
OldName: resources[index].OldAddress(instance.Index) + "." + prop,
NewName: resources[index].NewAddress(instance.Index) + "." + prop,
})
}
}
resources[index].Block = helper.InjectReference(resources[index].Block, resources[index].References)
resources[index].Migrated = true
log.Printf("[INFO] resource %s has migrated to %s", r.OldAddress(nil), r.NewAddress(nil))
}
}
tempDirectoryCleanup(workingDirectory)
// remove from state
for _, r := range resources {
if r.Migrated {
log.Printf("[INFO] removing %s from state", r.OldAddress(nil))
exec := terraform.GetExec()
if err := exec.StateRm(context.TODO(), r.OldAddress(nil)); err != nil {
log.Printf("[ERROR] error removing %s from state: %+v", r.OldAddress(nil), err)
}
}
}
// migrate depends_on, lifecycle, provisioner
for index, r := range resources {
if existingBlock, err := helper.GetResourceBlock(workingDirectory, r.OldAddress(nil)); err == nil && existingBlock != nil {
if attr := existingBlock.Body().GetAttribute("depends_on"); attr != nil {
resources[index].Block.Body().SetAttributeRaw("depends_on", attr.Expr().BuildTokens(nil))
}
for _, block := range existingBlock.Body().Blocks() {
if block.Type() == "lifecycle" || block.Type() == "provisioner" {
resources[index].Block.Body().AppendBlock(block)
}
}
}
}
// remove from config
if err := os.Remove(filepath.Join(workingDirectory, filenameImport)); err != nil {
log.Fatal(err)
}
for _, r := range resources {
if r.Migrated {
log.Printf("[INFO] removing %s from config", r.OldAddress(nil))
if err := helper.ReplaceResourceBlock(workingDirectory, r.OldAddress(nil), r.Block); err != nil {
log.Printf("[ERROR] error removing %s from state: %+v", r.OldAddress(nil), err)
}
}
}
// replace jsondecode(xxx.output) with azurerm references
outputs := make([]types.Output, 0)
for _, r := range resources {
if r.Migrated {
for _, instance := range r.Instances {
outputs = append(outputs, instance.Outputs...)
}
outputs = append(outputs, types.Output{
OldName: r.OldAddress(nil),
NewName: r.NewAddress(nil),
})
}
}
if len(outputs) != 0 {
log.Printf("[INFO] replacing azapi resource references with azurerm resoure reference.")
if err := helper.ReplaceGenericOutputs(workingDirectory, outputs); err != nil {
log.Printf("[ERROR] replacing azapi resource references with azurerm resoure reference: %+v", err)
}
}
}
func (c MigrateCommand) MigrateGenericUpdateResource(terraform *tf.Terraform, resources []types.GenericUpdateResource) {
log.Printf("[INFO] -----------------------------------------------")
log.Printf("[INFO] task: migrate azapi_update_resource")
// generate import config
config := providerConfig
for _, resource := range resources {
config += resource.EmptyImportConfig()
}
// save empty import config to temp dir
workingDirectory := terraform.GetWorkingDirectory()
tempDirectoryCreate(workingDirectory)
tempPath := filepath.Join(workingDirectory, tempDir)
devTerraform, err := tf.NewTerraform(tempPath, c.Verbose, true)
if err != nil {
log.Fatal(err)
}
if err = ioutil.WriteFile(filepath.Join(tempPath, filenameImport), []byte(config), 0644); err != nil {
log.Fatal(err)
}
// import and generate config
for index, r := range resources {
log.Printf("[INFO] migrating resource %s to resource %s", r.OldAddress(), r.NewAddress())
if block, err := importAndGenerateConfig(devTerraform, r.NewAddress(), r.Id, r.ResourceType, true); err == nil {
resources[index].Block = block
valuePropMap := helper.GetValuePropMap(resources[index].Block, resources[index].NewAddress())
for i := range resources[index].Outputs {
resources[index].Outputs[i].NewName = valuePropMap[resources[index].Outputs[i].GetStringValue()]
}
resources[index].Block = helper.InjectReference(resources[index].Block, resources[index].References)
resources[index].Migrated = true
log.Printf("[INFO] %s has migrated to %s", r.OldAddress(), r.NewAddress())
} else {
log.Printf("[ERROR] %+v", err)
}
}
if err := helper.UpdateMigratedResourceBlock(workingDirectory, resources); err != nil {
log.Fatal(err)
}
outputs := make([]types.Output, 0)
for _, r := range resources {
if r.Migrated {
outputs = append(outputs, r.Outputs...)
}
}
if len(outputs) != 0 {
log.Printf("[INFO] replacing azapi resource references with azurerm resoure reference.")
if err := helper.ReplaceGenericOutputs(workingDirectory, outputs); err != nil {
log.Printf("[ERROR] replacing azapi resource references with azurerm resoure reference: %+v", err)
}
}
// remove from state
for _, r := range resources {
if r.Migrated {
log.Printf("[INFO] removing %s from state", r.OldAddress())
exec := terraform.GetExec()
if err := exec.StateRm(context.TODO(), r.OldAddress()); err != nil {
log.Printf("[ERROR] error removing %s from state: %+v", r.OldAddress(), err)
}
}
}
// remove from config
for _, r := range resources {
if r.Migrated {
log.Printf("[INFO] removing %s from config", r.OldAddress())
if err := helper.ReplaceResourceBlock(workingDirectory, r.OldAddress(), nil); err != nil {
log.Printf("[ERROR] error removing %s from state: %+v", r.OldAddress(), err)
}
}
}
tempDirectoryCleanup(workingDirectory)
}
func importAndGenerateConfig(terraform *tf.Terraform, address string, id string, resourceType string, skipTune bool) (*hclwrite.Block, error) {
tpl, err := terraform.ImportAdd(address, id)
if err != nil {
return nil, fmt.Errorf("[ERROR] error importing address: %s, id: %s: %+v", address, id, err)
}
f, diag := hclwrite.ParseConfig([]byte(tpl), "", hcl.InitialPos)
if (diag != nil && diag.HasErrors()) || f == nil {
return nil, fmt.Errorf("[ERROR] parsing the HCL generated by \"terraform add\" of %s: %s", address, diag.Error())
}
if !skipTune {
rb := f.Body().Blocks()[0].Body()
sch := schema.ProviderSchemaInfo.ResourceSchemas[resourceType]
if err := azurerm.TuneHCLSchemaForResource(rb, sch); err != nil {
return nil, fmt.Errorf("[ERROR] tuning hcl config base on schema: %+v", err)
}
}
return f.Body().Blocks()[0], nil
}
func tempDirectoryCreate(workingDirectory string) {
tempPath := filepath.Join(workingDirectory, tempDir)
if _, err := os.Stat(tempPath); !os.IsNotExist(err) {
if err := os.RemoveAll(tempPath); err != nil {
log.Fatalf("error deleting %s: %+v", tempPath, err)
}
}
if err := os.MkdirAll(tempPath, 0755); err != nil {
log.Fatalf("creating temp workspace %q: %+v", tempPath, err)
}
}
func tempDirectoryCleanup(workingDirectory string) {
tempPath := filepath.Join(workingDirectory, tempDir)
// cleanup temp folder
if _, err := os.Stat(tempPath); !os.IsNotExist(err) {
if err := os.RemoveAll(tempPath); err != nil {
log.Printf("[WARN] error deleting %s: %+v", tempPath, err)
}
}
}