forked from scastria/terraform-provider-konnect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_source_role.go
95 lines (92 loc) · 2.47 KB
/
data_source_role.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
package konnect
import (
"bytes"
"context"
"encoding/json"
"fmt"
"github.com/csechrist/terraform-provider-konnect/konnect/client"
"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"
"net/http"
)
func dataSourceRole() *schema.Resource {
return &schema.Resource{
ReadContext: dataSourceRoleRead,
Schema: map[string]*schema.Schema{
"entity_type_display_name": {
Type: schema.TypeString,
Required: true,
ValidateFunc: validation.StringInSlice([]string{client.ControlPlanesDisplayName, client.ServicesDisplayName}, false),
},
"display_name": {
Type: schema.TypeString,
Required: true,
},
"entity_type_name": {
Type: schema.TypeString,
Computed: true,
},
"name": {
Type: schema.TypeString,
Computed: true,
},
"description": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func dataSourceRoleRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
var diags diag.Diagnostics
c := m.(*client.Client)
entityTypeDisplayName := d.Get("entity_type_display_name").(string)
displayName := d.Get("display_name").(string)
body, err := c.HttpRequest(ctx, false, http.MethodGet, client.RolePath, nil, nil, &bytes.Buffer{})
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
retVals := &client.RoleCollection{}
err = json.NewDecoder(body).Decode(retVals)
if err != nil {
d.SetId("")
return diag.FromErr(err)
}
// Find requested role group by display name
var foundGroup *client.RoleGroup
foundGroup = nil
foundGroupName := ""
for k, g := range *retVals {
if g.DisplayName == entityTypeDisplayName {
foundGroup = &g
foundGroupName = k
break
}
}
if foundGroup == nil {
d.SetId("")
return diag.FromErr(fmt.Errorf("No role exists with that filter criteria"))
}
// Find requested role by display name
var foundRole *client.Role
foundRole = nil
foundRoleName := ""
for k, r := range (*retVals)[foundGroupName].RoleMap {
if r.DisplayName == displayName {
foundRole = &r
foundRoleName = k
break
}
}
if foundRole == nil {
d.SetId("")
return diag.FromErr(fmt.Errorf("No role exists with that filter criteria"))
}
d.Set("entity_type_name", foundGroupName)
d.Set("name", foundRoleName)
d.Set("description", foundRole.Description)
d.SetId(foundGroupName + client.IdSeparator + foundRoleName)
return diags
}