当前位置:网站首页>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-pfFour Start project
cd docker_composedocker-compose up -dcurl localhost:19090/health5、 ... 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-lerdBvyCYaUZCnJM4m4AY6、 ... 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 GOBINcreate 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 installReference link
边栏推荐
- I am a graduating doctor majoring in mathematics. How should I choose an offer?
- 逆向学习入门-优秀的汇编调试工具OllyDbg
- 【信号处理】数字信号处理Matlab设计附GUI界面和报告
- Hashicopy之nomad应用编排方案08(检测Job)
- JSP实现银柜台业务绩效考核系统
- 网络信息系统应急响应
- LNMP deployment
- Is byte really the end of the universe?
- 从QUIC到TCP
- [filter] design of time-varying Wiener filter based on MATLAB [including Matlab source code 1870]
猜你喜欢

31w赛题奖金!当 AI for Science 撞上“先导杯”,会擦出什么样的火花?

常用字体介绍

Ecplise cannot connect to SQL Server

Explain in detail the differences between real participation formal parameters in C language

【后台交互】select 绑定后台传递的数据

TeaTalk·Online 演讲实录 | 圆满完结!安全上云,选对数据迁移策略很重要
![[arcgis] City relevance analysis](/img/f4/454266e1ed586240bce9a7f36aa52e.png)
[arcgis] City relevance analysis

关于分布式锁的续命问题——基于Redis实现的分布式锁

Which brand of bone conduction Bluetooth headset is good? Five most popular bone conduction Bluetooth headsets

The Tree (AVL, 2-3-, 红黑,Huffman)
随机推荐
网络信息系统应急响应
Quic resistance
Go 如何减少供应链攻击?
【信号处理】数字信号处理Matlab设计附GUI界面和报告
面试造航母,入职拧螺丝,工资...
[background interaction] select to bind the data transferred in the background
SQL的语法
模态框关闭后清空模态框里选择的数据
NFT市场怎么样 为什么NFT能如此火爆 怎么搭建NFT平台
【bug解决】上传图片后,取消这次上传 再次执行上传,上次的图片还存在
[problem summary] $t
Research on DB2 Database Reconstruction and table data migration
Dbutil auxiliary class, manual commit transaction, metadata
Can't understand kotlin source code? Starting with the contracts function~
LNMP部署
. The way to prove the effect of throwing exceptions on performance in. Net core
jdbctemplate数据后台管理,不知道为什么添加用户的时候显示roleId为空
/usr/bin/gzip: 1: ELF: not found /usr/bin/gzip: 3: : not found /usr/bin/gzip: 4: Syntax erro
关于#php#的问题:php写的原来的部署环境是在phpstudy里面进行部署的,php+MySQL+Apache但是由于每次都得保证电脑开着
【问题总结】$t