-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathprovider.go
432 lines (396 loc) · 14.4 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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
package provider
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/tmunzer/mistapi-go/mistapi/models"
"os"
"github.com/tmunzer/mistapi-go/mistapi"
"github.com/hashicorp/terraform-plugin-framework-validators/float64validator"
"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"
)
const (
defaultTag = "v0.0.0"
defaultApiTimeout = 10
)
var _ provider.Provider = (*mistProvider)(nil)
func New() func() provider.Provider {
return func() provider.Provider {
return &mistProvider{}
}
}
type mistProvider struct {
version string
}
type mistProviderData struct {
client mistapi.ClientInterface
}
type mistProviderModel struct {
Host types.String `tfsdk:"host"`
Apitoken types.String `tfsdk:"apitoken"`
Username types.String `tfsdk:"username"`
Password types.String `tfsdk:"password"`
ApiTimeout types.Float64 `tfsdk:"api_timeout"`
Proxy types.String `tfsdk:"proxy"`
}
func (p *mistProvider) Schema(ctx context.Context, req provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: "The Mist Provider allows Terraform to manage Juniper Mist Organizations.\n\n" +
"It is mainly focusing on day 0 and day 1 operations (provisionning and delpyment) but will be " +
"completed over time.\n\nUse the navigation tree to the left to read about the available resources " +
"and data sources.\n\nIt is possible to use API Token or Username/Password authentication (without 2FA)" +
", but only one method should be configured.\n\nThis version is supporting the following Mist Clouds:\n" +
"* Global 01 (api.mist.com)\n" +
"* Global 02 (api.gc1.mist.com)\n" +
"* Global 03 (api.ac2.mist.com)\n" +
"* Global 04 (api.gc2.mist.com)\n" +
"* EMEA 01 (api.eu.mist.com)\n" +
"* EMEA 02 (api.gc3.mist.com)\n" +
"* EMEA 03 (api.ac6.mist.com)\n" +
"* APAC 01 (api.ac5.mist.com)",
Attributes: map[string]schema.Attribute{
"host": schema.StringAttribute{
MarkdownDescription: "URL of the Mist Cloud, e.g. `api.mist.com`.",
Optional: true,
},
"apitoken": schema.StringAttribute{
MarkdownDescription: "For API Token authentication, the Mist API Token.",
Optional: true,
Sensitive: true,
},
"username": schema.StringAttribute{
MarkdownDescription: "For username/password authentication, the Mist Account username.",
Optional: true,
},
"password": schema.StringAttribute{
MarkdownDescription: "For username/password authentication, the Mist Account password.",
Optional: true,
Sensitive: true,
},
"api_timeout": schema.Float64Attribute{
MarkdownDescription: fmt.Sprintf("Timeout in seconds for completing API transactions "+
"with the Mist Cloud. Omit for default value of %d seconds. Value of 0 results in "+
"infinite timeout.",
defaultApiTimeout),
Optional: true,
Validators: []validator.Float64{float64validator.AtLeast(0)},
},
"proxy": schema.StringAttribute{
MarkdownDescription: "Requests use the configured proxy to reach the Mist Cloud.\n" +
"The value may be either a complete URL or a `[username:password@]host[:port]`, in which case the `http` scheme is assumed. " +
"The schemes `http`, `https`, and `socks5` are supported.",
Optional: true,
},
},
}
}
func (p *mistProviderModel) fromEnv(_ context.Context, diags *diag.Diagnostics) {
if s, ok := os.LookupEnv(envHost); ok && p.Host.IsNull() {
if !strings.HasPrefix(s, "api.") {
diags.AddError(fmt.Sprintf("error parsing environment variable %q", envHost),
fmt.Sprintf("The configured Mist Host does not match the supported Clouds; got %q", s))
}
p.Host = types.StringValue(s)
}
if s, ok := os.LookupEnv(envApitoken); ok && p.Apitoken.IsNull() {
if len(s) < 1 {
diags.AddError(fmt.Sprintf("error parsing environment variable %q", envApitoken),
fmt.Sprintf("minimum string length 1; got %q", s))
}
p.Apitoken = types.StringValue(s)
}
if s, ok := os.LookupEnv(envUsername); ok && p.Username.IsNull() {
if len(s) < 1 {
diags.AddError(fmt.Sprintf("error parsing environment variable %q", envUsername),
fmt.Sprintf("minimum string length 1; got %q", s))
}
p.Username = types.StringValue(s)
}
if s, ok := os.LookupEnv(envPassword); ok && p.Password.IsNull() {
if len(s) < 1 {
diags.AddError(fmt.Sprintf("error parsing environment variable %q", envPassword),
fmt.Sprintf("minimum string length 1; got %q", s))
}
p.Password = types.StringValue(s)
}
if s, ok := os.LookupEnv(envApiTimeout); ok && p.ApiTimeout.IsNull() {
v, err := strconv.ParseFloat(s, 64)
if err != nil {
diags.AddError(fmt.Sprintf("error parsing environment variable %q", envApiTimeout), err.Error())
}
if v < 0 {
diags.AddError(fmt.Sprintf("invalid value in environment variable %q", envApiTimeout),
fmt.Sprintf("minimum permitted value is 0, got %d", int64(v)))
}
p.ApiTimeout = types.Float64Value(v)
}
if s, ok := os.LookupEnv(envProxy); ok && p.Proxy.IsNull() {
if len(s) < 1 {
diags.AddError(fmt.Sprintf("error parsing environment variable %q", envProxy),
fmt.Sprintf("minimum string length 1; got %q", s))
}
p.Proxy = types.StringValue(s)
}
}
func (p *mistProviderModel) validateConfig(_ context.Context, diags *diag.Diagnostics) {
if p.Host.ValueString() == "" {
diags.AddAttributeError(
path.Root("host"),
"Missing MIST API Host",
"The provider cannot create the MIST API client because there is a missing or empty value for the MIST API host. "+
"Set the host value in the configuration or use the `"+envHost+"` environment variable. "+
"If either is already set, ensure the value is not empty.",
)
}
if p.Apitoken.ValueString() == "" && (p.Username.ValueString() == "" && p.Password.ValueString() == "") {
diags.AddError(
"Missing MIST API Authentication",
"The provider cannot create the MIST API client because the authentication configuration is missing. "+
"Set the Authentication values in the configuration or in the environment variables: "+
" * apitoken (environment variable `"+envApitoken+"`)"+
" * username and password (environment variables`"+envUsername+"` and `"+envPassword+"`)"+
"If either is already set, ensure the value is not empty.",
)
} else if p.Apitoken.ValueString() == "" && (p.Username.ValueString() != "" && p.Password.ValueString() == "") {
diags.AddAttributeError(
path.Root("username"),
"Missing MIST API Password",
"The provider cannot create the MIST API client because there is a a missing or empty value for the MIST Username whereas the MIST Password is configured. "+
"Set the host value in the configuration or use the `"+envUsername+"` environment variable. "+
"If either is already set, ensure the value is not empty.",
)
} else if p.Apitoken.ValueString() == "" && (p.Username.ValueString() == "" && p.Password.ValueString() != "") {
diags.AddAttributeError(
path.Root("password"),
"Missing MIST API Password",
"The provider cannot create the MIST API client because there is a a missing or empty value for the MIST Password whereas the MIST Username is configured. "+
"Set the host value in the configuration or use the `"+envPassword+"` environment variable. "+
"If either is already set, ensure the value is not empty.",
)
}
}
func (p *mistProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
var config mistProviderModel
diags := req.Config.Get(ctx, &config)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
// Retrieve missing config elements from environment
config.fromEnv(ctx, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
config.validateConfig(ctx, &resp.Diagnostics)
if resp.Diagnostics.HasError() {
return
}
if config.ApiTimeout.IsNull() {
config.ApiTimeout = types.Float64Value(defaultApiTimeout)
}
var proxy_url *url.URL
if !config.Proxy.IsNull() {
proxy_string := config.Proxy.ValueString()
if !strings.HasPrefix(proxy_string, "http://") &&
!strings.HasPrefix(proxy_string, "https://") &&
!strings.HasPrefix(proxy_string, "socks5://") {
proxy_string = "http://" + proxy_string
}
u, err := url.Parse(proxy_string)
if err != nil {
resp.Diagnostics.AddError("Unable to parse proxy configuration", err.Error())
return
}
proxy_url = u
}
var mist_cloud mistapi.Environment
switch config.Host.ValueString() {
case "api.mist.com":
mist_cloud = mistapi.MIST_GLOBAL_01
case "api.gc1.mist.com":
mist_cloud = mistapi.MIST_GLOBAL_02
case "api.ac2.mist.com":
mist_cloud = mistapi.MIST_GLOBAL_03
case "api.gc2.mist.com":
mist_cloud = mistapi.MIST_GLOBAL_04
case "api.eu.mist.com":
mist_cloud = mistapi.MIST_EMEA_01
case "api.gc3.mist.com":
mist_cloud = mistapi.MIST_EMEA_02
case "api.ac6.mist.com":
mist_cloud = mistapi.MIST_EMEA_03
case "api.ac5.mist.com":
mist_cloud = mistapi.MIST_APAC_01
case "api.mistsys.com":
mist_cloud = mistapi.AWS_STAGING
default:
resp.Diagnostics.AddAttributeError(
path.Root("host"),
"Wrong Mist Host",
"The configured host \""+config.Host.ValueString()+"\" is not a valid Mist Host. Please refer to the documentation to get the possible values",
)
return
}
var DefaultTransport http.RoundTripper = http.DefaultTransport
if proxy_url != nil {
DefaultTransport = &http.Transport{
Proxy: http.ProxyURL(proxy_url),
}
}
var client_config mistapi.Configuration
var cloud_config mistapi.ConfigurationOptions = mistapi.WithEnvironment(mist_cloud)
var http_config mistapi.ConfigurationOptions = mistapi.WithHttpConfiguration(
mistapi.CreateHttpConfiguration(
mistapi.WithTimeout(config.ApiTimeout.ValueFloat64()),
mistapi.WithTransport(DefaultTransport),
),
)
// configure the client for API Token Auth
if config.Apitoken.ValueString() != "" {
client_config = mistapi.CreateConfiguration(
http_config,
cloud_config,
mistapi.WithApiTokenCredentials(
mistapi.NewApiTokenCredentials("Token "+config.Apitoken.ValueString()),
),
)
// configure the client for Basic Auth + CSRF
} else {
// Initiate the login API Call
tmp_client := mistapi.NewClient(
mistapi.CreateConfiguration(
http_config,
cloud_config,
mistapi.WithBasicAuthCredentials(
mistapi.NewBasicAuthCredentials(config.Username.ValueString(), config.Password.ValueString()),
),
),
)
body := models.Login{}
body.Email = config.Username.ValueString()
body.Password = config.Password.ValueString()
apiResponse, err := tmp_client.AdminsLogin().Login(ctx, &body)
if err != nil {
resp.Diagnostics.AddError("Authentication Error", err.Error())
return
} else if apiResponse.Response.StatusCode != 200 {
resp.Diagnostics.AddError("Authentication Failed", "Incorrect login/password")
return
}
// Process the Response Headers to extract the CSRF Token
csrfTokenSet := false
for hNAme, hVal := range apiResponse.Response.Header {
if hNAme == "Set-Cookie" {
for _, cooky := range hVal {
for _, cVal := range strings.Split(cooky, ";") {
if strings.HasPrefix(cVal, "csrftoken") {
csrfToken_string := strings.Split(cVal, "=")[1]
csrfToken := mistapi.NewCsrfTokenCredentials(string(csrfToken_string))
client_config = mistapi.CreateConfiguration(
http_config,
cloud_config,
mistapi.WithBasicAuthCredentials(
mistapi.NewBasicAuthCredentials(config.Username.ValueString(), config.Password.ValueString()),
),
mistapi.WithCsrfTokenCredentials(csrfToken),
)
csrfTokenSet = true
}
}
}
}
}
// IF CSRF Token not set, raise an error and exit
if !csrfTokenSet {
resp.Diagnostics.AddError("Authentication Error", "Unable to extract the CSRF Token from the Authentication response")
return
}
}
// Use the configuration to create the client and test the credentials
var client mistapi.ClientInterface = mistapi.NewClient(client_config)
_, err := client.SelfAccount().GetSelf(ctx)
if err != nil {
resp.Diagnostics.AddError("Authentication Error", err.Error())
return
}
resp.DataSourceData = client
resp.ResourceData = client
}
func (p *mistProvider) Metadata(ctx context.Context, req provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "mist"
resp.Version = p.version
}
func (p *mistProvider) DataSources(ctx context.Context) []func() datasource.DataSource {
return []func() datasource.DataSource{
NewConstAppCategoriesDataSource,
NewConstApplicationsDataSource,
NewConstAppSubCategoriesDataSource,
NewConstCountriesDataSource,
NewConstTrafficTypesDataSource,
NewDeviceApStatsDataSource,
NewDeviceSwitchStatsDataSource,
NewDeviceGatewayStatsDataSource,
NewOrgGatewaytemplatesDataSource,
NewOrgInventoryDataSource,
NewOrgNacrulesDataSource,
NewOrgNactagsDataSource,
NewOrgNetworksDataSource,
NewOrgNetworktemplatesDataSource,
NewOrgRftemplatesDataSource,
NewOrgServicesDataSource,
NewOrgSitegroupsDataSource,
NewOrgVpnsDataSource,
NewOrgWlantemplatesDataSource,
NewOrgWxtagsDataSource,
NewSitesDataSource,
NewOrgDeviceprofilesApDataSource,
NewOrgDeviceprofilesGatewayDataSource,
NewOrgServicepoliciesDataSource,
NewOrgIdpprofilesDataSource,
}
}
func (p *mistProvider) Resources(ctx context.Context) []func() resource.Resource {
return []func() resource.Resource{
NewOrgResource,
NewOrgSiteGroupResource,
NewOrgNetworkTemplate,
NewOrgServiceResource,
NewOrgNetworkResource,
NewOrgGatewayTemplate,
NewOrgInventory,
NewOrgNacTag,
NewOrgNacRule,
NewOrgRfTemplate,
NewOrgVpn,
NewOrgWlanTemplate,
NewOrgWlan,
NewOrgWxTag,
NewOrgWxRule,
NewSiteResource,
NewSiteSettingResource,
NewSiteNetworkTemplate,
NewSiteWlan,
NewSiteWxRule,
NewSiteWxTag,
NewDeviceApResource,
NewDeviceSwitchResource,
NewDeviceGatewayResource,
NewDeviceGatewayClusterResource,
NewOrgDeviceprofileAp,
NewOrgDeviceprofileAssign,
NewOrgDeviceprofileGateway,
NewOrgSettingResource,
NewOrgServicepolicyResource,
NewOrgIdpprofileResource,
}
}