-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathresource_vault_cluster.go
More file actions
1861 lines (1670 loc) · 70.1 KB
/
resource_vault_cluster.go
File metadata and controls
1861 lines (1670 loc) · 70.1 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
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package providersdkv2
import (
"context"
"fmt"
"log"
"strings"
"time"
sharedmodels "github.com/hashicorp/hcp-sdk-go/clients/cloud-shared/v1/models"
vaultmodels "github.com/hashicorp/hcp-sdk-go/clients/cloud-vault-service/stable/2020-11-25/models"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-hcp/internal/clients"
"github.com/hashicorp/terraform-provider-hcp/internal/input"
)
// defaultClusterTimeout is the amount of time that can elapse
// before a cluster read operation should timeout.
var defaultVaultClusterTimeout = time.Minute * 5
// createUpdateVaultClusterTimeout is the amount of time that can elapse
// before a cluster create operation should timeout.
var createUpdateVaultClusterTimeout = time.Minute * 75
// deleteVaultClusterTimeout is the amount of time that can elapse
// before a cluster delete operation should timeout.
var deleteVaultClusterTimeout = time.Minute * 75
func resourceVaultCluster() *schema.Resource {
return &schema.Resource{
Description: "The Vault cluster resource allows you to manage an HCP Vault cluster.",
CreateContext: resourceVaultClusterCreate,
ReadContext: resourceVaultClusterRead,
UpdateContext: resourceVaultClusterUpdate,
DeleteContext: resourceVaultClusterDelete,
Timeouts: &schema.ResourceTimeout{
Create: &createUpdateVaultClusterTimeout,
Update: &createUpdateVaultClusterTimeout,
Delete: &deleteVaultClusterTimeout,
Default: &defaultVaultClusterTimeout,
},
Importer: &schema.ResourceImporter{
StateContext: resourceVaultClusterImport,
},
Schema: map[string]*schema.Schema{
// Required inputs
"cluster_id": {
Description: "The ID of the HCP Vault cluster.",
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: validateSlugID,
},
"hvn_id": {
Description: "The ID of the HVN this HCP Vault cluster is associated to.",
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: validateSlugID,
},
// Optional fields
"project_id": {
Description: `
The ID of the HCP project where the Vault cluster is located.
If not specified, the project specified in the HCP Provider config block will be used, if configured.
If a project is not configured in the HCP Provider config block, the oldest project in the organization will be used.`,
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validation.IsUUID,
Computed: true,
},
"tier": {
Description: "Tier of the HCP Vault cluster. Valid options for tiers - `dev`, `standard_small`, `standard_medium`, `standard_large`, `plus_small`, `plus_medium`, `plus_large`. See [pricing information](https://www.hashicorp.com/products/vault/pricing). Changing a cluster's size or tier is only available to admins. See [Scale a cluster](https://registry.terraform.io/providers/hashicorp/hcp/latest/docs/guides/vault-scaling).",
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateDiagFunc: validateVaultClusterTier,
DiffSuppressFunc: func(_, old, new string, _ *schema.ResourceData) bool {
return strings.EqualFold(old, new)
},
},
"public_endpoint": {
Description: "Denotes that the cluster has a public endpoint. Defaults to false.",
Type: schema.TypeBool,
Default: false,
Optional: true,
},
"proxy_endpoint": {
Description: "Denotes that the cluster has a proxy endpoint. Valid options are `ENABLED`, `DISABLED`. Defaults to `DISABLED`.",
Type: schema.TypeString,
Default: "DISABLED",
Optional: true,
ValidateDiagFunc: validateVaultClusterProxyEndpoint,
DiffSuppressFunc: func(_, old, new string, _ *schema.ResourceData) bool {
return strings.EqualFold(old, new)
},
},
"ip_allowlist": {
Description: "Allowed IPV4 address ranges (CIDRs) for inbound traffic. Each entry must be a unique CIDR. Maximum 50 CIDRS supported at this time.",
Type: schema.TypeList,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"address": {
Description: "IP address range in CIDR notation.",
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: validateCIDRRange,
},
"description": {
Description: "Description to help identify source (maximum 255 chars).",
Type: schema.TypeString,
Optional: true,
ValidateDiagFunc: validateCIDRRangeDescription,
},
},
},
MaxItems: 50,
},
"min_vault_version": {
Description: "The minimum Vault version to use when creating the cluster. If not specified, it is defaulted to the version that is currently recommended by HCP. For example, `v1.21.2`. Refer to the [HCP Vault changelog](https://developer.hashicorp.com/hcp/docs/changelog) for available versions.",
Type: schema.TypeString,
Optional: true,
ValidateDiagFunc: validateSemVer,
ForceNew: true,
},
// Only applies to Plus tier HCP Vault clusters
"primary_link": {
Description: "The `self_link` of the HCP Vault Plus tier cluster which is the primary in the performance replication setup with this HCP Vault Plus tier cluster. If not specified, it is a standalone Plus tier HCP Vault cluster.",
Type: schema.TypeString,
Optional: true,
ForceNew: true,
},
"paths_filter": {
Description: "The performance replication [paths filter](https://developer.hashicorp.com/vault/tutorials/cloud-ops/vault-replication-terraform). Applies to performance replication secondaries only and operates in \"deny\" mode only.",
Type: schema.TypeList,
MinItems: 1,
Elem: &schema.Schema{
Type: schema.TypeString,
ValidateDiagFunc: validateVaultPathsFilter,
},
Optional: true,
},
"organization_id": {
Description: "The ID of the organization this HCP Vault cluster is located in.",
Type: schema.TypeString,
Computed: true,
},
"cloud_provider": {
Description: "The provider where the HCP Vault cluster is located.",
Type: schema.TypeString,
Computed: true,
},
"region": {
Description: "The region where the HCP Vault cluster is located.",
Type: schema.TypeString,
Computed: true,
},
"namespace": {
Description: "The name of the customer namespace this HCP Vault cluster is located in.",
Type: schema.TypeString,
Computed: true,
},
"metrics_config": {
Description: "The metrics configuration for export. (https://developer.hashicorp.com/vault/tutorials/cloud-monitoring/vault-metrics-guide#metrics-streaming-configuration)",
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"grafana_endpoint": {
Description: "Grafana endpoint for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"grafana_user": {
Description: "Grafana user for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"grafana_password": {
Description: "Grafana password for streaming metrics",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"splunk_hecendpoint": {
Description: "Splunk endpoint for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"splunk_token": {
Description: "Splunk token for streaming metrics",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"datadog_api_key": {
Description: "Datadog api key for streaming metrics",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"datadog_region": {
Description: "Datadog region for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"cloudwatch_access_key_id": {
Description: "CloudWatch access key ID for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"cloudwatch_secret_access_key": {
Description: "CloudWatch secret access key for streaming metrics",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"cloudwatch_region": {
Description: "CloudWatch region for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"cloudwatch_namespace": {
Description: "CloudWatch namespace for streaming metrics",
Type: schema.TypeString,
Computed: true,
},
"elasticsearch_endpoint": {
Description: "ElasticSearch endpoint for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"elasticsearch_dataset": {
Description: "ElasticSearch dataset for streaming metrics",
Type: schema.TypeString,
Computed: true,
},
"elasticsearch_user": {
Description: "ElasticSearch user for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"elasticsearch_password": {
Description: "ElasticSearch password for streaming metrics",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"http_basic_user": {
Description: "HTTP basic authentication username for streaming metrics, one of the two available authentication methods, can be specified only if http_basic_password is also specified",
Type: schema.TypeString,
Optional: true,
},
"http_basic_password": {
Description: "HTTP basic authentication password for streaming metrics, one of the two available authentication methods, can be specified only if http_basic_user is also specified",
Type: schema.TypeString,
Optional: true,
},
"http_bearer_token": {
Description: "HTTP bearer authentication token for streaming metrics, one of the two available authentication methods, can be specified only if http_basic_user and http_basic_password are not provided",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"http_headers": {
Description: "HTTP headers for streaming metrics",
Type: schema.TypeMap,
Optional: true,
},
"http_codec": {
Description: "HTTP codec for streaming metrics, allowed values are JSON and NDJSON",
Type: schema.TypeString,
Optional: true,
},
"http_compression": {
Description: "HTTP compression flag for streaming metrics",
Type: schema.TypeBool,
Optional: true,
},
"http_method": {
Description: "HTTP payload method for streaming metrics, allowed values are PATCH, POST, or PUT",
Type: schema.TypeString,
Optional: true,
},
"http_payload_prefix": {
Description: "HTTP payload prefix for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"http_payload_suffix": {
Description: "HTTP payload suffix for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"http_uri": {
Description: "HTTP URI for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"newrelic_account_id": {
Description: "NewRelic Account ID for streaming metrics",
Type: schema.TypeString,
Optional: true,
},
"newrelic_license_key": {
Description: "NewRelic license key for streaming metrics",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"newrelic_region": {
Description: "NewRelic region for streaming metrics, allowed values are \"US\" and \"EU\"",
Type: schema.TypeString,
Optional: true,
},
},
},
},
"audit_log_config": {
Description: "The audit logs configuration for export. (https://developer.hashicorp.com/vault/tutorials/cloud-monitoring/vault-metrics-guide#metrics-streaming-configuration)",
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"grafana_endpoint": {
Description: "Grafana endpoint for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"grafana_user": {
Description: "Grafana user for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"grafana_password": {
Description: "Grafana password for streaming audit logs",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"splunk_hecendpoint": {
Description: "Splunk endpoint for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"splunk_token": {
Description: "Splunk token for streaming audit logs",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"datadog_api_key": {
Description: "Datadog api key for streaming audit logs",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"datadog_region": {
Description: "Datadog region for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"cloudwatch_access_key_id": {
Description: "CloudWatch access key ID for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"cloudwatch_secret_access_key": {
Description: "CloudWatch secret access key for streaming audit logs",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"cloudwatch_region": {
Description: "CloudWatch region for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"cloudwatch_stream_name": {
Description: "CloudWatch stream name for the target log stream for audit logs",
Type: schema.TypeString,
Computed: true,
},
"cloudwatch_group_name": {
Description: "CloudWatch group name of the target log stream for audit logs",
Type: schema.TypeString,
Computed: true,
},
"elasticsearch_endpoint": {
Description: "ElasticSearch endpoint for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"elasticsearch_dataset": {
Description: "ElasticSearch dataset for streaming audit logs",
Type: schema.TypeString,
Computed: true,
},
"elasticsearch_user": {
Description: "ElasticSearch user for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"elasticsearch_password": {
Description: "ElasticSearch password for streaming audit logs",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"http_basic_password": {
Description: "HTTP basic authentication password for streaming audit logs, one of the two available authentication methods, can be specified only if http_basic_user is also provided",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"http_bearer_token": {
Description: "HTTP bearer authentication token for streaming audit logs, one of the two available authentication methods, can be specified only if http_basic_user and http_basic_password are not provided",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"http_headers": {
Description: "HTTP headers for streaming audit logs",
Type: schema.TypeMap,
Optional: true,
},
"http_codec": {
Description: "HTTP codec for streaming audit logs, allowed values are JSON and NDJSON",
Type: schema.TypeString,
Optional: true,
},
"http_compression": {
Description: "HTTP compression flag for streaming audit logs",
Type: schema.TypeBool,
Optional: true,
},
"http_method": {
Description: "HTTP payload method for streaming audit logs, , allowed values are PATCH, POST, or PUT",
Type: schema.TypeString,
Optional: true,
},
"http_payload_prefix": {
Description: "HTTP payload prefix for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"http_payload_suffix": {
Description: "HTTP payload suffix for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"http_uri": {
Description: "HTTP URI for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"newrelic_account_id": {
Description: "NewRelic Account ID for streaming audit logs",
Type: schema.TypeString,
Optional: true,
},
"newrelic_license_key": {
Description: "NewRelic license key for streaming audit logs",
Type: schema.TypeString,
Optional: true,
Sensitive: true,
},
"newrelic_region": {
Description: "NewRelic region for streaming audit logs, allowed values are \"US\" and \"EU\"",
Type: schema.TypeString,
Optional: true,
},
"http_basic_user": {
Description: "HTTP basic authentication username for streaming audit logs, one of the two available authentication methods, can be specified only if http_basic_password is also provided",
Type: schema.TypeString,
Optional: true,
},
},
},
},
"vault_version": {
Description: "The Vault version of the cluster.",
Type: schema.TypeString,
Computed: true,
},
"major_version_upgrade_config": {
Description: "The Major Version Upgrade configuration.",
Type: schema.TypeList,
MaxItems: 1,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"upgrade_type": {
Description: "The major upgrade type for the cluster. Valid options for upgrade type - `AUTOMATIC`, `SCHEDULED`, `MANUAL`",
Type: schema.TypeString,
Required: true,
ValidateDiagFunc: validateVaultUpgradeType,
DiffSuppressFunc: func(_, old, new string, _ *schema.ResourceData) bool {
return strings.EqualFold(old, new)
},
},
"maintenance_window_day": {
Description: "The maintenance day of the week for scheduled upgrades. Valid options for maintenance window day - `MONDAY`, `TUESDAY`, `WEDNESDAY`, `THURSDAY`, `FRIDAY`, `SATURDAY`, `SUNDAY`",
Type: schema.TypeString,
Optional: true,
ValidateDiagFunc: validateVaultUpgradeWindowDay,
DiffSuppressFunc: func(_, old, new string, _ *schema.ResourceData) bool {
return strings.EqualFold(old, new)
},
},
"maintenance_window_time": {
Description: "The maintenance time frame for scheduled upgrades. Valid options for maintenance window time - `WINDOW_12AM_4AM`, `WINDOW_6AM_10AM`, `WINDOW_12PM_4PM`, `WINDOW_6PM_10PM`",
Type: schema.TypeString,
Optional: true,
ValidateDiagFunc: validateVaultUpgradeWindowTime,
DiffSuppressFunc: func(_, old, new string, _ *schema.ResourceData) bool {
return strings.EqualFold(old, new)
},
},
},
},
},
"vault_public_endpoint_url": {
Description: "The public URL for the Vault cluster. This will be empty if `public_endpoint` is `false`.",
Type: schema.TypeString,
Computed: true,
},
"vault_private_endpoint_url": {
Description: "The private URL for the Vault cluster.",
Type: schema.TypeString,
Computed: true,
},
"vault_proxy_endpoint_url": {
Description: "The proxy URL for the Vault cluster. This will be empty if `proxy_endpoint` is `DISABLED`.",
Type: schema.TypeString,
Computed: true,
},
"created_at": {
Description: "The time that the Vault cluster was created.",
Type: schema.TypeString,
Computed: true,
},
"self_link": {
Description: "A unique URL identifying the Vault cluster.",
Type: schema.TypeString,
Computed: true,
},
"state": {
Description: "The state of the Vault cluster.",
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceVaultClusterCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*clients.Client)
clusterID := d.Get("cluster_id").(string)
hvnID := d.Get("hvn_id").(string)
projectID, err := GetProjectID(d.Get("project_id").(string), client.Config.ProjectID)
if err != nil {
return diag.Errorf("unable to retrieve project ID: %v", err)
}
loc := &sharedmodels.HashicorpCloudLocationLocation{
OrganizationID: client.Config.OrganizationID,
ProjectID: projectID,
}
// Get metrics audit config and MVU config first so we can validate and fail faster.
metricsConfig, diagErr := getObservabilityConfig("metrics_config", d)
if diagErr != nil {
return diagErr
}
auditConfig, diagErr := getObservabilityConfig("audit_log_config", d)
if diagErr != nil {
return diagErr
}
mvuConfig, diagErr := getMajorVersionUpgradeConfig(d)
if diagErr != nil {
return diagErr
}
// Use the hvn to get provider and region.
hvn, err := clients.GetHvnByID(ctx, client, loc, hvnID)
if err != nil {
return diag.Errorf("unable to find existing HVN (%s): %v", hvnID, err)
}
loc.Region = &sharedmodels.HashicorpCloudLocationRegion{
Provider: hvn.Location.Region.Provider,
Region: hvn.Location.Region.Region,
}
locInternal := &vaultmodels.HashicorpCloudInternalLocationLocation{
OrganizationID: loc.OrganizationID,
ProjectID: loc.ProjectID,
Region: &vaultmodels.HashicorpCloudInternalLocationRegion{
Provider: loc.Region.Provider,
Region: loc.Region.Region,
},
}
// Check for an existing Vault cluster.
_, err = clients.GetVaultClusterByID(ctx, client, loc, clusterID)
if err != nil {
if !clients.IsResponseCodeNotFound(err) {
return diag.Errorf("unable to check for presence of an existing Vault cluster (%s): %v", clusterID, err)
}
// A 404 indicates a Vault cluster was not found.
log.Printf("[INFO] Vault cluster (%s) not found, proceeding with create", clusterID)
} else {
return diag.Errorf("a Vault cluster with cluster_id=%q in project_id=%q already exists - to be managed via Terraform this resource needs to be imported into the State. Please see the resource documentation for hcp_vault_cluster for more information.", clusterID, loc.ProjectID)
}
// If no min_vault_version is set, an empty version is passed and the backend will set a default version.
var vaultVersion string
v, ok := d.GetOk("min_vault_version")
if ok {
vaultVersion = input.NormalizeVersion(v.(string))
}
publicEndpoint := d.Get("public_endpoint").(bool)
var httpProxyOption *vaultmodels.HashicorpCloudVault20201125HTTPProxyOption
proxyEndpoint, ok := d.GetOk("proxy_endpoint")
if ok {
httpProxyOption = vaultmodels.HashicorpCloudVault20201125HTTPProxyOption(strings.ToUpper(proxyEndpoint.(string))).Pointer()
}
cidrs := d.Get("ip_allowlist").([]interface{})
ipAllowlist, err := buildIPAllowlistVaultCluster(cidrs)
if err != nil {
return diag.Errorf("Invalid ip_allowlist for Vault cluster (%s): %v", clusterID, err)
}
// If the cluster has a primary_link, make sure the link is valid
diagErr, primaryClusterModel := validatePerformanceReplicationChecksAndReturnPrimaryIfAny(ctx, client, d)
if diagErr != nil {
return diagErr
}
log.Printf("[INFO] Creating Vault cluster (%s)", clusterID)
var vaultCluster *vaultmodels.HashicorpCloudVault20201125InputCluster
if getPrimaryLinkIfAny(d) != "" {
primaryClusterSharedLoc := &sharedmodels.HashicorpCloudLocationLocation{
OrganizationID: primaryClusterModel.Location.OrganizationID,
ProjectID: primaryClusterModel.Location.ProjectID,
Region: &sharedmodels.HashicorpCloudLocationRegion{
Provider: primaryClusterModel.Location.Region.Provider,
Region: primaryClusterModel.Location.Region.Region,
},
}
primaryClusterLink := newLink(primaryClusterSharedLoc, VaultClusterResourceType, primaryClusterModel.ID)
var pathsFilter *vaultmodels.HashicorpCloudVault20201125ClusterPerformanceReplicationPathsFilter
mode := vaultmodels.HashicorpCloudVault20201125ClusterPerformanceReplicationPathsFilterModeDENY
if paths, ok := d.GetOk("paths_filter"); ok {
pathStrings := getPathStrings(paths)
pathsFilter = &vaultmodels.HashicorpCloudVault20201125ClusterPerformanceReplicationPathsFilter{
Mode: &mode,
Paths: pathStrings,
}
}
vaultCluster = &vaultmodels.HashicorpCloudVault20201125InputCluster{
Config: &vaultmodels.HashicorpCloudVault20201125InputClusterConfig{
VaultConfig: &vaultmodels.HashicorpCloudVault20201125VaultConfig{
// Secondary clusters inherit InitialVersion from their primary's current version
InitialVersion: primaryClusterModel.CurrentVersion,
},
Tier: primaryClusterModel.Config.Tier,
NetworkConfig: &vaultmodels.HashicorpCloudVault20201125InputNetworkConfig{
NetworkID: hvn.ID,
PublicIpsEnabled: publicEndpoint,
HTTPProxyOption: httpProxyOption,
IPAllowlist: ipAllowlist,
},
},
ID: clusterID,
Location: locInternal,
PerformanceReplicationPrimaryCluster: &vaultmodels.HashicorpCloudInternalLocationLink{
Description: primaryClusterLink.Description,
ID: primaryClusterLink.ID,
Location: &vaultmodels.HashicorpCloudInternalLocationLocation{
OrganizationID: primaryClusterLink.Location.OrganizationID,
ProjectID: primaryClusterLink.Location.ProjectID,
Region: &vaultmodels.HashicorpCloudInternalLocationRegion{
Provider: primaryClusterLink.Location.Region.Provider,
Region: primaryClusterLink.Location.Region.Region,
},
},
Type: primaryClusterLink.Type,
UUID: primaryClusterLink.UUID,
},
PerformanceReplicationPathsFilter: pathsFilter,
}
} else {
if _, ok := d.GetOk("paths_filter"); ok {
return diag.Errorf("only performance replication secondaries may specify a paths_filter")
}
var tier *vaultmodels.HashicorpCloudVault20201125Tier
t, ok := d.GetOk("tier")
if ok {
tier = vaultmodels.HashicorpCloudVault20201125Tier(strings.ToUpper(t.(string))).Pointer()
}
vaultCluster = &vaultmodels.HashicorpCloudVault20201125InputCluster{
Config: &vaultmodels.HashicorpCloudVault20201125InputClusterConfig{
VaultConfig: &vaultmodels.HashicorpCloudVault20201125VaultConfig{
InitialVersion: vaultVersion,
},
Tier: tier,
NetworkConfig: &vaultmodels.HashicorpCloudVault20201125InputNetworkConfig{
NetworkID: hvn.ID,
PublicIpsEnabled: publicEndpoint,
HTTPProxyOption: httpProxyOption,
IPAllowlist: ipAllowlist,
},
},
ID: clusterID,
Location: locInternal,
}
}
if metricsConfig != nil {
vaultCluster.Config.MetricsConfig = metricsConfig
}
if auditConfig != nil {
vaultCluster.Config.AuditLogExportConfig = auditConfig
}
payload, err := clients.CreateVaultCluster(ctx, client, loc, vaultCluster)
if err != nil {
return diag.Errorf("unable to create Vault cluster (%s): %v", clusterID, err)
}
link := newLink(loc, VaultClusterResourceType, clusterID)
url, err := linkURL(link)
if err != nil {
return diag.FromErr(err)
}
d.SetId(url)
// Wait for the Vault cluster to be created.
if err := clients.WaitForOperation(ctx, client, "create Vault cluster", loc, payload.Operation.ID); err != nil {
return diag.Errorf("unable to create Vault cluster (%s): %v", payload.ClusterID, err)
}
log.Printf("[INFO] Created Vault cluster (%s)", payload.ClusterID)
// Get the created Vault cluster.
cluster, err := clients.GetVaultClusterByID(ctx, client, loc, payload.ClusterID)
if err != nil {
return diag.Errorf("unable to retrieve Vault cluster (%s): %v", payload.ClusterID, err)
}
clusterRegionShared := &sharedmodels.HashicorpCloudLocationRegion{}
if cluster.Location.Region != nil {
clusterRegionShared.Provider = cluster.Location.Region.Provider
clusterRegionShared.Region = cluster.Location.Region.Region
}
clusterLocationShared := &sharedmodels.HashicorpCloudLocationLocation{
OrganizationID: cluster.Location.OrganizationID,
ProjectID: cluster.Location.ProjectID,
Region: clusterRegionShared,
}
// If we pass the major version upgrade configuration we need to update it after the creation of the cluster,
// since the cluster is created by default to automatic upgrade
if mvuConfig != nil {
_, err := clients.UpdateVaultMajorVersionUpgradeConfig(ctx, client, clusterLocationShared, payload.ClusterID, mvuConfig)
if err != nil {
return diag.Errorf("error updating Vault cluster major version upgrade config (%s): %v", payload.ClusterID, err)
}
// refresh the created Vault cluster.
cluster, err = clients.GetVaultClusterByID(ctx, client, loc, payload.ClusterID)
if err != nil {
return diag.Errorf("unable to retrieve Vault cluster (%s): %v", payload.ClusterID, err)
}
}
if err := setVaultClusterResourceData(d, cluster); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceVaultClusterRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*clients.Client)
link, err := buildLinkFromURL(d.Id(), VaultClusterResourceType, client.Config.OrganizationID)
if err != nil {
return diag.FromErr(err)
}
clusterID := link.ID
loc := link.Location
log.Printf("[INFO] Reading Vault cluster (%s) [project_id=%s, organization_id=%s]", clusterID, loc.ProjectID, loc.OrganizationID)
cluster, err := clients.GetVaultClusterByID(ctx, client, loc, clusterID)
if err != nil {
if clients.IsResponseCodeNotFound(err) {
log.Printf("[WARN] Vault cluster (%s) not found, removing from state", clusterID)
d.SetId("")
return nil
}
return diag.Errorf("unable to fetch Vault cluster (%s): %v", clusterID, err)
}
// The Vault cluster was already deleted, remove from state.
if *cluster.State == vaultmodels.HashicorpCloudVault20201125ClusterStateDELETING {
log.Printf("[WARN] Vault cluster (%s) failed to provision, removing from state", clusterID)
d.SetId("")
return nil
}
// Cluster found, update resource data.
if err := setVaultClusterResourceData(d, cluster); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceVaultClusterUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*clients.Client)
link, err := buildLinkFromURL(d.Id(), VaultClusterResourceType, client.Config.OrganizationID)
if err != nil {
return diag.FromErr(err)
}
clusterID := link.ID
loc := link.Location
log.Printf("[INFO] Reading Vault cluster (%s) [project_id=%s, organization_id=%s]", clusterID, loc.ProjectID, loc.OrganizationID)
cluster, err := clients.GetVaultClusterByID(ctx, client, loc, clusterID)
if err != nil {
if clients.IsResponseCodeNotFound(err) {
log.Printf("[WARN] Vault cluster (%s) not found, removing from state", clusterID)
d.SetId("")
return nil
}
return diag.Errorf("unable to fetch Vault cluster (%s): %v", clusterID, err)
}
clusterRegionShared := &sharedmodels.HashicorpCloudLocationRegion{}
if cluster.Location.Region != nil {
clusterRegionShared.Provider = cluster.Location.Region.Provider
clusterRegionShared.Region = cluster.Location.Region.Region
}
clusterLocationShared := &sharedmodels.HashicorpCloudLocationLocation{
OrganizationID: cluster.Location.OrganizationID,
ProjectID: cluster.Location.ProjectID,
Region: clusterRegionShared,
}
// Confirm at least one modifiable field has changed
if !d.HasChanges("tier", "public_endpoint", "proxy_endpoint", "ip_allowlist", "paths_filter", "metrics_config", "audit_log_config", "major_version_upgrade_config") {
return nil
}
// Get metrics audit config and mvu config first so we can validate and fail faster
mvuConfig, diagErr := getMajorVersionUpgradeConfig(d)
if diagErr != nil {
return diagErr
}
if d.HasChange("tier") || d.HasChange("public_endpoint") || d.HasChange("proxy_endpoint") || d.HasChange("ip_allowlist") || d.HasChange("metrics_config") || d.HasChange("audit_log_config") {
diagErr := updateVaultClusterConfig(ctx, client, d, cluster, clusterID)
if diagErr != nil {
return diagErr
}
}
if d.HasChange("paths_filter") {
if paths, ok := d.GetOk("paths_filter"); ok {
// paths_filter is present. Check that it is a secondary, then update.
if _, ok := d.GetOk("primary_link"); !ok {
return diag.Errorf("only performance replication secondaries may specify a paths_filter")
}
// Invoke update paths filter endpoint.
pathStrings := getPathStrings(paths)
mode := vaultmodels.HashicorpCloudVault20201125ClusterPerformanceReplicationPathsFilterModeDENY
updateResp, err := clients.UpdateVaultPathsFilter(ctx, client, clusterLocationShared, clusterID, vaultmodels.HashicorpCloudVault20201125ClusterPerformanceReplicationPathsFilter{
Mode: &mode,
Paths: pathStrings,
})
if err != nil {
return diag.Errorf("error updating Vault cluster paths filter (%s): %v", clusterID, err)
}
// Wait for the update paths filter operation.
if err := clients.WaitForOperation(ctx, client, "update Vault cluster paths filter", clusterLocationShared, updateResp.Operation.ID); err != nil {
return diag.Errorf("unable to update Vault cluster paths filter (%s): %v", clusterID, err)
}
} else {
// paths_filter is not present. Delete the paths_filter.
deleteResp, err := clients.DeleteVaultPathsFilter(ctx, client, clusterLocationShared, clusterID)
if err != nil {
return diag.Errorf("error deleting Vault cluster paths filter (%s): %v", clusterID, err)
}
// Wait for the delete paths filter operation.
if err := clients.WaitForOperation(ctx, client, "delete Vault cluster paths filter", clusterLocationShared, deleteResp.Operation.ID); err != nil {
return diag.Errorf("unable to delete Vault cluster paths filter (%s): %v", clusterID, err)
}
}
}
if mvuConfig != nil {
_, err := clients.UpdateVaultMajorVersionUpgradeConfig(ctx, client, clusterLocationShared, clusterID, mvuConfig)
if err != nil {
return diag.Errorf("error updating Vault cluster major version upgrade config (%s): %v", clusterID, err)
}
}
// Get the updated Vault cluster.
cluster, err = clients.GetVaultClusterByID(ctx, client, loc, clusterID)
if err != nil {
return diag.Errorf("unable to retrieve Vault cluster (%s): %v", clusterID, err)
}
if err := setVaultClusterResourceData(d, cluster); err != nil {
return diag.FromErr(err)
}
return nil
}
func resourceVaultClusterDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*clients.Client)
link, err := buildLinkFromURL(d.Id(), VaultClusterResourceType, client.Config.OrganizationID)
if err != nil {
return diag.FromErr(err)
}
clusterID := link.ID
loc := link.Location
log.Printf("[INFO] Deleting Vault cluster (%s)", clusterID)
deleteResp, err := clients.DeleteVaultCluster(ctx, client, loc, clusterID)
if err != nil {
if clients.IsResponseCodeNotFound(err) {
log.Printf("[WARN] Vault cluster (%s) not found, so no action was taken", clusterID)
return nil
}
return diag.Errorf("unable to delete Vault cluster (%s): %v", clusterID, err)
}
// Wait for the delete cluster operation.
if err := clients.WaitForOperation(ctx, client, "delete Vault cluster", loc, deleteResp.Operation.ID); err != nil {
return diag.Errorf("unable to delete Vault cluster (%s): %v", clusterID, err)
}
return nil
}
func updateVaultClusterConfig(ctx context.Context, client *clients.Client, d *schema.ResourceData, cluster *vaultmodels.HashicorpCloudVault20201125Cluster, clusterID string) diag.Diagnostics {
metricsConfig, diagErr := getObservabilityConfig("metrics_config", d)
if diagErr != nil {
return diagErr
}
auditConfig, diagErr := getObservabilityConfig("audit_log_config", d)
if diagErr != nil {
return diagErr
}
isSecondary := false
destTier := getClusterTier(d)
publicIpsEnabled := getPublicIpsEnabled(d)
httpProxyOption := getHTTPProxyOption(d)
ipAllowlist, diagErr := getIPAllowlist(d, clusterID)
if diagErr != nil {
return diagErr
}
clusterSharedLoc := &sharedmodels.HashicorpCloudLocationLocation{