github.com/tomaszheflik/terraform@v0.7.3-0.20160827060421-32f990b41594/terraform/context_import.go (about)

     1  package terraform
     2  
     3  import (
     4  	"github.com/hashicorp/terraform/config/module"
     5  )
     6  
     7  // ImportOpts are used as the configuration for Import.
     8  type ImportOpts struct {
     9  	// Targets are the targets to import
    10  	Targets []*ImportTarget
    11  
    12  	// Module is optional, and specifies a config module that is loaded
    13  	// into the graph and evaluated. The use case for this is to provide
    14  	// provider configuration.
    15  	Module *module.Tree
    16  }
    17  
    18  // ImportTarget is a single resource to import.
    19  type ImportTarget struct {
    20  	// Addr is the full resource address of the resource to import.
    21  	// Example: "module.foo.aws_instance.bar"
    22  	Addr string
    23  
    24  	// ID is the ID of the resource to import. This is resource-specific.
    25  	ID string
    26  }
    27  
    28  // Import takes already-created external resources and brings them
    29  // under Terraform management. Import requires the exact type, name, and ID
    30  // of the resources to import.
    31  //
    32  // This operation is idempotent. If the requested resource is already
    33  // imported, no changes are made to the state.
    34  //
    35  // Further, this operation also gracefully handles partial state. If during
    36  // an import there is a failure, all previously imported resources remain
    37  // imported.
    38  func (c *Context) Import(opts *ImportOpts) (*State, error) {
    39  	// Hold a lock since we can modify our own state here
    40  	v := c.acquireRun()
    41  	defer c.releaseRun(v)
    42  
    43  	// Copy our own state
    44  	c.state = c.state.DeepCopy()
    45  
    46  	// Get supported providers (for the graph builder)
    47  	providers := make([]string, 0, len(c.providers))
    48  	for k, _ := range c.providers {
    49  		providers = append(providers, k)
    50  	}
    51  
    52  	// Initialize our graph builder
    53  	builder := &ImportGraphBuilder{
    54  		ImportTargets: opts.Targets,
    55  		Module:        opts.Module,
    56  		Providers:     providers,
    57  	}
    58  
    59  	// Build the graph!
    60  	graph, err := builder.Build(RootModulePath)
    61  	if err != nil {
    62  		return c.state, err
    63  	}
    64  
    65  	// Walk it
    66  	if _, err := c.walk(graph, walkImport); err != nil {
    67  		return c.state, err
    68  	}
    69  
    70  	// Clean the state
    71  	c.state.prune()
    72  
    73  	return c.state, nil
    74  }