github.com/hugorut/terraform@v1.1.3/src/terraform/context_import.go (about) 1 package terraform 2 3 import ( 4 "log" 5 6 "github.com/hugorut/terraform/src/addrs" 7 "github.com/hugorut/terraform/src/configs" 8 "github.com/hugorut/terraform/src/states" 9 "github.com/hugorut/terraform/src/tfdiags" 10 ) 11 12 // ImportOpts are used as the configuration for Import. 13 type ImportOpts struct { 14 // Targets are the targets to import 15 Targets []*ImportTarget 16 17 // SetVariables are the variables set outside of the configuration, 18 // such as on the command line, in variables files, etc. 19 SetVariables InputValues 20 } 21 22 // ImportTarget is a single resource to import. 23 type ImportTarget struct { 24 // Addr is the address for the resource instance that the new object should 25 // be imported into. 26 Addr addrs.AbsResourceInstance 27 28 // ID is the ID of the resource to import. This is resource-specific. 29 ID string 30 31 // ProviderAddr is the address of the provider that should handle the import. 32 ProviderAddr addrs.AbsProviderConfig 33 } 34 35 // Import takes already-created external resources and brings them 36 // under Terraform management. Import requires the exact type, name, and ID 37 // of the resources to import. 38 // 39 // This operation is idempotent. If the requested resource is already 40 // imported, no changes are made to the state. 41 // 42 // Further, this operation also gracefully handles partial state. If during 43 // an import there is a failure, all previously imported resources remain 44 // imported. 45 func (c *Context) Import(config *configs.Config, prevRunState *states.State, opts *ImportOpts) (*states.State, tfdiags.Diagnostics) { 46 var diags tfdiags.Diagnostics 47 48 // Hold a lock since we can modify our own state here 49 defer c.acquireRun("import")() 50 51 // Don't modify our caller's state 52 state := prevRunState.DeepCopy() 53 54 log.Printf("[DEBUG] Building and walking import graph") 55 56 // Initialize our graph builder 57 builder := &ImportGraphBuilder{ 58 ImportTargets: opts.Targets, 59 Config: config, 60 Plugins: c.plugins, 61 } 62 63 // Build the graph 64 graph, graphDiags := builder.Build(addrs.RootModuleInstance) 65 diags = diags.Append(graphDiags) 66 if graphDiags.HasErrors() { 67 return state, diags 68 } 69 70 variables := mergeDefaultInputVariableValues(opts.SetVariables, config.Module.Variables) 71 72 // Walk it 73 walker, walkDiags := c.walk(graph, walkImport, &graphWalkOpts{ 74 Config: config, 75 InputState: state, 76 RootVariableValues: variables, 77 }) 78 diags = diags.Append(walkDiags) 79 if walkDiags.HasErrors() { 80 return state, diags 81 } 82 83 newState := walker.State.Close() 84 return newState, diags 85 }