forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 1
/
data_source_google_folder.go
108 lines (89 loc) · 2.47 KB
/
data_source_google_folder.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
package google
import (
"fmt"
"strings"
"github.com/hashicorp/terraform/helper/schema"
resourceManagerV2Beta1 "google.golang.org/api/cloudresourcemanager/v2beta1"
)
func dataSourceGoogleFolder() *schema.Resource {
return &schema.Resource{
Read: dataSourceFolderRead,
Schema: map[string]*schema.Schema{
"folder": {
Type: schema.TypeString,
Required: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"parent": {
Type: schema.TypeString,
Computed: true,
},
"display_name": {
Type: schema.TypeString,
Computed: true,
},
"lifecycle_state": {
Type: schema.TypeString,
Computed: true,
},
"create_time": {
Type: schema.TypeString,
Computed: true,
},
"lookup_organization": {
Type: schema.TypeBool,
Optional: true,
Default: false,
},
"organization": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceFolderRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
folderName := d.Get("folder").(string)
folder, err := config.clientResourceManagerV2Beta1.Folders.Get(canonicalFolderName(folderName)).Do()
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Folder Not Found : %s", folderName))
}
d.SetId(GetResourceNameFromSelfLink(folder.Name))
d.Set("name", folder.Name)
d.Set("parent", folder.Parent)
d.Set("display_name", folder.DisplayName)
d.Set("lifecycle_state", folder.LifecycleState)
d.Set("create_time", folder.CreateTime)
if v, ok := d.GetOk("lookup_organization"); ok && v.(bool) {
organization, err := lookupOrganizationName(folder, config)
if err != nil {
return err
}
d.Set("organization", organization)
}
return nil
}
func canonicalFolderName(ba string) string {
if strings.HasPrefix(ba, "folders/") {
return ba
}
return "folders/" + ba
}
func lookupOrganizationName(folder *resourceManagerV2Beta1.Folder, config *Config) (string, error) {
parent := folder.Parent
if parent == "" || strings.HasPrefix(parent, "organizations/") {
return parent, nil
} else if strings.HasPrefix(parent, "folders/") {
parentFolder, err := config.clientResourceManagerV2Beta1.Folders.Get(parent).Do()
if err != nil {
return "", fmt.Errorf("Error getting parent folder '%s': %s", parent, err)
}
return lookupOrganizationName(parentFolder, config)
} else {
return "", fmt.Errorf("Unknown parent type '%s' on folder '%s'", parent, folder.Name)
}
}