当前位置:网站首页>Customize terrain providers (terrain plugin framework) -04

Customize terrain providers (terrain plugin framework) -04

2022-06-11 13:18:00 Hua Weiyun

One Preface

Terraform The plug-in framework is for development Terraform A new method of plug-ins . It has Terraform plug-in unit SDKv2 Missing features , Include :

  • Determine if you are configuring 、 A value is set in the status or plan .
  • The determined value is null、 Unknown or null .
  • Have structured types , Such as the object .
  • Nested attributes are used natively .

In this tutorial , You will use Terraform Plug in framework , For a fictional coffee shop application (HashiCups) Add create and read functions to the provider of . First , You will review provider and resource schema, To understand provider How to use the plug-in framework to Go Structure maps to schema attribute . then , Before you implement resources yourself , You will explore the steps associated with creating and reading resources . Last , You will test the provider .

HashiCups API There are unprotected endpoints , Allows you to list all the coffee and ingredients for a particular coffee . After authentication , You can create 、 Read 、 Update and delete (CRUD) Order .HashiCups The provider passed GoLang Client libraries and HashiCups REST API Interface . This allows you to pass Terraform management HashiCups Order .

This framework is experimental . Do not use in production or critical environments . stay Terraform Plug in framework Github Submit any questions to the development team in the repository . About feedback and discussion , Please visit the plug-in SDK Discussion Forum .

Two Preset conditions

For this tutorial , You will need :

  • Install and configure Go1.16+. Of
  • Terraform V1.0.3+ Installed locally .
  • Docker and Docker The combination runs locally HashiCups example .
  • Installed jq.

3、 ... and Configure the development environment

git clone --branch boilerplate https://github.com/hashicorp/terraform-provider-hashicups-pfcd terraform-provider-hashicups-pf

Four Start project

cd docker_composedocker-compose up -dcurl localhost:19090/health

5、 ... and Create user

$ curl -X POST localhost:19090/signup -d '{"username":"education", "password":"test123"}'{"UserID":1,"Username":"education","token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NTQ4MjU4ODYsInVzZXJfaWQiOjEsInVzZXJuYW1lIjoiZWR1Y2F0aW9uIn0.DD1LxrJJL05wKJ56f8FSm-lerdBvyCYaUZCnJM4m4AY"}$ export HASHICUPS_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NTQ4MjU4ODYsInVzZXJfaWQiOjEsInVzZXJuYW1lIjoiZWR1Y2F0aW9uIn0.DD1LxrJJL05wKJ56f8FSm-lerdBvyCYaUZCnJM4m4AY

6、 ... and Development HashiCups provider

main.go file

package mainimport (    "context"    "github.com/hashicorp/terraform-plugin-framework/tfsdk"    "terraform-provider-hashicups/hashicups")func main() {    tfsdk.Serve(context.Background(), hashicups.New, tfsdk.ServeOpts{        Name: "hashicups",    })}

open hashicups/provider.go.
First , The provider calls a new function to call an instance of the provider . Please note that , This file also defines a provider structure with a client . image SDKv2 equally ,Terraform The provider should work with API Client interface , Not directly to API Submit a request .

package hashicupsimport (    "context"    "os"    "github.com/hashicorp-demoapp/hashicups-client-go"    "github.com/hashicorp/terraform-plugin-framework/diag"    "github.com/hashicorp/terraform-plugin-framework/tfsdk"    "github.com/hashicorp/terraform-plugin-framework/types")var stderr = os.Stderrfunc New() tfsdk.Provider {    return &provider{}}type provider struct {    configured bool    client     *hashicups.Client}

Next , The provider defines a schema ,Terraform This mode will be used to configure HashiCups API The client .providerData Structure maps these schema attributes to easily accessible values .

hashicups/provider.go

