generated from SAP/repository-template
/
provider.go
451 lines (399 loc) · 16.5 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
package provider
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"strings"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/datasource"
"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/types"
"github.com/SAP/terraform-provider-btp/internal/btpcli"
"github.com/SAP/terraform-provider-btp/internal/version"
)
const userPasswordFlow = "userPasswordFlow"
const x509Flow = "x509Flow"
const idTokenFlow = "idTokenFlow"
const errorMessagePostfixWithEnv = "If either is already set, ensure the value is not empty."
const errorMessagePostfixWithoutEnv = "If it is already set, ensure the value is not empty."
func New() provider.Provider {
return NewWithClient(http.DefaultClient)
}
func NewWithClient(httpClient *http.Client) provider.Provider {
return &btpcliProvider{httpClient: httpClient}
}
type btpcliProvider struct {
httpClient *http.Client
betaFeaturesEnabled bool
}
func (p *btpcliProvider) Schema(_ context.Context, _ provider.SchemaRequest, resp *provider.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: `The Terraform provider for SAP BTP enables you to automate the provisioning, management, and configuration of resources on [SAP Business Technology Platform](https://account.hana.ondemand.com/). By leveraging this provider, you can simplify and streamline the deployment and maintenance of BTP services and applications.`,
Attributes: map[string]schema.Attribute{
"cli_server_url": schema.StringAttribute{
MarkdownDescription: "The URL of the BTP CLI server (e.g. `https://cli.btp.cloud.sap`).",
Optional: true, // TODO validate URL
},
"globalaccount": schema.StringAttribute{
MarkdownDescription: "The subdomain of the global account in which you want to manage resources. To be found in the cockpit, in the global account view.",
Required: true,
Validators: []validator.String{
stringvalidator.LengthAtLeast(1),
},
},
"username": schema.StringAttribute{
MarkdownDescription: "Your user name, usually an e-mail address. This can also be sourced from the `BTP_USERNAME` environment variable.",
Optional: true,
},
"password": schema.StringAttribute{
MarkdownDescription: "Your password. Note that two-factor authentication is not supported. This can also be sourced from the `BTP_PASSWORD` environment variable.",
Optional: true,
Sensitive: true,
},
"idtoken": schema.StringAttribute{
MarkdownDescription: "A valid id token. To be provided instead of 'username' and 'password'. This can also be sourced from the `BTP_IDTOKEN` environment variable. (SAP-internal usage only)",
Optional: true,
Sensitive: true,
Validators: []validator.String{
stringvalidator.ConflictsWith(path.MatchRoot("username"), path.MatchRoot("password"), path.MatchRoot("idp"), path.MatchRoot("tls_idp_url"), path.MatchRoot("tls_client_key"), path.MatchRoot("tls_client_certificate")),
stringvalidator.LengthAtLeast(1),
},
},
"idp": schema.StringAttribute{
MarkdownDescription: "The identity provider to be used for authentication (only required for custom idp).",
Optional: true,
},
"tls_idp_url": schema.StringAttribute{
MarkdownDescription: "The URL of the identity provider to be used for authentication (only required for x509 auth).",
Optional: true,
Validators: []validator.String{
stringvalidator.ConflictsWith(path.MatchRoot("password"), path.MatchRoot("idtoken")),
stringvalidator.AlsoRequires(path.MatchRoot("tls_client_key"), path.MatchRoot("tls_client_certificate")),
},
},
"tls_client_key": schema.StringAttribute{
MarkdownDescription: "PEM encoded private key (only required for x509 auth).",
Optional: true,
Validators: []validator.String{
stringvalidator.ConflictsWith(path.MatchRoot("password"), path.MatchRoot("idtoken")),
stringvalidator.AlsoRequires(path.MatchRoot("tls_idp_url"), path.MatchRoot("tls_client_certificate")),
},
},
"tls_client_certificate": schema.StringAttribute{
MarkdownDescription: "PEM encoded certificate (only required for x509 auth).",
Optional: true,
Validators: []validator.String{
stringvalidator.ConflictsWith(path.MatchRoot("password"), path.MatchRoot("idtoken")),
stringvalidator.AlsoRequires(path.MatchRoot("tls_idp_url"), path.MatchRoot("tls_client_key")),
},
},
},
}
}
type providerData struct {
CLIServerURL types.String `tfsdk:"cli_server_url"`
GlobalAccount types.String `tfsdk:"globalaccount"`
Username types.String `tfsdk:"username"`
Password types.String `tfsdk:"password"`
IdToken types.String `tfsdk:"idtoken"`
IdentityProvider types.String `tfsdk:"idp"`
IdentityProviderURL types.String `tfsdk:"tls_idp_url"`
TLSClientKey types.String `tfsdk:"tls_client_key"`
TLSClientCertificate types.String `tfsdk:"tls_client_certificate"`
}
// Metadata returns the provider type name.
func (p *btpcliProvider) Metadata(_ context.Context, _ provider.MetadataRequest, resp *provider.MetadataResponse) {
resp.TypeName = "btp"
}
func (p *btpcliProvider) Configure(ctx context.Context, req provider.ConfigureRequest, resp *provider.ConfigureResponse) {
const unableToCreateClient = "unableToCreateClient"
// Retrieve provider data from configuration
var config providerData
diags := req.Config.Get(ctx, &config)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
selectedCLIServerURL := btpcli.DefaultServerURL
if !config.CLIServerURL.IsNull() {
selectedCLIServerURL = config.CLIServerURL.ValueString()
}
u, err := url.Parse(selectedCLIServerURL) // TODO move to NewV2Client
if err != nil {
resp.Diagnostics.AddError(unableToCreateClient, fmt.Sprintf("%s", err))
return
}
client := btpcli.NewClientFacade(btpcli.NewV2ClientWithHttpClient(p.httpClient, u))
btpUserAgent := os.Getenv("BTP_APPEND_USER_AGENT")
if len(strings.TrimSpace(btpUserAgent)) == 0 {
client.UserAgent = fmt.Sprintf("Terraform/%s terraform-provider-btp/%s", req.TerraformVersion, version.ProviderVersion)
} else {
client.UserAgent = fmt.Sprintf("Terraform/%s terraform-provider-btp/%s custom-user-agent/%s", req.TerraformVersion, version.ProviderVersion, btpUserAgent)
}
// User may provide an idp to the provider
var idp string
if config.IdentityProvider.IsUnknown() {
resp.Diagnostics.AddWarning(unableToCreateClient, "Cannot use unknown value as identity provider")
return
}
if config.IdentityProvider.IsNull() {
idp = os.Getenv("BTP_IDP")
} else {
idp = config.IdentityProvider.ValueString()
}
// User may provide an id token to the provider instead of username and password (see below)
var idToken string
if config.IdToken.IsUnknown() {
resp.Diagnostics.AddWarning(unableToCreateClient, "Cannot use unknown value as id token")
return
}
if config.IdToken.IsNull() {
idToken = os.Getenv("BTP_IDTOKEN")
} else {
idToken = config.IdToken.ValueString()
}
// User must provide a username to the provider unless an id token is given
var username string
if config.Username.IsUnknown() {
resp.Diagnostics.AddWarning(unableToCreateClient, "Cannot use unknown value as username")
return
}
if config.Username.IsNull() {
username = os.Getenv("BTP_USERNAME")
} else {
username = config.Username.ValueString()
}
// User must provide a password to the provider unless an id token is given
var password string
if config.Password.IsUnknown() {
resp.Diagnostics.AddWarning(unableToCreateClient, "Cannot use unknown value as password")
return
}
if config.Password.IsNull() {
password = os.Getenv("BTP_PASSWORD")
} else {
password = config.Password.ValueString()
}
//Determine and execute the login flow depending on the provided parameters
switch authFlow := determineAuthFlow(config, idToken); authFlow {
case userPasswordFlow:
validateUserPasswordFlow(username, password, resp)
if resp.Diagnostics.HasError() {
return
}
if _, err = client.Login(ctx, btpcli.NewLoginRequestWithCustomIDP(idp, config.GlobalAccount.ValueString(), username, password)); err != nil {
resp.Diagnostics.AddError(unableToCreateClient, fmt.Sprintf("%s", err))
}
case x509Flow:
validateX509Flow(username, config.IdentityProviderURL.ValueString(), config.TLSClientKey.ValueString(), config.TLSClientCertificate.ValueString(), resp)
if resp.Diagnostics.HasError() {
return
}
passcodeLoginReq := &btpcli.PasscodeLoginRequest{
GlobalAccountSubdomain: config.GlobalAccount.ValueString(),
IdentityProvider: idp,
IdentityProviderURL: config.IdentityProviderURL.ValueString(),
Username: username,
PEMEncodedPrivateKey: config.TLSClientKey.ValueString(),
PEMEncodedCertificate: config.TLSClientCertificate.ValueString(),
}
if _, err = client.PasscodeLogin(ctx, passcodeLoginReq); err != nil {
resp.Diagnostics.AddError(unableToCreateClient, fmt.Sprintf("%s", err))
return
}
case idTokenFlow:
// SAP Internal usage only
if _, err = client.IdTokenLogin(ctx, btpcli.NewIdTokenLoginRequest(config.GlobalAccount.ValueString(), idToken)); err != nil {
resp.Diagnostics.AddError(unableToCreateClient, fmt.Sprintf("%s", err))
}
default:
// No valid login flow
resp.Diagnostics.AddError(unableToCreateClient, "No valid login flow found. Please provide either username and password, or an id token, or a client certificate and key.")
}
if resp.Diagnostics.HasError() {
return
}
resp.DataSourceData = client
resp.ResourceData = client
}
// Resources - Defines provider resources
func (p *btpcliProvider) Resources(ctx context.Context) []func() resource.Resource {
betaResources := []func() resource.Resource{
//Beta resources should be excluded from sonar scan.
//If you add them to production code, remove them from sonar exclusion list
newDirectoryRoleResource,
newGlobalaccountRoleResource,
newSubaccountRoleResource,
}
if !p.betaFeaturesEnabled {
betaResources = nil
}
return append([]func() resource.Resource{
newDirectoryResource,
newDirectoryEntitlementResource,
newDirectoryRoleCollectionAssignmentResource,
newDirectoryRoleCollectionResource,
newGlobalaccountResourceProviderResource,
newGlobalaccountRoleCollectionAssignmentResource,
newGlobalaccountRoleCollectionResource,
newGlobalaccountSecuritySettingsResource,
newGlobalaccountTrustConfigurationResource,
newSubaccountEntitlementResource,
newSubaccountEnvironmentInstanceResource,
newSubaccountResource,
newSubaccountRoleCollectionAssignmentResource,
newSubaccountRoleCollectionResource,
newSubaccountSecuritySettingsResource,
newSubaccountServiceBindingResource,
newSubaccountServiceInstanceResource,
newSubaccountSubscriptionResource,
newSubaccountTrustConfigurationResource,
}, betaResources...)
}
// DataSources - Defines provider data sources
func (p *btpcliProvider) DataSources(ctx context.Context) []func() datasource.DataSource {
betaDataSources := []func() datasource.DataSource{
//Beta data sources should be excluded from sonar scan.
//If you add them to production code, remove them from sonar exclusion list
newDirectoryAppDataSource,
newDirectoryAppsDataSource,
newGlobalaccountAppDataSource,
newGlobalaccountAppsDataSource,
newGlobalaccountResourceProviderDataSource,
newGlobalaccountResourceProvidersDataSource,
newSubaccountServiceBrokerDataSource,
newSubaccountServiceBrokersDataSource,
newSubaccountServicePlatformDataSource,
newSubaccountServicePlatformsDataSource,
}
if !p.betaFeaturesEnabled {
betaDataSources = nil
}
return append([]func() datasource.DataSource{
newDirectoryDataSource,
newDirectoriesDataSource,
newDirectoryEntitlementsDataSource,
newDirectoryLabelsDataSource,
newDirectoryRoleCollectionDataSource,
newDirectoryRoleCollectionsDataSource,
newDirectoryRoleDataSource,
newDirectoryRolesDataSource,
newDirectoryUserDataSource,
newDirectoryUsersDataSource,
newGlobalaccountDataSource,
newGlobalaccountWithHierarchyDataSource,
newGlobalaccountEntitlementsDataSource,
newGlobalaccountRoleCollectionDataSource,
newGlobalaccountRoleCollectionsDataSource,
newGlobalaccountRoleDataSource,
newGlobalaccountRolesDataSource,
newGlobalaccountSecuritySettingsDataSource,
newGlobalaccountTrustConfigurationDataSource,
newGlobalaccountTrustConfigurationsDataSource,
newGlobalaccountUserDataSource,
newGlobalaccountUsersDataSource,
newRegionsDataSource,
newSubaccountAppDataSource,
newSubaccountAppsDataSource,
newSubaccountDataSource,
newSubaccountEntitlementsDataSource,
newSubaccountEnvironmentInstanceDataSource,
newSubaccountEnvironmentInstancesDataSource,
newSubaccountEnvironmentsDataSource,
newSubaccountLabelsDataSource,
newSubaccountRoleCollectionDataSource,
newSubaccountRoleCollectionsDataSource,
newSubaccountRoleDataSource,
newSubaccountRolesDataSource,
newSubaccountSecuritySettingsDataSource,
newSubaccountServiceBindingDataSource,
newSubaccountServiceBindingsDataSource,
newSubaccountServiceInstanceDataSource,
newSubaccountServiceInstancesDataSource,
newSubaccountServiceOfferingDataSource,
newSubaccountServiceOfferingsDataSource,
newSubaccountServicePlanDataSource,
newSubaccountServicePlansDataSource,
newSubaccountSubscriptionDataSource,
newSubaccountSubscriptionsDataSource,
newSubaccountTrustConfigurationDataSource,
newSubaccountTrustConfigurationsDataSource,
newSubaccountUserDataSource,
newSubaccountUsersDataSource,
newSubaccountsDataSource,
newWhoamiDataSource,
}, betaDataSources...)
}
func determineAuthFlow(config providerData, idToken string) string {
if len(idToken) > 0 {
return idTokenFlow
} else if !config.TLSClientKey.IsNull() {
return x509Flow
} else {
return userPasswordFlow
}
}
func validateUserPasswordFlow(userName string, password string, resp *provider.ConfigureResponse) {
if len(userName) == 0 {
resp.Diagnostics.AddAttributeError(
path.Root("username"),
"Missing Username",
"The provider cannot create the Terraform BTP client as there is a missing or empty value for the username. "+
"Set the username value in the configuration or use the BTP_USERNAME environment variable. "+
errorMessagePostfixWithEnv,
)
}
if len(password) == 0 {
resp.Diagnostics.AddAttributeError(
path.Root("password"),
"Missing Password",
"The provider cannot create the Terraform BTP client as there is a missing or empty value for the password. "+
"Set the password value in the configuration or use the BTP_PASSWORD environment variable. "+
errorMessagePostfixWithEnv,
)
}
}
func validateX509Flow(userName string, identityProviderUrl string, tlsClientKey string, tlsClientCertificate string, resp *provider.ConfigureResponse) {
if len(userName) == 0 {
resp.Diagnostics.AddAttributeError(
path.Root("username"),
"Missing Username",
"The provider cannot create the Terraform BTP client as there is a missing or empty value for the username. "+
"Set the username value in the configuration or use the BTP_USERNAME environment variable. "+
errorMessagePostfixWithEnv,
)
}
if len(identityProviderUrl) == 0 {
resp.Diagnostics.AddAttributeError(
path.Root("tls_idp_url"),
"Missing TLS IDP URL (only required for x509 auth)",
"The provider cannot create the Terraform BTP client as there is a missing or empty value for the tls_idp_url (only required for x509 auth). "+
"Set the tls_idp_url value in the configuration. "+
errorMessagePostfixWithoutEnv,
)
}
if len(tlsClientKey) == 0 {
resp.Diagnostics.AddAttributeError(
path.Root("tls_client_key"),
"Missing PEM Encoded Private Key",
"The provider cannot create the Terraform BTP client as there is a missing or empty value for the tls_client_key (PEM encoded private key). "+
"Set the tls_client_key value in the configuration. "+
errorMessagePostfixWithoutEnv,
)
}
if len(tlsClientCertificate) == 0 {
resp.Diagnostics.AddAttributeError(
path.Root("tls_client_certificate"),
"Missing PEM Encoded Certificate",
"The provider cannot create the Terraform BTP client as there is a missing or empty value for the tls_client_certificate (PEM encoded certificate). "+
"Set the tls_client_certificate value in the configuration. "+
errorMessagePostfixWithoutEnv,
)
}
}