This repository has been archived by the owner on Sep 14, 2021. It is now read-only.
forked from hashicorp/terraform-provider-tfe
/
data_source_workspace_ids.go
85 lines (68 loc) · 1.81 KB
/
data_source_workspace_ids.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
package tfe
import (
"fmt"
tfe "github.com/hashicorp/go-tfe"
"github.com/hashicorp/terraform/helper/schema"
)
func dataSourceTFEWorkspaceIDs() *schema.Resource {
return &schema.Resource{
Read: dataSourceTFEWorkspaceIDsRead,
Schema: map[string]*schema.Schema{
"names": {
Type: schema.TypeList,
Elem: &schema.Schema{Type: schema.TypeString},
Required: true,
},
"organization": {
Type: schema.TypeString,
Required: true,
},
"ids": {
Type: schema.TypeMap,
Computed: true,
},
"external_ids": {
Type: schema.TypeMap,
Computed: true,
},
},
}
}
func dataSourceTFEWorkspaceIDsRead(d *schema.ResourceData, meta interface{}) error {
tfeClient := meta.(*tfe.Client)
// Get the organization.
organization := d.Get("organization").(string)
// Create a map with all the names we are looking for.
var id string
names := make(map[string]bool)
for _, name := range d.Get("names").([]interface{}) {
id += name.(string)
names[name.(string)] = true
}
// Create two maps to hold the resuls.
ids := make(map[string]string, len(names))
externalIDs := make(map[string]string, len(names))
options := tfe.WorkspaceListOptions{}
for {
wl, err := tfeClient.Workspaces.List(ctx, organization, options)
if err != nil {
return fmt.Errorf("Error retrieving workspaces: %v", err)
}
for _, w := range wl.Items {
if names["*"] || names[w.Name] {
ids[w.Name] = organization + "/" + w.Name
externalIDs[w.Name] = w.ID
}
}
// Exit the loop when we've seen all pages.
if wl.CurrentPage >= wl.TotalPages {
break
}
// Update the page number to get the next page.
options.PageNumber = wl.NextPage
}
d.Set("ids", ids)
d.Set("external_ids", externalIDs)
d.SetId(fmt.Sprintf("%s/%d", organization, schema.HashString(id)))
return nil
}