diff --git a/internal/terraform/context_plan_import_test.go b/internal/terraform/context_plan_import_test.go index acff2cec7f07..caf753198511 100644 --- a/internal/terraform/context_plan_import_test.go +++ b/internal/terraform/context_plan_import_test.go @@ -2217,3 +2217,61 @@ func TestContext2Plan_importIdentityModuleWithOptional(t *testing.T) { tfdiags.ObjectToString(wantIdentity)) } } + +func TestContext2Plan_importIdentityMissingResponse(t *testing.T) { + p := testProvider("aws") + m := testModule(t, "import-identity-module") + + p.GetProviderSchemaResponse = getProviderSchemaResponseFromProviderSchema(&providerSchema{ + ResourceTypes: map[string]*configschema.Block{ + "aws_lb": { + Attributes: map[string]*configschema.Attribute{ + "id": { + Type: cty.String, + Computed: true, + }, + }, + }, + }, + IdentityTypes: map[string]*configschema.Object{ + "aws_lb": { + Attributes: map[string]*configschema.Attribute{ + "name": { + Type: cty.String, + Required: true, + }, + }, + Nesting: configschema.NestingSingle, + }, + }, + }) + p.ImportResourceStateResponse = &providers.ImportResourceStateResponse{ + ImportedResources: []providers.ImportedResource{ + { + TypeName: "aws_lb", + State: cty.ObjectVal(map[string]cty.Value{ + "id": cty.StringVal("foo"), + }), + // No identity returned + }, + }, + } + ctx := testContext2(t, &ContextOpts{ + Providers: map[addrs.Provider]providers.Factory{ + addrs.NewDefaultProvider("aws"): testProviderFuncFixed(p), + }, + }) + + diags := ctx.Validate(m, &ValidateOpts{}) + if diags.HasErrors() { + t.Fatalf("unexpected errors\n%s", diags.Err().Error()) + } + + _, diags = ctx.Plan(m, states.NewState(), DefaultPlanOpts) + if !diags.HasErrors() { + t.Fatal("succeeded; want errors") + } + if got, want := diags.Err().Error(), `import of aws_lb.foo didn't return an identity`; !strings.Contains(got, want) { + t.Fatalf("wrong error:\ngot: %s\nwant: message containing %q", got, want) + } +} diff --git a/internal/terraform/node_resource_plan_instance.go b/internal/terraform/node_resource_plan_instance.go index f181508b043c..fc311e2904ed 100644 --- a/internal/terraform/node_resource_plan_instance.go +++ b/internal/terraform/node_resource_plan_instance.go @@ -753,6 +753,12 @@ func (n *NodePlannableResourceInstance) importState(ctx EvalContext, addr addrs. return nil, deferred, diags } + // Providers are supposed to return an identity when importing by identity + if importTarget.Type().IsObjectType() && imported[0].Identity.IsNull() { + diags = diags.Append(fmt.Errorf("import of %s didn't return an identity", n.Addr.String())) + return nil, deferred, diags + } + // Providers are supposed to return null values for all write-only attributes writeOnlyDiags := ephemeral.ValidateWriteOnlyAttributes( "Import returned a non-null value for a write-only attribute", @@ -782,7 +788,6 @@ func (n *NodePlannableResourceInstance) importState(ctx EvalContext, addr addrs. importType, importValue, ), )) - } // refresh