-
Notifications
You must be signed in to change notification settings - Fork 418
/
provider.go
789 lines (742 loc) · 41.9 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
package provider
import (
"errors"
"fmt"
"net"
"net/url"
"os"
"strings"
"time"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/datasources"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/internal/provider/docs"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/resources"
"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/sdk"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/snowflakedb/gosnowflake"
)
func init() {
// useful links:
// - https://github.com/hashicorp/terraform-plugin-docs/issues/10#issuecomment-767682837
// - https://github.com/hashicorp/terraform-plugin-docs/issues/156#issuecomment-1600427216
schema.ResourceDescriptionBuilder = func(r *schema.Resource) string {
desc := r.Description
if r.DeprecationMessage != "" {
deprecationMessage := r.DeprecationMessage
replacement, path, ok := docs.GetDeprecatedResourceReplacement(deprecationMessage)
if ok {
deprecationMessage = strings.ReplaceAll(deprecationMessage, replacement, docs.RelativeLink(replacement, path))
}
// <deprecation> tag is a hack to split description into two parts (deprecation/real description) nicely. This tag won't be rendered.
// Check resources.md.tmpl for usage example.
desc = fmt.Sprintf("~> **Deprecation** %v <deprecation>\n\n%s", deprecationMessage, r.Description)
}
return strings.TrimSpace(desc)
}
}
// Provider returns a Terraform Provider using configuration from https://pkg.go.dev/github.com/snowflakedb/gosnowflake#Config
func Provider() *schema.Provider {
return &schema.Provider{
Schema: map[string]*schema.Schema{
"account": {
Type: schema.TypeString,
Description: "Specifies your Snowflake account identifier assigned, by Snowflake. For information about account identifiers, see the [Snowflake documentation](https://docs.snowflake.com/en/user-guide/admin-account-identifier.html). Can also be sourced from the `SNOWFLAKE_ACCOUNT` environment variable. Required unless using `profile`.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_ACCOUNT", nil),
},
"user": {
Type: schema.TypeString,
Description: "Username. Can also be sourced from the `SNOWFLAKE_USER` environment variable. Required unless using `profile`.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_USER", nil),
},
"username": {
Type: schema.TypeString,
Description: "Username for username+password authentication. Can also be sourced from the `SNOWFLAKE_USERNAME` environment variable. Required unless using `profile`.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_USERNAME", nil),
Deprecated: "Use `user` instead of `username`",
},
"password": {
Type: schema.TypeString,
Description: "Password for username+password auth. Cannot be used with `browser_auth` or `private_key_path`. Can also be sourced from the `SNOWFLAKE_PASSWORD` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PASSWORD", nil),
ConflictsWith: []string{"browser_auth", "private_key_path", "private_key", "private_key_passphrase", "oauth_access_token", "oauth_refresh_token"},
},
// todo: add database and schema once unqualified identifiers are supported
"warehouse": {
Type: schema.TypeString,
Description: "Specifies the virtual warehouse to use by default for queries, loading, etc. in the client session. Can also be sourced from the `SNOWFLAKE_WAREHOUSE` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_WAREHOUSE", nil),
},
"role": {
Type: schema.TypeString,
Description: "Specifies the role to use by default for accessing Snowflake objects in the client session. Can also be sourced from the `SNOWFLAKE_ROLE` environment variable. .",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_ROLE", nil),
},
"validate_default_parameters": {
Type: schema.TypeBool,
Description: "True by default. If false, disables the validation checks for Database, Schema, Warehouse and Role at the time a connection is established. Can also be sourced from the `SNOWFLAKE_VALIDATE_DEFAULT_PARAMETERS` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_VALIDATE_DEFAULT_PARAMETERS", nil),
},
"params": {
Type: schema.TypeMap,
Description: "Sets other connection (i.e. session) parameters. [Parameters](https://docs.snowflake.com/en/sql-reference/parameters)",
Optional: true,
},
"client_ip": {
Type: schema.TypeString,
Description: "IP address for network checks. Can also be sourced from the `SNOWFLAKE_CLIENT_IP` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_CLIENT_IP", nil),
},
"protocol": {
Type: schema.TypeString,
Description: "Either http or https, defaults to https. Can also be sourced from the `SNOWFLAKE_PROTOCOL` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PROTOCOL", nil),
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
switch val.(string) {
case "http", "https":
return nil, nil
default:
errs := append(errs, fmt.Errorf("%q must be one of http or https", key))
return warns, errs
}
},
},
"host": {
Type: schema.TypeString,
Description: "Supports passing in a custom host value to the snowflake go driver for use with privatelink. Can also be sourced from the `SNOWFLAKE_HOST` environment variable. ",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_HOST", nil),
},
"port": {
Type: schema.TypeInt,
Description: "Support custom port values to snowflake go driver for use with privatelink. Can also be sourced from the `SNOWFLAKE_PORT` environment variable. ",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PORT", nil),
},
"authenticator": {
Type: schema.TypeString,
Description: "Specifies the [authentication type](https://pkg.go.dev/github.com/snowflakedb/gosnowflake#AuthType) to use when connecting to Snowflake. Valid values include: Snowflake, OAuth, ExternalBrowser, Okta, JWT, TokenAccessor, UsernamePasswordMFA. Can also be sourced from the `SNOWFLAKE_AUTHENTICATOR` environment variable. It has to be set explicitly to JWT for private key authentication.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_AUTHENTICATOR", nil),
ValidateFunc: func(val interface{}, key string) (warns []string, errs []error) {
switch val.(string) {
case "Snowflake", "OAuth", "ExternalBrowser", "Okta", "JWT", "TokenAccessor", "UsernamePasswordMFA":
return nil, nil
default:
errs := append(errs, fmt.Errorf("%q must be one of Snowflake, OAuth, ExternalBrowser, Okta, JWT, TokenAccessor or UsernamePasswordMFA", key))
return warns, errs
}
},
},
"passcode": {
Type: schema.TypeString,
Description: "Specifies the passcode provided by Duo when using multi-factor authentication (MFA) for login. Can also be sourced from the `SNOWFLAKE_PASSCODE` environment variable. ",
Optional: true,
ConflictsWith: []string{"passcode_in_password"},
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PASSCODE", nil),
},
"passcode_in_password": {
Type: schema.TypeBool,
Description: "False by default. Set to true if the MFA passcode is embedded in the login password. Appends the MFA passcode to the end of the password. Can also be sourced from the `SNOWFLAKE_PASSCODE_IN_PASSWORD` environment variable. ",
Optional: true,
ConflictsWith: []string{"passcode"},
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PASSCODE_IN_PASSWORD", nil),
},
"okta_url": {
Type: schema.TypeString,
Description: "The URL of the Okta server. e.g. https://example.okta.com. Can also be sourced from the `SNOWFLAKE_OKTA_URL` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_OKTA_URL", nil),
},
"login_timeout": {
Type: schema.TypeInt,
Description: "Login retry timeout EXCLUDING network roundtrip and read out http response. Can also be sourced from the `SNOWFLAKE_LOGIN_TIMEOUT` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_LOGIN_TIMEOUT", nil),
},
"request_timeout": {
Type: schema.TypeInt,
Description: "request retry timeout EXCLUDING network roundtrip and read out http response. Can also be sourced from the `SNOWFLAKE_REQUEST_TIMEOUT` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_REQUEST_TIMEOUT", nil),
},
"jwt_expire_timeout": {
Type: schema.TypeInt,
Description: "JWT expire after timeout in seconds. Can also be sourced from the `SNOWFLAKE_JWT_EXPIRE_TIMEOUT` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_JWT_EXPIRE_TIMEOUT", nil),
},
"client_timeout": {
Type: schema.TypeInt,
Description: "The timeout in seconds for the client to complete the authentication. Default is 900 seconds. Can also be sourced from the `SNOWFLAKE_CLIENT_TIMEOUT` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_CLIENT_TIMEOUT", nil),
},
"jwt_client_timeout": {
Type: schema.TypeInt,
Description: "The timeout in seconds for the JWT client to complete the authentication. Default is 10 seconds. Can also be sourced from the `SNOWFLAKE_JWT_CLIENT_TIMEOUT` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_JWT_CLIENT_TIMEOUT", nil),
},
"external_browser_timeout": {
Type: schema.TypeInt,
Description: "The timeout in seconds for the external browser to complete the authentication. Default is 120 seconds. Can also be sourced from the `SNOWFLAKE_EXTERNAL_BROWSER_TIMEOUT` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_EXTERNAL_BROWSER_TIMEOUT", nil),
},
"insecure_mode": {
Type: schema.TypeBool,
Description: "If true, bypass the Online Certificate Status Protocol (OCSP) certificate revocation check. IMPORTANT: Change the default value for testing or emergency situations only. Can also be sourced from the `SNOWFLAKE_INSECURE_MODE` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_INSECURE_MODE", nil),
},
"ocsp_fail_open": {
Type: schema.TypeBool,
Description: "True represents OCSP fail open mode. False represents OCSP fail closed mode. Fail open true by default. Can also be sourced from the `SNOWFLAKE_OCSP_FAIL_OPEN` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_OCSP_FAIL_OPEN", nil),
},
"token": {
Type: schema.TypeString,
Description: "Token to use for OAuth and other forms of token based auth. Can also be sourced from the `SNOWFLAKE_TOKEN` environment variable.",
Sensitive: true,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_TOKEN", nil),
},
"token_accessor": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"token_endpoint": {
Type: schema.TypeString,
Description: "The token endpoint for the OAuth provider e.g. https://{yourDomain}/oauth/token when using a refresh token to renew access token. Can also be sourced from the `SNOWFLAKE_TOKEN_ACCESSOR_TOKEN_ENDPOINT` environment variable.",
Required: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_TOKEN_ACCESSOR_TOKEN_ENDPOINT", nil),
},
"refresh_token": {
Type: schema.TypeString,
Description: "The refresh token for the OAuth provider when using a refresh token to renew access token. Can also be sourced from the `SNOWFLAKE_TOKEN_ACCESSOR_REFRESH_TOKEN` environment variable.",
Required: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_TOKEN_ACCESSOR_REFRESH_TOKEN", nil),
},
"client_id": {
Type: schema.TypeString,
Description: "The client ID for the OAuth provider when using a refresh token to renew access token. Can also be sourced from the `SNOWFLAKE_TOKEN_ACCESSOR_CLIENT_ID` environment variable.",
Required: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_TOKEN_ACCESSOR_CLIENT_ID", nil),
},
"client_secret": {
Type: schema.TypeString,
Description: "The client secret for the OAuth provider when using a refresh token to renew access token. Can also be sourced from the `SNOWFLAKE_TOKEN_ACCESSOR_CLIENT_SECRET` environment variable.",
Required: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_TOKEN_ACCESSOR_CLIENT_SECRET", nil),
},
"redirect_uri": {
Type: schema.TypeString,
Description: "The redirect URI for the OAuth provider when using a refresh token to renew access token. Can also be sourced from the `SNOWFLAKE_TOKEN_ACCESSOR_REDIRECT_URI` environment variable.",
Required: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_TOKEN_ACCESSOR_REDIRECT_URI", nil),
},
},
},
},
"keep_session_alive": {
Type: schema.TypeBool,
Description: "Enables the session to persist even after the connection is closed. Can also be sourced from the `SNOWFLAKE_KEEP_SESSION_ALIVE` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_KEEP_SESSION_ALIVE", nil),
},
"private_key": {
Type: schema.TypeString,
Description: "Private Key for username+private-key auth. Cannot be used with `browser_auth` or `password`. Can also be sourced from `SNOWFLAKE_PRIVATE_KEY` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PRIVATE_KEY", nil),
ConflictsWith: []string{"browser_auth", "password", "oauth_access_token", "private_key_path", "oauth_refresh_token"},
},
"private_key_passphrase": {
Type: schema.TypeString,
Description: "Supports the encryption ciphers aes-128-cbc, aes-128-gcm, aes-192-cbc, aes-192-gcm, aes-256-cbc, aes-256-gcm, and des-ede3-cbc. Can also be sourced from `SNOWFLAKE_PRIVATE_KEY_PASSPHRASE` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PRIVATE_KEY_PASSPHRASE", nil),
ConflictsWith: []string{"browser_auth", "password", "oauth_access_token", "oauth_refresh_token"},
},
"disable_telemetry": {
Type: schema.TypeBool,
Description: "Indicates whether to disable telemetry. Can also be sourced from the `SNOWFLAKE_DISABLE_TELEMETRY` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_DISABLE_TELEMETRY", nil),
},
"client_request_mfa_token": {
Type: schema.TypeBool,
Description: "When true the MFA token is cached in the credential manager. True by default in Windows/OSX. False for Linux. Can also be sourced from the `SNOWFLAKE_CLIENT_REQUEST_MFA_TOKEN` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_CLIENT_REQUEST_MFA_TOKEN", nil),
},
"client_store_temporary_credential": {
Type: schema.TypeBool,
Description: "When true the ID token is cached in the credential manager. True by default in Windows/OSX. False for Linux. Can also be sourced from the `SNOWFLAKE_CLIENT_STORE_TEMPORARY_CREDENTIAL` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_CLIENT_STORE_TEMPORARY_CREDENTIAL", nil),
},
"disable_query_context_cache": {
Type: schema.TypeBool,
Description: "Should HTAP query context cache be disabled. Can also be sourced from the `SNOWFLAKE_DISABLE_QUERY_CONTEXT_CACHE` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_DISABLE_QUERY_CONTEXT_CACHE", nil),
},
/*
Feature not yet released as of latest gosnowflake release
https://github.com/snowflakedb/gosnowflake/blob/master/dsn.go#L103
"include_retry_reason": {
Type: schema.TypeBool,
Description: "Should retried request contain retry reason. Can also be sourced from the `SNOWFLAKE_INCLUDE_RETRY_REASON` environment variable.",
Optional: true,
},
*/
"profile": {
Type: schema.TypeString,
Description: "Sets the profile to read from ~/.snowflake/config file. Can also be sourced from the `SNOWFLAKE_PROFILE` environment variable.",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PROFILE", "default"),
},
// Deprecated attributes
"region": {
Type: schema.TypeString,
Description: "Snowflake region, such as \"eu-central-1\", with this parameter. However, since this parameter is deprecated, it is best to specify the region as part of the account parameter. For details, see the description of the account parameter. [Snowflake region](https://docs.snowflake.com/en/user-guide/intro-regions.html) to use. Required if using the [legacy format for the `account` identifier](https://docs.snowflake.com/en/user-guide/admin-account-identifier.html#format-2-legacy-account-locator-in-a-region) in the form of `<cloud_region_id>.<cloud>`. Can also be sourced from the `SNOWFLAKE_REGION` environment variable. ",
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_REGION", nil),
Deprecated: "Specify the region as part of the account parameter",
},
"session_params": {
Type: schema.TypeMap,
Description: "Sets session parameters. [Parameters](https://docs.snowflake.com/en/sql-reference/parameters)",
Optional: true,
Deprecated: "Use `params` instead",
},
"oauth_access_token": {
Type: schema.TypeString,
Description: "Token for use with OAuth. Generating the token is left to other tools. Cannot be used with `browser_auth`, `private_key_path`, `oauth_refresh_token` or `password`. Can also be sourced from `SNOWFLAKE_OAUTH_ACCESS_TOKEN` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_OAUTH_ACCESS_TOKEN", nil),
ConflictsWith: []string{"browser_auth", "private_key_path", "private_key", "private_key_passphrase", "password", "oauth_refresh_token"},
Deprecated: "Use `token` instead",
},
"oauth_refresh_token": {
Type: schema.TypeString,
Description: "Token for use with OAuth. Setup and generation of the token is left to other tools. Should be used in conjunction with `oauth_client_id`, `oauth_client_secret`, `oauth_endpoint`, `oauth_redirect_url`. Cannot be used with `browser_auth`, `private_key_path`, `oauth_access_token` or `password`. Can also be sourced from `SNOWFLAKE_OAUTH_REFRESH_TOKEN` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_OAUTH_REFRESH_TOKEN", nil),
ConflictsWith: []string{"browser_auth", "private_key_path", "private_key", "private_key_passphrase", "password", "oauth_access_token"},
RequiredWith: []string{"oauth_client_id", "oauth_client_secret", "oauth_endpoint", "oauth_redirect_url"},
Deprecated: "Use `token_accessor.0.refresh_token` instead",
},
"oauth_client_id": {
Type: schema.TypeString,
Description: "Required when `oauth_refresh_token` is used. Can also be sourced from `SNOWFLAKE_OAUTH_CLIENT_ID` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_OAUTH_CLIENT_ID", nil),
ConflictsWith: []string{"browser_auth", "private_key_path", "private_key", "private_key_passphrase", "password", "oauth_access_token"},
RequiredWith: []string{"oauth_refresh_token", "oauth_client_secret", "oauth_endpoint", "oauth_redirect_url"},
Deprecated: "Use `token_accessor.0.client_id` instead",
},
"oauth_client_secret": {
Type: schema.TypeString,
Description: "Required when `oauth_refresh_token` is used. Can also be sourced from `SNOWFLAKE_OAUTH_CLIENT_SECRET` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_OAUTH_CLIENT_SECRET", nil),
ConflictsWith: []string{"browser_auth", "private_key_path", "private_key", "private_key_passphrase", "password", "oauth_access_token"},
RequiredWith: []string{"oauth_client_id", "oauth_refresh_token", "oauth_endpoint", "oauth_redirect_url"},
Deprecated: "Use `token_accessor.0.client_secret` instead",
},
"oauth_endpoint": {
Type: schema.TypeString,
Description: "Required when `oauth_refresh_token` is used. Can also be sourced from `SNOWFLAKE_OAUTH_ENDPOINT` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_OAUTH_ENDPOINT", nil),
ConflictsWith: []string{"browser_auth", "private_key_path", "private_key", "private_key_passphrase", "password", "oauth_access_token"},
RequiredWith: []string{"oauth_client_id", "oauth_client_secret", "oauth_refresh_token", "oauth_redirect_url"},
Deprecated: "Use `token_accessor.0.token_endpoint` instead",
},
"oauth_redirect_url": {
Type: schema.TypeString,
Description: "Required when `oauth_refresh_token` is used. Can also be sourced from `SNOWFLAKE_OAUTH_REDIRECT_URL` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_OAUTH_REDIRECT_URL", nil),
ConflictsWith: []string{"browser_auth", "private_key_path", "private_key", "private_key_passphrase", "password", "oauth_access_token"},
RequiredWith: []string{"oauth_client_id", "oauth_client_secret", "oauth_endpoint", "oauth_refresh_token"},
Deprecated: "Use `token_accessor.0.redirect_uri` instead",
},
"browser_auth": {
Type: schema.TypeBool,
Description: "Required when `oauth_refresh_token` is used. Can also be sourced from `SNOWFLAKE_USE_BROWSER_AUTH` environment variable.",
Optional: true,
Sensitive: false,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_USE_BROWSER_AUTH", nil),
Deprecated: "Use `authenticator` instead",
},
"private_key_path": {
Type: schema.TypeString,
Description: "Path to a private key for using keypair authentication. Cannot be used with `browser_auth`, `oauth_access_token` or `password`. Can also be sourced from `SNOWFLAKE_PRIVATE_KEY_PATH` environment variable.",
Optional: true,
Sensitive: true,
DefaultFunc: schema.EnvDefaultFunc("SNOWFLAKE_PRIVATE_KEY_PATH", nil),
ConflictsWith: []string{"browser_auth", "password", "oauth_access_token", "private_key"},
Deprecated: "use the [file Function](https://developer.hashicorp.com/terraform/language/functions/file) instead",
},
},
ResourcesMap: getResources(),
DataSourcesMap: getDataSources(),
ConfigureFunc: ConfigureProvider,
ProviderMetaSchema: map[string]*schema.Schema{},
}
}
func getResources() map[string]*schema.Resource {
return map[string]*schema.Resource{
"snowflake_account": resources.Account(),
"snowflake_account_role": resources.AccountRole(),
"snowflake_account_password_policy_attachment": resources.AccountPasswordPolicyAttachment(),
"snowflake_account_parameter": resources.AccountParameter(),
"snowflake_alert": resources.Alert(),
"snowflake_api_authentication_integration_with_authorization_code_grant": resources.ApiAuthenticationIntegrationWithAuthorizationCodeGrant(),
"snowflake_api_authentication_integration_with_client_credentials": resources.ApiAuthenticationIntegrationWithClientCredentials(),
"snowflake_api_authentication_integration_with_jwt_bearer": resources.ApiAuthenticationIntegrationWithJwtBearer(),
"snowflake_api_integration": resources.APIIntegration(),
"snowflake_cortex_search_service": resources.CortexSearchService(),
"snowflake_database_old": resources.DatabaseOld(),
"snowflake_database": resources.Database(),
"snowflake_database_role": resources.DatabaseRole(),
"snowflake_dynamic_table": resources.DynamicTable(),
"snowflake_email_notification_integration": resources.EmailNotificationIntegration(),
"snowflake_external_function": resources.ExternalFunction(),
"snowflake_external_oauth_integration": resources.ExternalOauthIntegration(),
"snowflake_external_table": resources.ExternalTable(),
"snowflake_failover_group": resources.FailoverGroup(),
"snowflake_file_format": resources.FileFormat(),
"snowflake_function": resources.Function(),
"snowflake_grant_account_role": resources.GrantAccountRole(),
"snowflake_grant_application_role": resources.GrantApplicationRole(),
"snowflake_grant_database_role": resources.GrantDatabaseRole(),
"snowflake_grant_ownership": resources.GrantOwnership(),
"snowflake_grant_privileges_to_account_role": resources.GrantPrivilegesToAccountRole(),
"snowflake_grant_privileges_to_database_role": resources.GrantPrivilegesToDatabaseRole(),
"snowflake_grant_privileges_to_share": resources.GrantPrivilegesToShare(),
"snowflake_legacy_service_user": resources.LegacyServiceUser(),
"snowflake_managed_account": resources.ManagedAccount(),
"snowflake_masking_policy": resources.MaskingPolicy(),
"snowflake_materialized_view": resources.MaterializedView(),
"snowflake_network_policy": resources.NetworkPolicy(),
"snowflake_network_policy_attachment": resources.NetworkPolicyAttachment(),
"snowflake_network_rule": resources.NetworkRule(),
"snowflake_notification_integration": resources.NotificationIntegration(),
"snowflake_oauth_integration": resources.OAuthIntegration(),
"snowflake_oauth_integration_for_partner_applications": resources.OauthIntegrationForPartnerApplications(),
"snowflake_oauth_integration_for_custom_clients": resources.OauthIntegrationForCustomClients(),
"snowflake_object_parameter": resources.ObjectParameter(),
"snowflake_password_policy": resources.PasswordPolicy(),
"snowflake_pipe": resources.Pipe(),
"snowflake_procedure": resources.Procedure(),
"snowflake_resource_monitor": resources.ResourceMonitor(),
"snowflake_role": resources.Role(),
"snowflake_row_access_policy": resources.RowAccessPolicy(),
"snowflake_saml_integration": resources.SAMLIntegration(),
"snowflake_saml2_integration": resources.SAML2Integration(),
"snowflake_schema": resources.Schema(),
"snowflake_scim_integration": resources.SCIMIntegration(),
"snowflake_secondary_database": resources.SecondaryDatabase(),
"snowflake_secret_with_authorization_code_grant": resources.SecretWithAuthorizationCodeGrant(),
"snowflake_secret_with_basic_authentication": resources.SecretWithBasicAuthentication(),
"snowflake_secret_with_client_credentials": resources.SecretWithClientCredentials(),
"snowflake_secret_with_generic_string": resources.SecretWithGenericString(),
"snowflake_sequence": resources.Sequence(),
"snowflake_service_user": resources.ServiceUser(),
"snowflake_session_parameter": resources.SessionParameter(),
"snowflake_share": resources.Share(),
"snowflake_shared_database": resources.SharedDatabase(),
"snowflake_stage": resources.Stage(),
"snowflake_storage_integration": resources.StorageIntegration(),
"snowflake_stream": resources.Stream(),
"snowflake_stream_on_external_table": resources.StreamOnExternalTable(),
"snowflake_stream_on_table": resources.StreamOnTable(),
"snowflake_streamlit": resources.Streamlit(),
"snowflake_table": resources.Table(),
"snowflake_table_column_masking_policy_application": resources.TableColumnMaskingPolicyApplication(),
"snowflake_table_constraint": resources.TableConstraint(),
"snowflake_tag": resources.Tag(),
"snowflake_tag_association": resources.TagAssociation(),
"snowflake_tag_masking_policy_association": resources.TagMaskingPolicyAssociation(),
"snowflake_task": resources.Task(),
"snowflake_unsafe_execute": resources.UnsafeExecute(),
"snowflake_user": resources.User(),
"snowflake_user_password_policy_attachment": resources.UserPasswordPolicyAttachment(),
"snowflake_user_public_keys": resources.UserPublicKeys(),
"snowflake_view": resources.View(),
"snowflake_warehouse": resources.Warehouse(),
}
}
func getDataSources() map[string]*schema.Resource {
return map[string]*schema.Resource{
"snowflake_accounts": datasources.Accounts(),
"snowflake_alerts": datasources.Alerts(),
"snowflake_cortex_search_services": datasources.CortexSearchServices(),
"snowflake_current_account": datasources.CurrentAccount(),
"snowflake_current_role": datasources.CurrentRole(),
"snowflake_database": datasources.Database(),
"snowflake_database_role": datasources.DatabaseRole(),
"snowflake_database_roles": datasources.DatabaseRoles(),
"snowflake_databases": datasources.Databases(),
"snowflake_dynamic_tables": datasources.DynamicTables(),
"snowflake_external_functions": datasources.ExternalFunctions(),
"snowflake_external_tables": datasources.ExternalTables(),
"snowflake_failover_groups": datasources.FailoverGroups(),
"snowflake_file_formats": datasources.FileFormats(),
"snowflake_functions": datasources.Functions(),
"snowflake_grants": datasources.Grants(),
"snowflake_masking_policies": datasources.MaskingPolicies(),
"snowflake_materialized_views": datasources.MaterializedViews(),
"snowflake_network_policies": datasources.NetworkPolicies(),
"snowflake_parameters": datasources.Parameters(),
"snowflake_pipes": datasources.Pipes(),
"snowflake_procedures": datasources.Procedures(),
"snowflake_resource_monitors": datasources.ResourceMonitors(),
"snowflake_role": datasources.Role(),
"snowflake_roles": datasources.Roles(),
"snowflake_row_access_policies": datasources.RowAccessPolicies(),
"snowflake_schemas": datasources.Schemas(),
"snowflake_secrets": datasources.Secrets(),
"snowflake_security_integrations": datasources.SecurityIntegrations(),
"snowflake_sequences": datasources.Sequences(),
"snowflake_shares": datasources.Shares(),
"snowflake_stages": datasources.Stages(),
"snowflake_storage_integrations": datasources.StorageIntegrations(),
"snowflake_streams": datasources.Streams(),
"snowflake_streamlits": datasources.Streamlits(),
"snowflake_system_generate_scim_access_token": datasources.SystemGenerateSCIMAccessToken(),
"snowflake_system_get_aws_sns_iam_policy": datasources.SystemGetAWSSNSIAMPolicy(),
"snowflake_system_get_privatelink_config": datasources.SystemGetPrivateLinkConfig(),
"snowflake_system_get_snowflake_platform_info": datasources.SystemGetSnowflakePlatformInfo(),
"snowflake_tables": datasources.Tables(),
"snowflake_tasks": datasources.Tasks(),
"snowflake_users": datasources.Users(),
"snowflake_views": datasources.Views(),
"snowflake_warehouses": datasources.Warehouses(),
}
}
var (
configuredClient *sdk.Client
configureClientError error //nolint:errname
)
func ConfigureProvider(s *schema.ResourceData) (interface{}, error) {
// hacky way to speed up our acceptance tests
if os.Getenv("TF_ACC") != "" && os.Getenv("SF_TF_ACC_TEST_CONFIGURE_CLIENT_ONCE") == "true" {
if configuredClient != nil {
return &provider.Context{Client: configuredClient}, nil
}
if configureClientError != nil {
return nil, configureClientError
}
}
config := &gosnowflake.Config{
Application: "terraform-provider-snowflake",
}
if v, ok := s.GetOk("account"); ok && v.(string) != "" {
config.Account = v.(string)
}
// backwards compatibility until we can remove this
if v, ok := s.GetOk("username"); ok && v.(string) != "" {
config.User = v.(string)
}
if v, ok := s.GetOk("user"); ok && v.(string) != "" {
config.User = v.(string)
}
if v, ok := s.GetOk("password"); ok && v.(string) != "" {
config.Password = v.(string)
}
if v, ok := s.GetOk("warehouse"); ok && v.(string) != "" {
config.Warehouse = v.(string)
}
if v, ok := s.GetOk("role"); ok && v.(string) != "" {
config.Role = v.(string)
}
if v, ok := s.GetOk("region"); ok && v.(string) != "" {
config.Region = v.(string)
}
if v, ok := s.GetOk("validate_default_parameters"); ok && v.(bool) {
config.ValidateDefaultParameters = gosnowflake.ConfigBoolTrue
}
m := make(map[string]interface{})
if v, ok := s.GetOk("params"); ok {
m = v.(map[string]interface{})
}
// backwards compatibility until we can remove this
if v, ok := s.GetOk("session_params"); ok {
m = v.(map[string]interface{})
}
params := make(map[string]*string)
for key, value := range m {
strValue := value.(string)
params[key] = &strValue
}
config.Params = params
if v, ok := s.GetOk("client_ip"); ok && v.(string) != "" {
config.ClientIP = net.ParseIP(v.(string))
}
if v, ok := s.GetOk("protocol"); ok && v.(string) != "" {
config.Protocol = v.(string)
}
if v, ok := s.GetOk("host"); ok && v.(string) != "" {
config.Host = v.(string)
}
if v, ok := s.GetOk("port"); ok && v.(int) > 0 {
config.Port = v.(int)
}
// backwards compatibility until we can remove this
if v, ok := s.GetOk("browser_auth"); ok && v.(bool) {
config.Authenticator = gosnowflake.AuthTypeExternalBrowser
}
if v, ok := s.GetOk("authenticator"); ok && v.(string) != "" {
config.Authenticator = toAuthenticatorType(v.(string))
}
if v, ok := s.GetOk("passcode"); ok && v.(string) != "" {
config.Passcode = v.(string)
}
if v, ok := s.GetOk("passcode_in_password"); ok && v.(bool) {
config.PasscodeInPassword = v.(bool)
}
if v, ok := s.GetOk("okta_url"); ok && v.(string) != "" {
oktaURL, err := url.Parse(v.(string))
if err != nil {
return nil, fmt.Errorf("could not parse okta_url err = %w", err)
}
config.OktaURL = oktaURL
}
if v, ok := s.GetOk("login_timeout"); ok && v.(int) > 0 {
config.LoginTimeout = time.Second * time.Duration(int64(v.(int)))
}
if v, ok := s.GetOk("request_timeout"); ok && v.(int) > 0 {
config.RequestTimeout = time.Second * time.Duration(int64(v.(int)))
}
if v, ok := s.GetOk("jwt_expire_timeout"); ok && v.(int) > 0 {
config.JWTExpireTimeout = time.Second * time.Duration(int64(v.(int)))
}
if v, ok := s.GetOk("client_timeout"); ok && v.(int) > 0 {
config.ClientTimeout = time.Second * time.Duration(int64(v.(int)))
}
if v, ok := s.GetOk("jwt_client_timeout"); ok && v.(int) > 0 {
config.JWTClientTimeout = time.Second * time.Duration(int64(v.(int)))
}
if v, ok := s.GetOk("external_browser_timeout"); ok && v.(int) > 0 {
config.ExternalBrowserTimeout = time.Second * time.Duration(int64(v.(int)))
}
if v, ok := s.GetOk("insecure_mode"); ok && v.(bool) {
config.InsecureMode = v.(bool)
}
if v, ok := s.GetOk("ocsp_fail_open"); ok && v.(bool) {
config.OCSPFailOpen = gosnowflake.OCSPFailOpenTrue
}
if v, ok := s.GetOk("token"); ok && v.(string) != "" {
config.Token = v.(string)
config.Authenticator = gosnowflake.AuthTypeOAuth
}
if v, ok := s.GetOk("token_accessor"); ok {
if len(v.([]interface{})) > 0 {
tokenAccessor := v.([]interface{})[0].(map[string]interface{})
tokenEndpoint := tokenAccessor["token_endpoint"].(string)
refreshToken := tokenAccessor["refresh_token"].(string)
clientID := tokenAccessor["client_id"].(string)
clientSecret := tokenAccessor["client_secret"].(string)
redirectURI := tokenAccessor["redirect_uri"].(string)
accessToken, err := GetAccessTokenWithRefreshToken(tokenEndpoint, clientID, clientSecret, refreshToken, redirectURI)
if err != nil {
return nil, fmt.Errorf("could not retrieve access token from refresh token, err = %w", err)
}
config.Token = accessToken
config.Authenticator = gosnowflake.AuthTypeOAuth
}
}
if v, ok := s.GetOk("keep_session_alive"); ok && v.(bool) {
config.KeepSessionAlive = v.(bool)
}
privateKeyPath := s.Get("private_key_path").(string)
privateKey := s.Get("private_key").(string)
privateKeyPassphrase := s.Get("private_key_passphrase").(string)
v, err := getPrivateKey(privateKeyPath, privateKey, privateKeyPassphrase)
if err != nil {
return nil, fmt.Errorf("could not retrieve private key: %w", err)
}
if v != nil {
config.PrivateKey = v
}
if v, ok := s.GetOk("disable_telemetry"); ok && v.(bool) {
config.DisableTelemetry = v.(bool)
}
if v, ok := s.GetOk("client_request_mfa_token"); ok && v.(bool) {
config.ClientRequestMfaToken = gosnowflake.ConfigBoolTrue
}
if v, ok := s.GetOk("client_store_temporary_credential"); ok && v.(bool) {
config.ClientStoreTemporaryCredential = gosnowflake.ConfigBoolTrue
}
if v, ok := s.GetOk("disable_query_context_cache"); ok && v.(bool) {
config.DisableQueryContextCache = v.(bool)
}
/*
Feature not yet released as of latest gosnowflake release
https://github.com/snowflakedb/gosnowflake/blob/master/dsn.go#L103
if v, ok := s.GetOk("include_retry_reason"); ok && v.(bool) {
config.IncludeRetryParameters = v.(bool)
}
*/
if v, ok := s.GetOk("profile"); ok && v.(string) != "" {
profile := v.(string)
if profile == "default" {
defaultConfig := sdk.DefaultConfig()
config = sdk.MergeConfig(config, defaultConfig)
} else {
profileConfig, err := sdk.ProfileConfig(profile)
if err != nil {
return "", errors.New("could not retrieve profile config: " + err.Error())
}
if profileConfig == nil {
return "", errors.New("profile with name: " + profile + " not found in config file")
}
// merge any credentials found in profile with config
config = sdk.MergeConfig(config, profileConfig)
}
}
cl, clErr := sdk.NewClient(config)
// needed for tests verifying different provider setups
if os.Getenv("TF_ACC") != "" && os.Getenv("SF_TF_ACC_TEST_CONFIGURE_CLIENT_ONCE") == "true" {
configuredClient = cl
configureClientError = clErr
} else {
configuredClient = nil
configureClientError = nil
}
if clErr != nil {
return nil, clErr
}
return &provider.Context{Client: cl}, nil
}