diff --git a/internal/terraform/context_import.go b/internal/terraform/context_import.go index ce5df08f5fb3..ac469e3cb85b 100644 --- a/internal/terraform/context_import.go +++ b/internal/terraform/context_import.go @@ -82,6 +82,11 @@ func (c *Context) Import(config *configs.Config, prevRunState *states.State, opt return state, diags } + // Data sources which could not be read during the import plan will be + // unknown. We need to strip those objects out so that the state can be + // serialized. + walker.State.RemovePlannedResourceInstanceObjects() + newState := walker.State.Close() return newState, diags } diff --git a/internal/terraform/context_import_test.go b/internal/terraform/context_import_test.go index af8ff4b856be..dc773dcf1f86 100644 --- a/internal/terraform/context_import_test.go +++ b/internal/terraform/context_import_test.go @@ -430,7 +430,24 @@ func TestContextImport_providerConfigResources(t *testing.T) { func TestContextImport_refresh(t *testing.T) { p := testProvider("aws") - m := testModule(t, "import-provider") + m := testModuleInline(t, map[string]string{ + "main.tf": ` +provider "aws" { + foo = "bar" +} + +resource "aws_instance" "foo" { +} + + +// we are only importing aws_instance.foo, so these resources will be unknown +resource "aws_instance" "bar" { +} +data "aws_data_source" "bar" { + foo = aws_instance.bar.id +} +`}) + ctx := testContext2(t, &ContextOpts{ Providers: map[addrs.Provider]providers.Factory{ addrs.NewDefaultProvider("aws"): testProviderFuncFixed(p), @@ -448,6 +465,13 @@ func TestContextImport_refresh(t *testing.T) { }, } + p.ReadDataSourceResponse = &providers.ReadDataSourceResponse{ + State: cty.ObjectVal(map[string]cty.Value{ + "id": cty.StringVal("id"), + "foo": cty.UnknownVal(cty.String), + }), + } + p.ReadResourceFn = nil p.ReadResourceResponse = &providers.ReadResourceResponse{ @@ -471,6 +495,10 @@ func TestContextImport_refresh(t *testing.T) { t.Fatalf("unexpected errors: %s", diags.Err()) } + if d := state.ResourceInstance(mustResourceInstanceAddr("data.aws_data_source.bar")); d != nil { + t.Errorf("data.aws_data_source.bar has a status of ObjectPlanned and should not be in the state\ngot:%#v\n", d.Current) + } + actual := strings.TrimSpace(state.String()) expected := strings.TrimSpace(testImportRefreshStr) if actual != expected {