当前位置:网站首页>自定义Terraform-Providers(Terraform Plugin Framework)-04
自定义Terraform-Providers(Terraform Plugin Framework)-04
2022-06-11 13:12:00 【华为云】
一 前言
Terraform插件框架是开发Terraform插件的一种新方法。它具有Terraform插件SDKv2所缺少的特性,包括:
- 确定是否在配置、状态或计划中设置了值。
- 确定值是null、未知还是空值。
- 具有结构化类型,如对象。
- 本机使用嵌套属性。
在本教程中,您将使用Terraform插件框架,为一个虚构的咖啡店应用程序(HashiCups)的提供程序添加创建和读取功能。首先,您将回顾provider和resource schema,以了解provider如何使用插件框架将Go结构映射到schema属性。然后,在自己实现资源之前,您将探索与创建和读取资源相关联的步骤。最后,您将测试提供程序。
HashiCups API有不受保护的端点,允许您列出特定咖啡的所有咖啡和成分。经过身份验证后,可以创建、读取、更新和删除(CRUD)订单。HashiCups提供程序通过GoLang客户机库与HashiCups REST API接口。这允许您通过Terraform管理HashiCups订单。
这个框架是实验性的。不要在生产或关键环境中使用。在Terraform插件框架Github存储库中向开发团队提交任何问题。有关反馈和讨论,请访问插件SDK讨论论坛。
二 预置条件
对于本教程,您将需要:
- 安装并配置Go1.16+。的
- Terraform V1.0.3+已在本地安装。
- Docker和Docker组合在本地运行HashiCups实例。
- 安装了jq。
三 配置开发环境
git clone --branch boilerplate https://github.com/hashicorp/terraform-provider-hashicups-pfcd terraform-provider-hashicups-pf四 启动项目
cd docker_composedocker-compose up -dcurl localhost:19090/health五 创建用户
$ 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六 开发HashiCups provider
main.go文件
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", })}打开hashicups/provider.go。
首先,提供程序调用新函数来调用提供程序的实例。请注意,该文件还定义了一个带有客户端的提供程序结构。像SDKv2一样,Terraform提供程序应该与API客户机接口,而不是直接向API提交请求。
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}接下来,提供程序定义一个模式,Terraform将使用该模式来配置HashiCups API客户机。providerData结构将这些模式属性映射到易于访问的值。
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 定义资源和数据源
GetResources和GetDataSources函数定义提供者的资源和数据源。HashiCups提供程序的这个样板版本有一个名为HashiCups\u order的资源,不定义任何数据源。
// 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 查看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 实现具体方法
6.2.1 创建方法
- 检查是否配置了提供程序和API客户端。如果不是,提供程序将以错误响应。
- 从计划中检索值。该函数将尝试从计划中检索值,并将其转换为Order结构(在models.go中定义)。
- 从计划值生成API请求正文。该函数循环遍历每个计划项,并将其映射到HashiCups.OrderItem。这就是API客户机创建新订单所需要的。
- 创建新订单。该函数调用API客户端的CreateOrder方法。
- 将响应正文映射到资源架构属性。函数创建订单后,它将HashiCups.order响应映射到[]OrderItem,这样提供者就可以更新Terraform状态。
- 将状态设置为新顺序。
6.2.2 读取方法
- 获取当前状态。如果不能,则提供程序将以错误进行响应。
- 从状态检索订单ID。
- 获取订单的信息。该函数使用订单ID调用API客户机的GetOrder方法。
- 将响应正文映射到资源架构属性。函数检索订单后,它将HashiCups.order响应映射到[]OrderItem,这样提供者就可以更新Terraform状态。
- 将状态设置为新顺序。
七 执行构建
go env GOBIN创建文件
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参考链接
边栏推荐
- 2022 年,捕捉这 12 个数据和分析趋势!
- 五年官司终败诉,万亿爬虫大军蠢蠢欲动
- 逆向学习入门-优秀的汇编调试工具OllyDbg
- 历史上的今天:Apple II 问世;微软收购 GECAD;发明“软件工程”一词的科技先驱出生...
- Schematic drawing for pads
- China's SaaS development lags behind that of the United States for 10 years, and it still needs to rely on innovation, open source, M & A and other strategies | archsummit
- Network information system emergency response
- Does it affect children to wear Bluetooth headsets? How to protect children's ear health
- Luo Jing: connection Efficiency Optimization Practice
- Chapter V data type (IV)
猜你喜欢

The end of an era! After ten years, Wu Enda's classic machine learning course closed its registration this month and launched a new course

Log management system, summary in multiple ways

Introduction to common fonts

Tawang food industry insight | China's dairy market analysis, competition pattern, development trend and thinking

Condition debug of pycharm

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

關於分布式鎖的續命問題——基於Redis實現的分布式鎖

模态框关闭后清空模态框里选择的数据

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

网络信息系统应急响应
随机推荐
Quic resistance
. 5 string
Log management system, summary in multiple ways
分页浏览后搜索无数据
Luo Jing: connection Efficiency Optimization Practice
ecplise无法连接sql server
How to synchronize openstack RDO source to local for offline installation
LNMP部署
tf.data(二) —— 并行化 tf.data.Dataset 生成器
【增加功能】select下拉多选 显示选中的人员
Application of pip2pi, pypiserver and Apache in PIP local source configuration
Niu Mei and 01 Chuan
历史上的今天:Apple II 问世;微软收购 GECAD;发明“软件工程”一词的科技先驱出生...
UI inspiration analysis Notes 6: feature
Go 如何减少供应链攻击?
【信号处理】数字信号处理Matlab设计附GUI界面和报告
Matrix elimination game
. The way to prove the effect of throwing exceptions on performance in. Net core
Zhongfu Jinshi: with the rapid development of the intelligent bathroom industry, the intelligent toilet will usher in a highlight moment
Musk says he doesn't like being a CEO, but rather wants to do technology and design; Wu Enda's "machine learning" course is about to close its registration | geek headlines