// GetSchemafunc (p *provider) GetSchema(_ context.Context) (tfsdk.Schema, diag.Diagnostics) {    return tfsdk.Schema{        Attributes: map[string]tfsdk.Attribute{            "host": {                Type:     types.StringType,                Optional: true,                Computed: true,            },            "username": {                Type:     types.StringType,                Optional: true,                Computed: true,            },            "password": {                Type:      types.StringType,                Optional:  true,                Computed:  true,                Sensitive: true,            },        },    }, nil}// Provider schema structtype providerData struct {    Username types.String `tfsdk:"username"`    Host     types.String `tfsdk:"host"`    Password types.String `tfsdk:"password"`}

6.1 Define resources and data sources

GetResources and GetDataSources Function to define the provider's resources and data sources .HashiCups This template version of the provider has a named HashiCups\u order Resources for , No data sources are defined .

// GetResources - Defines provider resourcesfunc (p *provider) GetResources(_ context.Context) (map[string]tfsdk.ResourceType, diag.Diagnostics) {    return map[string]tfsdk.ResourceType{        "hashicups_order": resourceOrderType{},    }, nil}// GetDataSources - Defines provider data sourcesfunc (p *provider) GetDataSources(_ context.Context) (map[string]tfsdk.DataSourceType, diag.Diagnostics) {    return map[string]tfsdk.DataSourceType{}, nil}

6.2 see Review HashiCups models

package hashicupsimport (	"github.com/hashicorp/terraform-plugin-framework/types")// Order -type Order struct {	ID          types.String `tfsdk:"id"`	Items       []OrderItem  `tfsdk:"items"`	LastUpdated types.String `tfsdk:"last_updated"`}// OrderItem -type OrderItem struct {	Coffee   Coffee `tfsdk:"coffee"`	Quantity int    `tfsdk:"quantity"`}// Coffee -// This Coffee struct is for Order.Items[].Coffee which does not have an// ingredients field in the schema defined by plugin framework. Since the// resource schema must match the struct exactly (extra field will return an// error). This struct has Ingredients commented out.type Coffee struct {	ID          int          `tfsdk:"id"`	Name        types.String `tfsdk:"name"`	Teaser      types.String `tfsdk:"teaser"`	Description types.String `tfsdk:"description"`	Price       types.Number `tfsdk:"price"`	Image       types.String `tfsdk:"image"`	// Ingredients []Ingredient `tfsdk:"ingredients"`}// Ingredient -// type Ingredient struct {// ID int `tfsdk:"ingredient_id"`// Name string `tfsdk:"name"`// Quantity int `tfsdk:"quantity"`// Unit string `tfsdk:"unit"`// }

6.3 How to achieve it

6.2.1 Create method

  • Check if the provider and are configured API client . If not , The provider will respond with an error .
  • Retrieve values from the plan . This function will attempt to retrieve values from the plan , And convert it to Order structure ( stay models.go In the definition of ).
  • Generate... From plan values API Request body . This function iterates through each plan item , And map it to HashiCups.OrderItem. This is it. API What the client needs to create a new order .
  • Create new order . This function call API Client's CreateOrder Method .
  • Map the response body to the resource schema attribute . Function to create an order , It will HashiCups.order The response maps to []OrderItem, So the provider can update Terraform state .
  • Set the status to the new sequence .

6.2.2 Reading method

  • Get current status . If not , The provider will respond with an error .
  • Retrieve order from status ID.
  • Get order information . This function uses the order ID call API Of the client GetOrder Method .
  • Map the response body to the resource schema attribute . Function to retrieve the order , It will HashiCups.order The response maps to []OrderItem, So the provider can update Terraform state .
  • Set the status to the new sequence .

7、 ... and Execute build

go env GOBIN

create a file

provider_installation {  dev_overrides {      "hashicorp.com/edu/hashicups-pf" = "<PATH>"  }  # For all other providers, install them directly from their origin provider  # registries as normal. If you omit this, Terraform will _only_ use  # the dev_overrides block, and so no other providers will be available.  direct {}}
go mod tidygo install

Reference link

原网站

版权声明
本文为[Hua Weiyun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111312171561.html