-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathresource_tfe_registry_module.go
More file actions
746 lines (638 loc) · 23.6 KB
/
resource_tfe_registry_module.go
File metadata and controls
746 lines (638 loc) · 23.6 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
// Copyright IBM Corp. 2018, 2025
// SPDX-License-Identifier: MPL-2.0
// NOTE: This is a legacy resource and should be migrated to the Plugin
// Framework if substantial modifications are planned. See
// docs/new-resources.md if planning to use this code as boilerplate for
// a new resource.
package provider
import (
"context"
"errors"
"fmt"
"log"
"strings"
"time"
tfe "github.com/hashicorp/go-tfe"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"github.com/hashicorp/terraform-provider-tfe/internal/provider/helpers"
)
func resourceTFERegistryModule() *schema.Resource {
return &schema.Resource{
Create: resourceTFERegistryModuleCreate,
Read: resourceTFERegistryModuleRead,
Update: resourceTFERegistryModuleUpdate,
Delete: resourceTFERegistryModuleDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceTFERegistryModuleImporter,
},
CustomizeDiff: func(c context.Context, d *schema.ResourceDiff, meta interface{}) error {
if err := validateNameAndProvider(d); err != nil {
return err
}
if err := validateVcsRepo(d); err != nil {
return err
}
return validateTestConfig(d)
},
Identity: &schema.ResourceIdentity{
SchemaFunc: func() map[string]*schema.Schema {
return map[string]*schema.Schema{
"id": {
Type: schema.TypeString,
RequiredForImport: true,
},
"hostname": {
Type: schema.TypeString,
OptionalForImport: true,
},
"organization": {
Type: schema.TypeString,
RequiredForImport: true,
},
"registry_name": {
Type: schema.TypeString,
RequiredForImport: true,
},
"namespace": {
Type: schema.TypeString,
RequiredForImport: true,
},
"name": {
Type: schema.TypeString,
RequiredForImport: true,
},
"module_provider": {
Type: schema.TypeString,
RequiredForImport: true,
},
}
},
},
Schema: map[string]*schema.Schema{
"organization": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"module_provider": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
RequiredWith: []string{"organization", "name"},
},
"name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"publishing_mechanism": {
Type: schema.TypeString,
Computed: true,
},
"vcs_repo": {
Type: schema.TypeList,
Optional: true,
ForceNew: true,
MinItems: 1,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"display_identifier": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"identifier": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
},
"oauth_token_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
ConflictsWith: []string{"vcs_repo.0.github_app_installation_id"},
},
"github_app_installation_id": {
Type: schema.TypeString,
ForceNew: true,
Optional: true,
ConflictsWith: []string{"vcs_repo.0.oauth_token_id"},
AtLeastOneOf: []string{"vcs_repo.0.oauth_token_id", "vcs_repo.0.github_app_installation_id"},
},
"branch": {
Type: schema.TypeString,
Optional: true,
},
"tags": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"source_directory": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"tag_prefix": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
},
},
},
"namespace": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
RequiredWith: []string{"registry_name"},
},
"no_code": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
},
"registry_name": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
RequiredWith: []string{"module_provider"},
ValidateFunc: validation.StringInSlice(
[]string{"private", "public"},
true,
),
},
"test_config": {
Type: schema.TypeList,
Optional: true,
Computed: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"tests_enabled": {
Type: schema.TypeBool,
Optional: true,
},
"agent_execution_mode": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ValidateFunc: validation.StringInSlice(
[]string{"agent", "remote"},
false,
),
},
"agent_pool_id": {
Type: schema.TypeString,
Optional: true,
},
},
},
},
"initial_version": {
Type: schema.TypeString,
Optional: true,
},
},
}
}
func resourceTFERegistryModuleCreateWithVCS(v interface{}, meta interface{}, d *schema.ResourceData) (*tfe.RegistryModule, error) {
config := meta.(ConfiguredClient)
// Create module with VCS repo configuration block.
options := tfe.RegistryModuleCreateWithVCSConnectionOptions{}
vcsRepo := v.([]interface{})[0].(map[string]interface{})
var testConfig map[string]interface{}
if tc, ok := d.GetOk("test_config"); ok {
if tc.([]interface{})[0] == nil {
return nil, fmt.Errorf("tests_enabled must be provided when configuring a test_config")
}
testConfig = tc.([]interface{})[0].(map[string]interface{})
}
orgName, err := config.schemaOrDefaultOrganization(d)
if err != nil {
log.Printf("[WARN] Error getting organization name: %s", err)
}
if name, ok := d.GetOk("name"); ok {
options.Name = tfe.String(name.(string))
}
if provider, ok := d.GetOk("module_provider"); ok {
options.Provider = tfe.String(provider.(string))
}
options.VCSRepo = &tfe.RegistryModuleVCSRepoOptions{
Identifier: tfe.String(vcsRepo["identifier"].(string)),
GHAInstallationID: tfe.String(vcsRepo["github_app_installation_id"].(string)),
DisplayIdentifier: tfe.String(vcsRepo["display_identifier"].(string)),
OrganizationName: tfe.String(orgName),
}
tags, tagsOk := vcsRepo["tags"].(bool)
branch, branchOk := vcsRepo["branch"].(string)
initialVersion, initialVersionOk := d.GetOk("initial_version")
if tagsOk {
options.VCSRepo.Tags = tfe.Bool(tags)
}
if branchOk && branch != "" {
options.VCSRepo.Branch = tfe.String(branch)
if initialVersionOk && initialVersion.(string) != "" {
options.InitialVersion = tfe.String(initialVersion.(string))
}
}
tagPrefix, tagPrefixOk := vcsRepo["tag_prefix"].(string)
sourceDirectory, sourceDirectoryOk := vcsRepo["source_directory"].(string)
if tagPrefixOk && tagPrefix != "" {
options.VCSRepo.TagPrefix = tfe.String(tagPrefix)
}
if sourceDirectoryOk && sourceDirectory != "" {
options.VCSRepo.SourceDirectory = tfe.String(sourceDirectory)
}
if vcsRepo["oauth_token_id"] != nil && vcsRepo["oauth_token_id"].(string) != "" {
options.VCSRepo.OAuthTokenID = tfe.String(vcsRepo["oauth_token_id"].(string))
}
if testConfig != nil {
options.TestConfig = &tfe.RegistryModuleTestConfigOptions{}
if testsEnabled, ok := testConfig["tests_enabled"].(bool); ok {
options.TestConfig.TestsEnabled = tfe.Bool(testsEnabled)
}
if agentExecutionMode, ok := testConfig["agent_execution_mode"].(string); ok && agentExecutionMode != "" {
mode := tfe.AgentExecutionMode(agentExecutionMode)
options.TestConfig.AgentExecutionMode = &mode
}
// Handle agent pool ID - only set if explicitly provided and not empty
if agentPoolID, ok := testConfig["agent_pool_id"].(string); ok && agentPoolID != "" {
options.TestConfig.AgentPoolID = tfe.String(agentPoolID)
}
}
log.Printf("[DEBUG] Create registry module from repository %s", *options.VCSRepo.Identifier)
registryModule, err := config.Client.RegistryModules.CreateWithVCSConnection(ctx, options)
if err != nil {
return nil, fmt.Errorf(
"Error creating registry module from repository %s: %w", *options.VCSRepo.Identifier, err)
}
return registryModule, nil
}
func resourceTFERegistryModuleCreateWithoutVCS(meta interface{}, d *schema.ResourceData) (*tfe.RegistryModule, error) {
config := meta.(ConfiguredClient)
options := tfe.RegistryModuleCreateOptions{
Name: tfe.String(d.Get("name").(string)),
Provider: tfe.String(d.Get("module_provider").(string)),
}
if v, ok := d.GetOk("no_code"); ok {
log.Println("[WARN] The attribute no_code is deprecated as of release 0.44.0 and may be removed in a future version. The preferred way to create a no-code registry module is to use the tfe_no_code_module resource.")
options.NoCode = tfe.Bool(v.(bool))
}
if registryName, ok := d.GetOk("registry_name"); ok {
options.RegistryName = tfe.RegistryName(registryName.(string))
if registryName.(string) == "public" {
options.Namespace = d.Get("namespace").(string)
}
}
orgName := d.Get("organization").(string)
log.Printf("[DEBUG] Create registry module named %s", *options.Name)
registryModule, err := config.Client.RegistryModules.Create(ctx, orgName, options)
if err != nil {
return nil, fmt.Errorf("Error creating registry module %s: %w", *options.Name, err)
}
return registryModule, nil
}
func resourceTFERegistryModuleCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(ConfiguredClient)
var registryModule *tfe.RegistryModule
var err error
if v, ok := d.GetOk("vcs_repo"); ok {
registryModule, err = resourceTFERegistryModuleCreateWithVCS(v, meta, d)
} else {
registryModule, err = resourceTFERegistryModuleCreateWithoutVCS(meta, d)
}
if err != nil {
return err
}
var rmID tfe.RegistryModuleID
err = retry.Retry(time.Duration(5)*time.Minute, func() *retry.RetryError {
rmID = tfe.RegistryModuleID{
Organization: registryModule.Organization.Name,
Name: registryModule.Name,
Provider: registryModule.Provider,
Namespace: registryModule.Namespace,
RegistryName: registryModule.RegistryName,
}
_, err := config.Client.RegistryModules.Read(ctx, rmID)
if err != nil {
if strings.Contains(strings.ToLower(err.Error()), "not found") {
return retry.RetryableError(err)
}
return retry.NonRetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("Error while waiting for module %s/%s to be ingested: %w", registryModule.Organization.Name, registryModule.Name, err)
}
d.SetId(registryModule.ID)
// Set these fields so we have the information needed to read the registry module
d.Set("name", registryModule.Name)
d.Set("module_provider", registryModule.Provider)
d.Set("organization", registryModule.Organization.Name)
d.Set("namespace", registryModule.Namespace)
d.Set("registry_name", registryModule.RegistryName)
err = helpers.WriteRegistryIdentity(d, registryModule.ID, rmID, config.Client.BaseURL().Host)
if err != nil {
return err
}
return resourceTFERegistryModuleRead(d, meta)
}
func resourceTFERegistryModuleUpdate(d *schema.ResourceData, meta interface{}) error {
config := meta.(ConfiguredClient)
options := tfe.RegistryModuleUpdateOptions{}
if v, ok := d.GetOk("no_code"); ok {
log.Println("[WARN] The attribute no_code is deprecated as of release 0.44.0 and may be removed in a future version. The preferred way to create a no-code registry module is to use the tfe_no_code_module resource.")
options.NoCode = tfe.Bool(v.(bool))
}
var registryModule *tfe.RegistryModule
var err error
rmID := tfe.RegistryModuleID{
Organization: d.Get("organization").(string),
Name: d.Get("name").(string),
Provider: d.Get("module_provider").(string),
Namespace: d.Get("namespace").(string),
RegistryName: tfe.RegistryName(d.Get("registry_name").(string)),
}
if v, ok := d.GetOk("vcs_repo"); ok { //nolint:nestif
vcsRepo := v.([]interface{})[0].(map[string]interface{})
options.VCSRepo = &tfe.RegistryModuleVCSRepoUpdateOptions{}
tags, tagsOk := vcsRepo["tags"].(bool)
branch, branchOk := vcsRepo["branch"].(string)
if tagsOk {
options.VCSRepo.Tags = tfe.Bool(tags)
}
if branchOk {
options.VCSRepo.Branch = tfe.String(branch)
}
}
if v, ok := d.GetOk("test_config"); ok {
if v.([]interface{})[0] == nil {
return fmt.Errorf("tests_enabled must be provided when configuring a test_config")
}
testConfig := v.([]interface{})[0].(map[string]interface{})
options.TestConfig = &tfe.RegistryModuleTestConfigOptions{}
if testsEnabled, ok := testConfig["tests_enabled"].(bool); ok {
options.TestConfig.TestsEnabled = tfe.Bool(testsEnabled)
}
if agentExecutionMode, ok := testConfig["agent_execution_mode"].(string); ok && agentExecutionMode != "" {
mode := tfe.AgentExecutionMode(agentExecutionMode)
options.TestConfig.AgentExecutionMode = &mode
}
handleAgentPoolID(testConfig, d, options.TestConfig)
}
err = retry.Retry(time.Duration(5)*time.Minute, func() *retry.RetryError {
registryModule, err = config.Client.RegistryModules.Update(ctx, rmID, options)
if err != nil {
return retry.RetryableError(err)
}
return nil
})
if err != nil {
return fmt.Errorf("Error while waiting for module %s/%s to be updated: %w", rmID.Organization, rmID.Name, err)
}
d.SetId(registryModule.ID)
return resourceTFERegistryModuleRead(d, meta)
}
func resourceTFERegistryModuleRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(ConfiguredClient)
log.Printf("[DEBUG] Read registry module: %s", d.Id())
// Get the fields we need to read the registry module
rmID := tfe.RegistryModuleID{
Organization: d.Get("organization").(string),
Name: d.Get("name").(string),
Provider: d.Get("module_provider").(string),
Namespace: d.Get("namespace").(string),
RegistryName: tfe.RegistryName(d.Get("registry_name").(string)),
}
registryModule, err := config.Client.RegistryModules.Read(ctx, rmID)
if err != nil {
if err == tfe.ErrResourceNotFound {
log.Printf("[DEBUG] Registry module %s no longer exists", d.Id())
d.SetId("")
return nil
}
return fmt.Errorf("Error reading registry module %s: %w", d.Id(), err)
}
err = helpers.WriteRegistryIdentity(d, registryModule.ID, rmID, config.Client.BaseURL().Host)
if err != nil {
return err
}
// Update the config
log.Printf("[DEBUG] Update config for registry module: %s", d.Id())
d.Set("name", registryModule.Name)
d.Set("module_provider", registryModule.Provider)
d.Set("organization", registryModule.Organization.Name)
d.Set("namespace", registryModule.Namespace)
d.Set("registry_name", registryModule.RegistryName)
d.Set("no_code", registryModule.NoCode)
d.Set("publishing_mechanism", registryModule.PublishingMechanism)
// Set VCS repo options.
var vcsRepo []interface{}
if registryModule.VCSRepo != nil {
vcsConfig := map[string]interface{}{
"identifier": registryModule.VCSRepo.Identifier,
"oauth_token_id": registryModule.VCSRepo.OAuthTokenID,
"github_app_installation_id": registryModule.VCSRepo.GHAInstallationID,
"display_identifier": registryModule.VCSRepo.DisplayIdentifier,
"branch": registryModule.VCSRepo.Branch,
"tags": registryModule.VCSRepo.Tags,
"source_directory": registryModule.VCSRepo.SourceDirectory,
"tag_prefix": registryModule.VCSRepo.TagPrefix,
}
vcsRepo = append(vcsRepo, vcsConfig)
d.Set("vcs_repo", vcsRepo)
}
var testConfig []interface{}
if registryModule.TestConfig != nil {
testConfigValues := map[string]interface{}{
"tests_enabled": registryModule.TestConfig.TestsEnabled,
}
if registryModule.TestConfig.AgentExecutionMode != nil {
testConfigValues["agent_execution_mode"] = *registryModule.TestConfig.AgentExecutionMode
}
if registryModule.TestConfig.AgentPoolID != nil {
testConfigValues["agent_pool_id"] = *registryModule.TestConfig.AgentPoolID
} else {
testConfigValues["agent_pool_id"] = ""
}
testConfig = append(testConfig, testConfigValues)
}
d.Set("test_config", testConfig)
return nil
}
func resourceTFERegistryModuleDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(ConfiguredClient)
// Fields required to delete registry module by provider
// To delete by name, Provider field is not required
rModID := tfe.RegistryModuleID{
Organization: d.Get("organization").(string),
Name: d.Get("name").(string),
Provider: d.Get("module_provider").(string),
Namespace: d.Get("namespace").(string),
RegistryName: tfe.RegistryName(d.Get("registry_name").(string)),
}
if v, ok := d.GetOk("module_provider"); ok && v.(string) != "" {
log.Printf("[DEBUG] Delete registry module by provider: %s", d.Id())
err := config.Client.RegistryModules.DeleteProvider(ctx, rModID)
if err != nil && !errors.Is(err, tfe.ErrResourceNotFound) {
return fmt.Errorf("error deleting registry module provider: %w", err)
}
} else {
log.Printf("[DEBUG] Delete registry module by name: %s", d.Id())
err := config.Client.RegistryModules.DeleteByName(ctx, rModID)
if err != nil && !errors.Is(err, tfe.ErrResourceNotFound) {
return fmt.Errorf("Error deleting registry module %s: %w", d.Id(), err)
}
}
return nil
}
func validateNameAndProvider(d *schema.ResourceDiff) error {
configMap := d.GetRawConfig().AsValueMap()
nameValue, hasName := configMap["name"]
providerValue, hasProvider := configMap["module_provider"]
vcsRepoValue := configMap["vcs_repo"]
nameProvided := hasName && !nameValue.IsNull()
providerProvided := hasProvider && !providerValue.IsNull()
if vcsRepoValue.LengthInt() == 0 {
return nil
}
vcsRepoBlock := vcsRepoValue.AsValueSlice()[0]
sourceDirectory := vcsRepoBlock.GetAttr("source_directory")
if sourceDirectory.IsNull() || (sourceDirectory.IsKnown() && sourceDirectory.AsString() == "") {
return nil
}
// Check if identifier follows terraform-<provider>-<name> convention
displayIdentifier := vcsRepoBlock.GetAttr("display_identifier")
if displayIdentifier.IsNull() || !displayIdentifier.IsKnown() {
return nil
}
// Extract repo name from "org/repo" format
repoName := displayIdentifier.AsString()
if idx := strings.LastIndex(repoName, "/"); idx >= 0 {
repoName = repoName[idx+1:]
}
nameParts := strings.SplitN(repoName, "-", 3)
followsConvention := len(nameParts) == 3
// Standard repos: neither name nor provider is required
if followsConvention {
return nil
}
// Non-standard repos: requires both name and provider fields
if !followsConvention && (!nameProvided || !providerProvided) {
return fmt.Errorf("name and module_provider are required when the repository name does not follow the terraform-<provider>-<name> convention")
}
return nil
}
func resourceTFERegistryModuleImporter(ctx context.Context, d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
// First we'll check for an identity
identity, err := d.Identity()
if err != nil {
return nil, fmt.Errorf("error reading registry module identity: %w", err)
}
if externalID := identity.Get("id").(string); externalID != "" {
// We are importing by identity
// This only supported when using an import block, since import blocks
// are the only way to specify an identity. Importing via TF CLI does
// not support specifying an identity.
d.SetId(externalID)
d.Set("organization", identity.Get("organization").(string))
d.Set("registry_name", identity.Get("registry_name").(string))
d.Set("namespace", identity.Get("namespace").(string))
d.Set("name", identity.Get("name").(string))
d.Set("module_provider", identity.Get("module_provider").(string))
// Exit early
return []*schema.ResourceData{d}, nil
}
registryModuleInfo := strings.SplitN(d.Id(), "/", 6)
if len(registryModuleInfo) == 4 {
// for format: <ORGANIZATION>/<REGISTRY MODULE NAME>/<REGISTRY MODULE PROVIDER>/<REGISTRY MODULE ID>
log.Printf("[WARN] The import format <ORGANIZATION>/<REGISTRY MODULE NAME>/<REGISTRY MODULE PROVIDER>/<REGISTRY MODULE ID> is deprecated as of release 0.33.0 and may be removed in a future version. The preferred format is <ORGANIZATION>/<REGISTRY_NAME>/<NAMESPACE>/<REGISTRY MODULE NAME>/<REGISTRY MODULE PROVIDER>/<REGISTRY MODULE ID>.")
d.Set("organization", registryModuleInfo[0])
d.Set("name", registryModuleInfo[1])
d.Set("module_provider", registryModuleInfo[2])
d.SetId(registryModuleInfo[3])
return []*schema.ResourceData{d}, nil
} else if len(registryModuleInfo) == 6 {
// for format: <ORGANIZATION>/<REGISTRY_NAME>/<NAMESPACE>/<REGISTRY MODULE NAME>/<REGISTRY MODULE PROVIDER>/<REGISTRY MODULE ID>
// see https://developer.hashicorp.com/terraform/cloud-docs/api-docs/private-registry/modules#get-a-module
d.Set("organization", registryModuleInfo[0])
d.Set("registry_name", registryModuleInfo[1])
d.Set("namespace", registryModuleInfo[2])
d.Set("name", registryModuleInfo[3])
d.Set("module_provider", registryModuleInfo[4])
d.SetId(registryModuleInfo[5])
return []*schema.ResourceData{d}, nil
}
return nil, fmt.Errorf(
"invalid registry module import format: %s (expected <ORGANIZATION>/<REGISTRY_NAME>/<NAMESPACE>/<REGISTRY MODULE NAME>/<REGISTRY MODULE PROVIDER>/<REGISTRY MODULE ID>)",
d.Id(),
)
}
func validateVcsRepo(d *schema.ResourceDiff) error {
vcsRepo, ok := d.GetRawConfig().AsValueMap()["vcs_repo"]
if !ok || vcsRepo.LengthInt() == 0 {
return nil
}
branchValue := vcsRepo.AsValueSlice()[0].GetAttr("branch")
tagsValue := vcsRepo.AsValueSlice()[0].GetAttr("tags")
if !tagsValue.IsNull() && tagsValue.False() && branchValue.IsNull() {
return fmt.Errorf("branch must be provided when tags is set to false")
}
if !tagsValue.IsNull() && !branchValue.IsNull() {
tags := tagsValue.True()
branch := branchValue.AsString()
// tags must be set to true or branch provided but not both
if tags && branch != "" {
return fmt.Errorf("tags must be set to false when a branch is provided")
} else if !tags && branch == "" {
return fmt.Errorf("tags must be set to true when no branch is provided")
}
}
return nil
}
func validateTestConfig(d *schema.ResourceDiff) error {
testConfig, ok := d.GetRawConfig().AsValueMap()["test_config"]
if !ok || testConfig.LengthInt() == 0 {
return nil
}
testConfigValue := testConfig.AsValueSlice()[0]
// Check if test_config block is empty (no tests_enabled field)
testsEnabledValue := testConfigValue.GetAttr("tests_enabled")
if testsEnabledValue.IsNull() {
return fmt.Errorf("tests_enabled must be provided when configuring a test_config")
}
agentExecutionModeValue := testConfigValue.GetAttr("agent_execution_mode")
agentPoolIDValue := testConfigValue.GetAttr("agent_pool_id")
// Skip validation if values are unknown (during plan phase)
if !agentExecutionModeValue.IsKnown() || !agentPoolIDValue.IsKnown() {
return nil
}
if !agentExecutionModeValue.IsNull() && !agentPoolIDValue.IsNull() {
executionMode := agentExecutionModeValue.AsString()
agentPoolID := agentPoolIDValue.AsString()
if executionMode == "remote" && agentPoolID != "" {
return fmt.Errorf("agent_pool_id cannot be set when agent_execution_mode is 'remote'")
}
}
return nil
}
func handleAgentPoolID(testConfig map[string]interface{}, d *schema.ResourceData, options *tfe.RegistryModuleTestConfigOptions) {
if agentPoolID, ok := testConfig["agent_pool_id"].(string); ok {
if agentPoolID != "" {
options.AgentPoolID = tfe.String(agentPoolID)
} else if d.HasChange("test_config.0.agent_pool_id") {
options.AgentPoolID = tfe.String("")
}
} else if d.HasChange("test_config.0.agent_pool_id") {
options.AgentPoolID = tfe.String("")
}
}