-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovider.go
More file actions
204 lines (177 loc) · 6.51 KB
/
provider.go
File metadata and controls
204 lines (177 loc) · 6.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"context"
"os"
// Packages
datasource "github.com/hashicorp/terraform-plugin-framework/datasource"
provider "github.com/hashicorp/terraform-plugin-framework/provider"
tfschema "github.com/hashicorp/terraform-plugin-framework/provider/schema"
resource "github.com/hashicorp/terraform-plugin-framework/resource"
types "github.com/hashicorp/terraform-plugin-framework/types"
tflog "github.com/hashicorp/terraform-plugin-log/tflog"
client "github.com/mutablelogic/go-client"
httpclient "github.com/mutablelogic/go-server/pkg/provider/httpclient"
schema "github.com/mutablelogic/go-server/pkg/provider/schema"
)
///////////////////////////////////////////////////////////////////////////////
// TYPES
// kaiakProvider implements the Terraform provider for a running Kaiak server.
type kaiakProvider struct {
version string
endpoint string // resolved during Configure; used by Resources for discovery
apiKey string // resolved during Configure; used by Resources for discovery
}
// kaiakProviderModel maps provider schema data to a Go type.
type kaiakProviderModel struct {
Endpoint types.String `tfsdk:"endpoint"`
ApiKey types.String `tfsdk:"api_key"`
}
var _ provider.Provider = (*kaiakProvider)(nil)
///////////////////////////////////////////////////////////////////////////////
// LIFECYCLE
// New returns a provider factory that creates a new provider instance
// with the given version. It is called by the plugin framework.
func New(v string) func() provider.Provider {
return func() provider.Provider {
return &kaiakProvider{version: v}
}
}
// resolveEndpoint returns the API endpoint from the environment, falling
// back to a sensible default.
func resolveEndpoint() string {
if v := os.Getenv("KAIAK_ENDPOINT"); v != "" {
return v
}
return "http://localhost:8084/api"
}
// resolveApiKey returns the API key from the environment, or empty string.
func resolveApiKey() string {
return os.Getenv("KAIAK_API_KEY")
}
// clientOpts returns the common client options for the given API key,
// including request tracing when KAIAK_TRACE is set.
func clientOpts(apiKey string) []client.ClientOpt {
var opts []client.ClientOpt
if apiKey != "" {
opts = append(opts, client.OptReqToken(client.Token{
Scheme: client.Bearer,
Value: apiKey,
}))
}
if os.Getenv("KAIAK_TRACE") != "" {
verbose := os.Getenv("KAIAK_TRACE") == "verbose"
opts = append(opts, client.OptTrace(os.Stderr, verbose))
}
return opts
}
///////////////////////////////////////////////////////////////////////////////
// PROVIDER INTERFACE
func (p *kaiakProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "kaiak"
resp.Version = p.version
}
func (p *kaiakProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = tfschema.Schema{
Description: "Manage resources on a running Kaiak server.",
Attributes: map[string]tfschema.Attribute{
"endpoint": tfschema.StringAttribute{
Description: "Base URL of the Kaiak server API (e.g. http://localhost:8084/api). " +
"Can also be set via the KAIAK_ENDPOINT environment variable.",
Optional: true,
},
"api_key": tfschema.StringAttribute{
Description: "API key (bearer token) for authenticating with the Kaiak server. " +
"Can also be set via the KAIAK_API_KEY environment variable.",
Optional: true,
Sensitive: true,
},
},
}
}
func (p *kaiakProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
var config kaiakProviderModel
resp.Diagnostics.Append(req.Config.Get(ctx, &config)...)
if resp.Diagnostics.HasError() {
return
}
// Reject unknown values — they can cause silent fallback to env/defaults
if config.Endpoint.IsUnknown() {
resp.Diagnostics.AddError("Unknown endpoint",
"The \"endpoint\" attribute is not yet known. Set it to a concrete value or use the KAIAK_ENDPOINT environment variable.")
return
}
if config.ApiKey.IsUnknown() {
resp.Diagnostics.AddError("Unknown api_key",
"The \"api_key\" attribute is not yet known. Set it to a concrete value or use the KAIAK_API_KEY environment variable.")
return
}
// Resolve endpoint: config value > environment variable > default
endpoint := config.Endpoint.ValueString()
if endpoint == "" {
endpoint = resolveEndpoint()
}
// Resolve API key: config value > environment variable
apiKey := config.ApiKey.ValueString()
if apiKey == "" {
apiKey = resolveApiKey()
}
// Cache resolved values so Resources() uses the same settings
p.endpoint = endpoint
p.apiKey = apiKey
// Create the HTTP client
cl, err := httpclient.New(endpoint, clientOpts(apiKey)...)
if err != nil {
resp.Diagnostics.AddError("Failed to create Kaiak client", err.Error())
return
}
// Make the client available to resources and data sources
resp.DataSourceData = cl
resp.ResourceData = cl
}
// Resources discovers resource types from the running Kaiak server and
// returns a factory for each one. The server must be reachable at schema-
// discovery time (i.e. during terraform plan / apply).
//
// When Configure() has already run, the provider-configured endpoint and
// API key are used. Otherwise (e.g. during validate or early plan phases)
// the values fall back to KAIAK_ENDPOINT / KAIAK_API_KEY env vars.
func (p *kaiakProvider) Resources(ctx context.Context) []func() resource.Resource {
// Prefer values cached from Configure(); fall back to env vars
endpoint := p.endpoint
if endpoint == "" {
endpoint = resolveEndpoint()
}
apiKey := p.apiKey
if apiKey == "" {
apiKey = resolveApiKey()
}
cl, err := httpclient.New(endpoint, clientOpts(apiKey)...)
if err != nil {
tflog.Error(ctx, "Failed to create Kaiak client. No resources will be available.", map[string]interface{}{
"endpoint": endpoint,
"error": err.Error(),
})
return nil
}
result, err := cl.ListResources(ctx, schema.ListResourcesRequest{})
if err != nil {
tflog.Error(ctx, "Failed to discover resources from Kaiak server. No resources will be available.", map[string]interface{}{
"endpoint": endpoint,
"error": err.Error(),
})
return nil
}
factories := make([]func() resource.Resource, 0, len(result.Resources))
for _, r := range result.Resources {
meta := r // capture
factories = append(factories, func() resource.Resource {
return newDynamicResource(meta)
})
}
return factories
}
func (p *kaiakProvider) DataSources(_ context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{
NewResourcesDataSource,
}
}