summaryrefslogtreecommitdiff
path: root/vendor/github.com/hashicorp/terraform/terraform/context_import.go
blob: f1d57760df3e6953d9f3d45c09492c244949893a (plain)
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
package terraform

import (
	"github.com/hashicorp/terraform/config/module"
)

// ImportOpts are used as the configuration for Import.
type ImportOpts struct {
	// Targets are the targets to import
	Targets []*ImportTarget

	// Module is optional, and specifies a config module that is loaded
	// into the graph and evaluated. The use case for this is to provide
	// provider configuration.
	Module *module.Tree
}

// ImportTarget is a single resource to import.
type ImportTarget struct {
	// Addr is the full resource address of the resource to import.
	// Example: "module.foo.aws_instance.bar"
	Addr string

	// ID is the ID of the resource to import. This is resource-specific.
	ID string

	// Provider string
	Provider string
}

// Import takes already-created external resources and brings them
// under Terraform management. Import requires the exact type, name, and ID
// of the resources to import.
//
// This operation is idempotent. If the requested resource is already
// imported, no changes are made to the state.
//
// Further, this operation also gracefully handles partial state. If during
// an import there is a failure, all previously imported resources remain
// imported.
func (c *Context) Import(opts *ImportOpts) (*State, error) {
	// Hold a lock since we can modify our own state here
	defer c.acquireRun("import")()

	// Copy our own state
	c.state = c.state.DeepCopy()

	// If no module is given, default to the module configured with
	// the Context.
	module := opts.Module
	if module == nil {
		module = c.module
	}

	// Initialize our graph builder
	builder := &ImportGraphBuilder{
		ImportTargets: opts.Targets,
		Module:        module,
		Providers:     c.components.ResourceProviders(),
	}

	// Build the graph!
	graph, err := builder.Build(RootModulePath)
	if err != nil {
		return c.state, err
	}

	// Walk it
	if _, err := c.walk(graph, nil, walkImport); err != nil {
		return c.state, err
	}

	// Clean the state
	c.state.prune()

	return c.state, nil
}