Переглянути джерело

Tutorial 8: import. Generation working.

Frédéric G. MARAND 5 місяців тому
батько
коміт
38f6cf6f44

+ 6 - 0
examples/order/imports.tf

@@ -0,0 +1,6 @@
+# import {
+#   to = hashicups_order.edu
+#   id = "7"
+# }
+#
+#

+ 8 - 4
examples/order/main.tf

@@ -7,7 +7,7 @@ terraform {
 }
 
 provider "hashicups" {
-  host = "http://localhost:19090"
+  host     = "http://localhost:19090"
   username = "education"
   password = "test123"
 }
@@ -15,11 +15,15 @@ provider "hashicups" {
 resource "hashicups_order" "edu" {
   items = [
     {
-      coffee = { id = 3 }
+      coffee = {
+        id = 3
+      }
       quantity = 2
     },
     {
-      coffee = { id = 2 }
+      coffee = {
+        id = 2
+      }
       quantity = 2
     },
   ]
@@ -27,4 +31,4 @@ resource "hashicups_order" "edu" {
 
 output "edu_order" {
   value = hashicups_order.edu
-}
+}

+ 12 - 2
internal/provider/order_resource.go

@@ -7,6 +7,7 @@ import (
 	"time"
 
 	"github.com/hashicorp-demoapp/hashicups-client-go"
+	"github.com/hashicorp/terraform-plugin-framework/path"
 	"github.com/hashicorp/terraform-plugin-framework/resource"
 	"github.com/hashicorp/terraform-plugin-framework/resource/schema"
 	"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
@@ -16,8 +17,9 @@ import (
 
 // Ensure the implementation satisfies the expected interfaces.
 var (
-	_ resource.Resource              = &orderResource{}
-	_ resource.ResourceWithConfigure = &orderResource{}
+	_ resource.Resource                = &orderResource{}
+	_ resource.ResourceWithConfigure   = &orderResource{}
+	_ resource.ResourceWithImportState = &orderResource{}
 )
 
 // NewOrderResource is a helper function to simplify the provider implementation.
@@ -132,6 +134,7 @@ func (r *orderResource) Configure(_ context.Context, req resource.ConfigureReque
 
 // Create a new resource.
 func (r *orderResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
+	// Retrieve values from plan
 	var plan orderResourceModel
 
 	// 1. Checks whether the API Client is configured.
@@ -366,3 +369,10 @@ func (r *orderResource) Delete(ctx context.Context, req resource.DeleteRequest,
 		return
 	}
 }
+
+func (r *orderResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
+	// Retrieves import identifier and saves to attribute state.
+	// The method will use the resource.ImportStatePassthroughID() function
+	// to retrieve the ID value from the terraform import command and save it to the id attribute.
+	resource.ImportStatePassthroughID(ctx, path.Root("id"), req, resp)
+}