-
Notifications
You must be signed in to change notification settings - Fork 84
/
provider.go
337 lines (279 loc) · 11.1 KB
/
provider.go
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package ec
import (
"context"
"fmt"
"github.com/elastic/terraform-provider-ec/ec/ecdatasource/deploymenttemplates"
"time"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/provider"
"github.com/hashicorp/terraform-plugin-framework/provider/schema"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/elastic/cloud-sdk-go/pkg/api"
"github.com/elastic/terraform-provider-ec/ec/ecdatasource/deploymentdatasource"
"github.com/elastic/terraform-provider-ec/ec/ecdatasource/deploymentsdatasource"
"github.com/elastic/terraform-provider-ec/ec/ecdatasource/privatelinkdatasource"
"github.com/elastic/terraform-provider-ec/ec/ecdatasource/stackdatasource"
"github.com/elastic/terraform-provider-ec/ec/ecdatasource/trafficfilterdatasource"
"github.com/elastic/terraform-provider-ec/ec/ecresource/deploymentresource"
"github.com/elastic/terraform-provider-ec/ec/ecresource/elasticsearchkeystoreresource"
"github.com/elastic/terraform-provider-ec/ec/ecresource/extensionresource"
"github.com/elastic/terraform-provider-ec/ec/ecresource/snapshotrepositoryresource"
"github.com/elastic/terraform-provider-ec/ec/ecresource/trafficfilterassocresource"
"github.com/elastic/terraform-provider-ec/ec/ecresource/trafficfilterresource"
"github.com/elastic/terraform-provider-ec/ec/internal/util"
"github.com/elastic/terraform-provider-ec/ec/internal/validators"
)
const (
eceOnlyText = "Available only when targeting ECE Installations or Elasticsearch Service Private"
saasRequiredText = "The only valid authentication mechanism for the Elasticsearch Service"
endpointDesc = "Endpoint where the terraform provider will point to. Defaults to \"%s\"."
insecureDesc = "Allow the provider to skip TLS validation on its outgoing HTTP calls."
timeoutDesc = "Timeout used for individual HTTP calls. Defaults to \"1m\"."
verboseDesc = "When set, a \"request.log\" file will be written with all outgoing HTTP requests. Defaults to \"false\"."
verboseCredsDesc = "When set with verbose, the contents of the Authorization header will not be redacted. Defaults to \"false\"."
)
var (
apikeyDesc = fmt.Sprint("API Key to use for API authentication. ", saasRequiredText, ".")
usernameDesc = fmt.Sprint("Username to use for API authentication. ", eceOnlyText, ".")
passwordDesc = fmt.Sprint("Password to use for API authentication. ", eceOnlyText, ".")
validURLSchemes = []string{"http", "https"}
// defaultTimeout used for all outgoing HTTP requests, keeping it low-ish
// since any requests which timeout due to network factors are retried
// automatically by the SDK 2 times.
defaultTimeout = 40 * time.Second
)
func New(version string) provider.Provider {
return &Provider{version: version}
}
func ProviderWithClient(client *api.API, version string) provider.Provider {
return &Provider{client: client, version: version}
}
var _ provider.Provider = (*Provider)(nil)
type Provider struct {
version string
client *api.API
}
func (p *Provider) Metadata(ctx context.Context, request provider.MetadataRequest, response *provider.MetadataResponse) {
response.TypeName = "ec"
}
func (p *Provider) DataSources(ctx context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{
func() datasource.DataSource { return &deploymentdatasource.DataSource{} },
func() datasource.DataSource { return &deploymentsdatasource.DataSource{} },
func() datasource.DataSource { return &stackdatasource.DataSource{} },
func() datasource.DataSource { return &trafficfilterdatasource.DataSource{} },
privatelinkdatasource.AwsDataSource,
privatelinkdatasource.GcpDataSource,
privatelinkdatasource.AzureDataSource,
func() datasource.DataSource { return &deploymenttemplates.DataSource{} },
}
}
func (p *Provider) Resources(ctx context.Context) []func() resource.Resource {
return []func() resource.Resource{
func() resource.Resource { return &elasticsearchkeystoreresource.Resource{} },
func() resource.Resource { return &extensionresource.Resource{} },
func() resource.Resource { return &deploymentresource.Resource{} },
func() resource.Resource { return &snapshotrepositoryresource.Resource{} },
func() resource.Resource { return &trafficfilterresource.Resource{} },
func() resource.Resource { return &trafficfilterassocresource.Resource{} },
}
}
func (p *Provider) Schema(_ context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
Attributes: map[string]schema.Attribute{
"endpoint": schema.StringAttribute{
Description: fmt.Sprintf(endpointDesc, api.ESSEndpoint),
Optional: true,
Validators: []validator.String{
validators.Known(),
validators.IsURLWithSchemeValidator(validURLSchemes),
},
},
"apikey": schema.StringAttribute{
Description: apikeyDesc,
Optional: true,
Sensitive: true,
},
"username": schema.StringAttribute{
Description: usernameDesc,
Optional: true,
},
"password": schema.StringAttribute{
Description: passwordDesc,
Optional: true,
Sensitive: true,
},
"insecure": schema.BoolAttribute{
Description: insecureDesc,
Optional: true,
},
"timeout": schema.StringAttribute{
Description: timeoutDesc,
Optional: true,
},
"verbose": schema.BoolAttribute{
Description: verboseDesc,
Optional: true,
},
"verbose_credentials": schema.BoolAttribute{
Description: verboseCredsDesc,
Optional: true,
},
"verbose_file": schema.StringAttribute{
Description: timeoutDesc,
Optional: true,
},
},
}
}
// Retrieve provider data from configuration
type providerConfig struct {
Endpoint types.String `tfsdk:"endpoint"`
ApiKey types.String `tfsdk:"apikey"`
Username types.String `tfsdk:"username"`
Password types.String `tfsdk:"password"`
Insecure types.Bool `tfsdk:"insecure"`
Timeout types.String `tfsdk:"timeout"`
Verbose types.Bool `tfsdk:"verbose"`
VerboseCredentials types.Bool `tfsdk:"verbose_credentials"`
VerboseFile types.String `tfsdk:"verbose_file"`
}
func (p *Provider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
if p.client != nil {
// Required for unit tests, because a mock client is pre-created there.
resp.DataSourceData = p.client
resp.ResourceData = p.client
return
}
var config providerConfig
diags := req.Config.Get(ctx, &config)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
endpoint := config.Endpoint.ValueString()
if config.Endpoint.ValueString() == "" {
endpoint = util.MultiGetenvOrDefault([]string{"EC_ENDPOINT", "EC_HOST"}, api.ESSEndpoint)
diags := validateEndpoint(ctx, endpoint)
resp.Diagnostics.Append(diags...)
if diags.HasError() {
return
}
}
apiKey := config.ApiKey.ValueString()
if config.ApiKey.ValueString() == "" {
apiKey = util.MultiGetenvOrDefault([]string{"EC_API_KEY"}, "")
}
username := config.Username.ValueString()
if config.Username.ValueString() == "" {
username = util.MultiGetenvOrDefault([]string{"EC_USER", "EC_USERNAME"}, "")
}
password := config.Password.ValueString()
if config.Password.ValueString() == "" {
password = util.MultiGetenvOrDefault([]string{"EC_PASS", "EC_PASSWORD"}, "")
}
timeoutStr := config.Timeout.ValueString()
if config.Timeout.ValueString() == "" {
timeoutStr = util.MultiGetenvOrDefault([]string{"EC_TIMEOUT"}, defaultTimeout.String())
}
timeout, err := time.ParseDuration(timeoutStr)
if err != nil {
resp.Diagnostics.AddError("Unable to create client", err.Error())
return
}
insecure := config.Insecure.ValueBool()
if config.Insecure.IsNull() {
insecureStr := util.MultiGetenvOrDefault([]string{"EC_INSECURE", "EC_SKIP_TLS_VALIDATION"}, "")
if insecure, err = util.StringToBool(insecureStr); err != nil {
resp.Diagnostics.AddError(
"Unable to create client",
fmt.Sprintf("Invalid value '%v' in 'EC_INSECURE' or 'EC_SKIP_TLS_VALIDATION'", insecureStr),
)
return
}
}
verbose := config.Verbose.ValueBool()
if config.Verbose.IsNull() {
verboseStr := util.MultiGetenvOrDefault([]string{"EC_VERBOSE"}, "")
if verbose, err = util.StringToBool(verboseStr); err != nil {
resp.Diagnostics.AddError(
"Unable to create client",
fmt.Sprintf("Invalid value '%v' in 'EC_VERBOSE'", verboseStr),
)
return
}
}
verboseCredentials := config.VerboseCredentials.ValueBool()
if config.VerboseCredentials.IsNull() {
verboseCredentialsStr := util.MultiGetenvOrDefault([]string{"EC_VERBOSE_CREDENTIALS"}, "")
if verboseCredentials, err = util.StringToBool(verboseCredentialsStr); err != nil {
resp.Diagnostics.AddError(
"Unable to create client",
fmt.Sprintf("Invalid value '%v' in 'EC_VERBOSE_CREDENTIALS'", verboseCredentialsStr),
)
return
}
}
verboseFile := config.VerboseFile.ValueString()
if config.VerboseFile.IsNull() {
verboseFile = util.MultiGetenvOrDefault([]string{"EC_VERBOSE_FILE"}, "request.log")
}
cfg, err := newAPIConfig(apiSetup{
endpoint: endpoint,
apikey: apiKey,
username: username,
password: password,
insecure: insecure,
timeout: timeout,
verbose: verbose,
verboseCredentials: verboseCredentials,
verboseFile: verboseFile,
})
if err != nil {
resp.Diagnostics.AddError(
"Unable to create api Client config",
err.Error(),
)
return
}
client, err := api.NewAPI(cfg)
if err != nil {
resp.Diagnostics.AddError(
"Unable to create api Client config",
err.Error(),
)
return
}
p.client = client
resp.DataSourceData = client
resp.ResourceData = client
}
func validateEndpoint(ctx context.Context, endpoint string) diag.Diagnostics {
validateReq := validator.StringRequest{
Path: path.Root("endpoint"),
ConfigValue: types.StringValue(endpoint),
}
validateResp := validator.StringResponse{}
validators.IsURLWithSchemeValidator(validURLSchemes).ValidateString(ctx, validateReq, &validateResp)
return validateResp.Diagnostics
}